input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: What is difference between arm64 and armhf? <p>Raspberry Pi Type 3 has 64-bit CPU, but its architecture is not <code>arm64</code> but <code>armhf</code>. What is the difference between <code>arm64</code> and <code>armhf</code>?</p>
<p><code>armhf</code> stands for "arm hard float", and is the name given to <a href="https://www.debian.org/ports/#portlist-released" rel="noreferrer">a debian port</a> for arm processors (armv7+) that have hardware floating point support. </p> <p>On the beaglebone black, for example:</p> <pre><code>:~$ dpkg --print-architecture armhf </code></pre> <p>Although other commands (such as <code>uname -a</code> or <code>arch</code>) will just show <code>armv7l</code></p> <pre><code>:~$ cat /proc/cpuinfo processor : 0 model name : ARMv7 Processor rev 2 (v7l) BogoMIPS : 995.32 Features : half thumb fastmult vfp edsp thumbee neon vfpv3 tls ... </code></pre> <p>The <code>vfpv3</code> listed under <code>Features</code> is what refers to the <a href="https://developer.arm.com/technologies/floating-point" rel="noreferrer">floating point support.</a></p> <p>Incidentally, <code>armhf</code>, if your processor supports it, basically supersedes Raspbian, which if I understand correctly was <a href="https://wiki.debian.org/RaspberryPi" rel="noreferrer">mainly a rebuild</a> of <code>armhf</code> with work arounds to deal with the lack of floating point support on the original raspberry pi's. Nowdays, of course, there's a whole ecosystem build up around Raspbian, so they're probably not going to abandon it. However, this is partly why the beaglebone runs straight debian, and that's ok even if you're used to Raspbian, unless you want some of the special included non-free software such as Mathematica.</p>
{ "question_id": 37790029, "question_date": "2016-06-13T12:36:33.643Z", "question_score": 219, "tags": "linux|arm|debian|arm64", "answer_id": 48954012, "answer_date": "2018-02-23T18:18:16.547Z", "answer_score": 263 }
Please answer the following Stack Overflow question: Title: What is the difference between connection and read timeout for sockets? <p>3 questions:</p> <ol> <li><p>What is the difference between <strong>connection</strong> and <strong>read</strong> timeout for sockets?</p></li> <li><p>What does <strong>connection</strong> timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?</p></li> <li><p>What does <strong>read</strong> timeout set to "infinity" mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?</p></li> </ol>
<blockquote> <ol> <li>What is the difference between connection and read timeout for sockets?</li> </ol> </blockquote> <p>The connection timeout is the timeout in making the initial connection; i.e. completing the TCP connection handshake. The read timeout is the timeout on waiting to read data<sup>1</sup>. If the server (or network) fails to deliver any data &lt;timeout&gt; seconds after the client makes a socket <code>read</code> call, a read timeout error will be raised.</p> <blockquote> <ol start="2"> <li>What does connection timeout set to &quot;infinity&quot; mean? In what situation can it remain in an infinitive loop? and what can trigger that the infinity-loop dies?</li> </ol> </blockquote> <p>It means that the connection attempt can potentially block for ever. There is no infinite loop, but the attempt to connect can be unblocked by another thread closing the socket. (A <code>Thread.interrupt()</code> call may also do the trick ... not sure.)</p> <blockquote> <ol start="3"> <li>What does read timeout set to &quot;infinity&quot; mean? In what situation can it remain in an infinite loop? What can trigger that the infinite loop to end?</li> </ol> </blockquote> <p>It means that a call to <code>read</code> on the socket stream may block for ever. Once again there is no infinite loop, but the <code>read</code> can be unblocked by a <code>Thread.interrupt()</code> call, closing the socket, and (of course) the other end sending data or closing the connection.</p> <hr /> <p><sup>1 - It is not ... as one commenter thought ... the timeout on how long a socket can be open, or idle.</sup></p>
{ "question_id": 3069382, "question_date": "2010-06-18T12:04:08.463Z", "question_score": 219, "tags": "java|sockets|timeout|connection", "answer_id": 3069450, "answer_date": "2010-06-18T12:14:07.560Z", "answer_score": 280 }
Please answer the following Stack Overflow question: Title: How to get the <html> tag HTML with JavaScript / jQuery? <p>Using <code>$('html').html()</code> I can get the HTML within the <code>&lt;html&gt;</code> tag (<code>&lt;head&gt;</code>, <code>&lt;body&gt;</code>, etc.). But how can I get the actual HTML of the <code>&lt;html&gt;</code> tag (with attributes)?</p> <p>Alternatively, is it possible to get the entire HTML of the page (including doctype, <code>&lt;html&gt;</code>, etc.) with jQuery (or plain old JavaScript)?</p>
<p>The simplest way to get the <code>html</code> element natively is:</p> <pre><code>document.documentElement </code></pre> <p>Here's the reference: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document.documentElement">https://developer.mozilla.org/en-US/docs/Web/API/Document.documentElement</a>.</p> <p>UPDATE: To then grab the <code>html</code> element as a string you would do:</p> <pre><code>document.documentElement.outerHTML </code></pre>
{ "question_id": 4196971, "question_date": "2010-11-16T17:20:16.493Z", "question_score": 219, "tags": "javascript|jquery", "answer_id": 22873490, "answer_date": "2014-04-04T21:39:19.110Z", "answer_score": 413 }
Please answer the following Stack Overflow question: Title: How to get a variable name as a string in PHP? <p>Say i have this PHP code:</p> <pre><code>$FooBar = "a string"; </code></pre> <p>i then need a function like this:</p> <pre><code>print_var_name($FooBar); </code></pre> <p>which prints:</p> <pre><code>FooBar </code></pre> <p>Any Ideas how to achieve this? Is this even possible in PHP?</p>
<p>You could use <a href="http://php.net/get_defined_vars" rel="noreferrer">get_defined_vars()</a> to find the name of a variable that has the same value as the one you're trying to find the name of. Obviously this will not always work, since different variables often have the same values, but it's the only way I can think of to do this.</p> <p>Edit: get_defined_vars() doesn't seem to be working correctly, it returns 'var' because $var is used in the function itself. $GLOBALS seems to work so I've changed it to that.</p> <pre><code>function print_var_name($var) { foreach($GLOBALS as $var_name =&gt; $value) { if ($value === $var) { return $var_name; } } return false; } </code></pre> <p>Edit: to be clear, there is no good way to do this in PHP, which is probably because you shouldn't have to do it. There are probably better ways of doing what you're trying to do.</p>
{ "question_id": 255312, "question_date": "2008-11-01T00:28:31.960Z", "question_score": 219, "tags": "php", "answer_id": 255335, "answer_date": "2008-11-01T00:42:30.687Z", "answer_score": 49 }
Please answer the following Stack Overflow question: Title: Make Hibernate ignore instance variables that are not mapped <p>I thought hibernate takes into consideration only instance variables that are annotated with <code>@Column</code>. But strangely today when I added a variable (that is not mapped to any column, just a variable i need in the class), it is trying to include that variable in the select statement as a column name and throws the error -</p> <blockquote> <p>Unknown column 'team1_.agencyName' in 'field list'</p> </blockquote> <p>My class -</p> <pre><code>@Entity @Table(name=&quot;team&quot;) public class Team extends BaseObject implements Serializable { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id; @Column(length=50) private String name; @Column(length=10) private String code; @Column(name = &quot;agency_id&quot;) private Long agencyId; private String agencyName; //note: not annotated. } </code></pre> <p>FYI...I use the above class in another class with many to many mapping</p> <pre><code>@ManyToMany(fetch = FetchType.EAGER) @JoinTable( name=&quot;user_team&quot;, joinColumns = { @JoinColumn( name=&quot;user_id&quot;) }, inverseJoinColumns = @JoinColumn( name=&quot;team_id&quot;) ) public Set&lt;Team&gt; getTeams() { return teams; } </code></pre> <p>Why is this happening?!</p>
<p>JPA will use <em>all</em> properties of the class, unless you specifically mark them with <code>@Transient</code>:</p> <pre><code>@Transient private String agencyName; </code></pre> <p>The <code>@Column</code> annotation is purely optional, and is there to let you override the auto-generated column name. Furthermore, the <code>length</code> attribute of <code>@Column</code> is only used when auto-generating table definitions, it has no effect on the runtime.</p>
{ "question_id": 4662582, "question_date": "2011-01-11T20:59:04.503Z", "question_score": 219, "tags": "java|hibernate|jpa", "answer_id": 4662599, "answer_date": "2011-01-11T21:00:31.540Z", "answer_score": 464 }
Please answer the following Stack Overflow question: Title: SQL Server equivalent of MySQL's NOW()? <p>I'm a MySQL guy working on a SQL Server project, trying to get a datetime field to show the current time. In MySQL I'd use NOW() but it isn't accepting that.</p> <pre><code>INSERT INTO timelog (datetime_filed) VALUES (NOW()) </code></pre>
<p><code>getdate()</code> or <code>getutcdate()</code>.</p>
{ "question_id": 385042, "question_date": "2008-12-21T22:06:34.370Z", "question_score": 219, "tags": "sql|sql-server", "answer_id": 385051, "answer_date": "2008-12-21T22:12:15.217Z", "answer_score": 241 }
Please answer the following Stack Overflow question: Title: Why is __dirname not defined in node REPL? <p>From the node manual I see that I can get the directory of a file with <code>__dirname</code>, but from the REPL this seems to be undefined. Is this a misunderstanding on my side or where is the error?</p> <pre><code>$ node &gt; console.log(__dirname) ReferenceError: __dirname is not defined at repl:1:14 at REPLServer.eval (repl.js:80:21) at Interface.&lt;anonymous&gt; (repl.js:182:12) at Interface.emit (events.js:67:17) at Interface._onLine (readline.js:162:10) at Interface._line (readline.js:426:8) at Interface._ttyWrite (readline.js:603:14) at ReadStream.&lt;anonymous&gt; (readline.js:82:12) at ReadStream.emit (events.js:88:20) at ReadStream._emitKey (tty.js:320:10) </code></pre>
<p><code>__dirname</code> is only defined in scripts. It's not available in REPL.</p> <p>try make a script <code>a.js</code></p> <pre><code>console.log(__dirname); </code></pre> <p>and run it:</p> <pre><code>node a.js </code></pre> <p>you will see <code>__dirname</code> printed.</p> <p>Added background explanation: <code>__dirname</code> means 'The directory of this script'. In REPL, you don't have a script. Hence, <code>__dirname</code> would not have any real meaning.</p>
{ "question_id": 8817423, "question_date": "2012-01-11T10:05:46.610Z", "question_score": 219, "tags": "node.js", "answer_id": 8817507, "answer_date": "2012-01-11T10:12:01.573Z", "answer_score": 227 }
Please answer the following Stack Overflow question: Title: Chrome: console.log, console.debug are not working <p>Console.log and debug not printing, only return undefined. Why it can be? I've tried to re-install chrome, but it doesn't help.</p> <p>Here is screenshot from chrome's main page, so functions are not redefined in some code <img src="https://i.stack.imgur.com/bI8Oe.jpg" alt="console.log doesn&#39;t work"></p>
<p>Click “Default levels” and make sure that &quot;Verbose&quot; is checked. By default it is only set to show Errors and Warnings</p> <p>I came here with the same problem :/</p>
{ "question_id": 18760213, "question_date": "2013-09-12T09:17:04.067Z", "question_score": 219, "tags": "google-chrome|console", "answer_id": 18853868, "answer_date": "2013-09-17T15:26:04.653Z", "answer_score": 378 }
Please answer the following Stack Overflow question: Title: Is it possible to do a sparse checkout without checking out the whole repository first? <p>I'm working with a repository with a very large number of files that takes hours to checkout. I'm looking into the possibility of whether Git would work well with this kind of repository now that it supports sparse checkouts but every example that I can find does the following:</p> <pre><code>git clone &lt;path&gt; git config core.sparsecheckout true echo &lt;dir&gt; &gt; .git/info/sparse-checkout git read-tree -m -u HEAD </code></pre> <p>The problem with this sequence of commands is the original clone also does a checkout. If you add -n to the original clone command, then the read-tree command results in the following error:</p> <p>error: Sparse checkout leaves no entry on working directory</p> <p>How can do the sparse checkout without checking out all the files first?</p>
<p>Works in git 3.37.1</p> <pre><code>git clone --filter=blob:none --no-checkout --depth 1 --sparse &lt;project-url&gt; cd &lt;project&gt; </code></pre> <p>Specify folders you want to clone</p> <pre><code>git sparse-checkout add &lt;folder1&gt; &lt;folder2&gt; git checkout </code></pre>
{ "question_id": 4114887, "question_date": "2010-11-06T19:52:06.247Z", "question_score": 219, "tags": "git|sparse-checkout|git-sparse-checkout", "answer_id": 63786181, "answer_date": "2020-09-08T01:58:46.760Z", "answer_score": 30 }
Please answer the following Stack Overflow question: Title: How to listen for changes to a MongoDB collection? <p>I'm creating a sort of background job queue system with MongoDB as the data store. How can I &quot;listen&quot; for inserts to a MongoDB collection before spawning workers to process the job?</p> <p>Do I need to poll every few seconds to see if there are any changes from last time, or is there a way my script can wait for inserts to occur?</p> <p>This is a PHP project that I am working on, but feel free to answer in Ruby or language agnostic.</p>
<p>MongoDB has what is called <a href="http://www.mongodb.org/display/DOCS/Capped+Collections" rel="noreferrer"><code>capped collections</code></a> and <a href="http://www.mongodb.org/display/DOCS/Tailable+Cursors" rel="noreferrer"><code>tailable cursors</code></a> that allows MongoDB to push data to the listeners.</p> <p>A <code>capped collection</code> is essentially a collection that is a fixed size and only allows insertions. Here's what it would look like to create one:</p> <pre><code>db.createCollection("messages", { capped: true, size: 100000000 }) </code></pre> <h3>MongoDB Tailable cursors (<a href="http://jwage.com/post/30490196727/mongodb-tailable-cursors" rel="noreferrer">original post by Jonathan H. Wage</a>)</h3> <p><strong>Ruby</strong></p> <pre class="lang-rb prettyprint-override"><code>coll = db.collection('my_collection') cursor = Mongo::Cursor.new(coll, :tailable =&gt; true) loop do if doc = cursor.next_document puts doc else sleep 1 end end </code></pre> <p><strong>PHP</strong></p> <pre class="lang-php prettyprint-override"><code>$mongo = new Mongo(); $db = $mongo-&gt;selectDB('my_db') $coll = $db-&gt;selectCollection('my_collection'); $cursor = $coll-&gt;find()-&gt;tailable(true); while (true) { if ($cursor-&gt;hasNext()) { $doc = $cursor-&gt;getNext(); print_r($doc); } else { sleep(1); } } </code></pre> <p><strong>Python</strong> (by <a href="http://www.wombatnation.com" rel="noreferrer">Robert Stewart)</a></p> <pre class="lang-py prettyprint-override"><code>from pymongo import Connection import time db = Connection().my_db coll = db.my_collection cursor = coll.find(tailable=True) while cursor.alive: try: doc = cursor.next() print doc except StopIteration: time.sleep(1) </code></pre> <p><strong>Perl</strong> (by <a href="http://tong.ijenko.net" rel="noreferrer">Max</a>)</p> <pre class="lang-perl prettyprint-override"><code>use 5.010; use strict; use warnings; use MongoDB; my $db = MongoDB::Connection-&gt;new; my $coll = $db-&gt;my_db-&gt;my_collection; my $cursor = $coll-&gt;find-&gt;tailable(1); for (;;) { if (defined(my $doc = $cursor-&gt;next)) { say $doc; } else { sleep 1; } } </code></pre> <h3>Additional Resources:</h3> <p><a href="https://devcenter.heroku.com/articles/realtime-polyglot-app-node-ruby-mongodb-socketio" rel="noreferrer">Ruby/Node.js Tutorial which walks you through creating an application that listens to inserts in a MongoDB capped collection.</a></p> <p><a href="http://www.shtylman.com/archives/217" rel="noreferrer">An article talking about tailable cursors in more detail.</a></p> <p><a href="http://jwage.com/post/30490196727/mongodb-tailable-cursors" rel="noreferrer">PHP, Ruby, Python, and Perl examples of using tailable cursors.</a></p>
{ "question_id": 9691316, "question_date": "2012-03-13T20:09:59.853Z", "question_score": 219, "tags": "mongodb", "answer_id": 10325343, "answer_date": "2012-04-25T23:42:36.420Z", "answer_score": 106 }
Please answer the following Stack Overflow question: Title: Multiple calls to state updater from useState in component causes multiple re-renders <p>I'm trying React hooks for the first time and all seemed good until I realised that when I get data and update two different state variables (data and loading flag), my component (a data table) is rendered twice, even though both calls to the state updater are happening in the same function. Here is my api function which is returning both variables to my component.</p> <pre><code>const getData = url =&gt; { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); useEffect(async () =&gt; { const test = await api.get('/people') if(test.ok){ setLoading(false); setData(test.data.results); } }, []); return { data, loading }; }; </code></pre> <p>In a normal class component you'd make a single call to update the state which can be a complex object but the "hooks way" seems to be to split the state into smaller units, a side effect of which seems to be multiple re-renders when they are updated separately. Any ideas how to mitigate this?</p>
<p>You could combine the <code>loading</code> state and <code>data</code> state into one state object and then you could do one <code>setState</code> call and there will only be one render. </p> <p><strong>Note:</strong> Unlike the <code>setState</code> in class components, the <code>setState</code> returned from <code>useState</code> doesn't merge objects with existing state, it replaces the object entirely. If you want to do a merge, you would need to read the previous state and merge it with the new values yourself. Refer to the <a href="https://reactjs.org/docs/hooks-reference.html#functional-updates" rel="noreferrer">docs</a>.</p> <p>I wouldn't worry too much about calling renders excessively until you have determined you have a performance problem. Rendering (in the React context) and committing the virtual DOM updates to the real DOM are different matters. The rendering here is referring to generating virtual DOMs, and not about updating the browser DOM. React may batch the <code>setState</code> calls and update the browser DOM with the final new state.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const {useState, useEffect} = React; function App() { const [userRequest, setUserRequest] = useState({ loading: false, user: null, }); useEffect(() =&gt; { // Note that this replaces the entire object and deletes user key! setUserRequest({ loading: true }); fetch('https://randomuser.me/api/') .then(results =&gt; results.json()) .then(data =&gt; { setUserRequest({ loading: false, user: data.results[0], }); }); }, []); const { loading, user } = userRequest; return ( &lt;div&gt; {loading &amp;&amp; 'Loading...'} {user &amp;&amp; user.name.first} &lt;/div&gt; ); } ReactDOM.render(&lt;App /&gt;, document.querySelector('#app'));</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://unpkg.com/[email protected]/umd/react.development.js"&gt;&lt;/script&gt; &lt;script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"&gt;&lt;/script&gt; &lt;div id="app"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <h2>Alternative - write your own state merger hook</h2> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const {useState, useEffect} = React; function useMergeState(initialState) { const [state, setState] = useState(initialState); const setMergedState = newState =&gt; setState(prevState =&gt; Object.assign({}, prevState, newState) ); return [state, setMergedState]; } function App() { const [userRequest, setUserRequest] = useMergeState({ loading: false, user: null, }); useEffect(() =&gt; { setUserRequest({ loading: true }); fetch('https://randomuser.me/api/') .then(results =&gt; results.json()) .then(data =&gt; { setUserRequest({ loading: false, user: data.results[0], }); }); }, []); const { loading, user } = userRequest; return ( &lt;div&gt; {loading &amp;&amp; 'Loading...'} {user &amp;&amp; user.name.first} &lt;/div&gt; ); } ReactDOM.render(&lt;App /&gt;, document.querySelector('#app'));</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://unpkg.com/[email protected]/umd/react.development.js"&gt;&lt;/script&gt; &lt;script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"&gt;&lt;/script&gt; &lt;div id="app"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
{ "question_id": 53574614, "question_date": "2018-12-01T20:06:59.097Z", "question_score": 219, "tags": "javascript|reactjs|react-hooks", "answer_id": 53575023, "answer_date": "2018-12-01T21:03:12.257Z", "answer_score": 195 }
Please answer the following Stack Overflow question: Title: HttpListener Access Denied <p>I am writing an HTTP server in C#.</p> <p>When I try to execute the function <code>HttpListener.Start()</code> I get an <code>HttpListenerException</code> saying </p> <blockquote> <p>"Access Denied".</p> </blockquote> <p>When I run the app in admin mode in windows 7 it works fine.</p> <p>Can I make it run without admin mode? if yes how? If not how can I make the app change to admin mode after start running?</p> <pre><code>using System; using System.Net; namespace ConsoleApplication1 { class Program { private HttpListener httpListener = null; static void Main(string[] args) { Program p = new Program(); p.Server(); } public void Server() { this.httpListener = new HttpListener(); if (httpListener.IsListening) throw new InvalidOperationException("Server is currently running."); httpListener.Prefixes.Clear(); httpListener.Prefixes.Add("http://*:4444/"); try { httpListener.Start(); //Throws Exception } catch (HttpListenerException ex) { if (ex.Message.Contains("Access is denied")) { return; } else { throw; } } } } } </code></pre>
<p>Yes you can run HttpListener in non-admin mode. All you need to do is grant permissions to the particular URL. e.g.</p> <pre class="lang-sh prettyprint-override"><code>netsh http add urlacl url=http://+:80/MyUri user=DOMAIN\user </code></pre> <p>Documentation is <a href="http://msdn.microsoft.com/en-us/library/ms733768.aspx" rel="noreferrer">here</a>.</p>
{ "question_id": 4019466, "question_date": "2010-10-25T22:44:16.493Z", "question_score": 219, "tags": "windows-7|c#-4.0|uac|httplistener", "answer_id": 4115328, "answer_date": "2010-11-06T21:44:59.120Z", "answer_score": 343 }
Please answer the following Stack Overflow question: Title: C# binary literals <p>Is there a way to write binary literals in C#, like prefixing hexadecimal with 0x? 0b doesn't work.</p> <p>If not, what is an easy way to do it? Some kind of string conversion?</p>
<p>C# <a href="https://github.com/dotnet/roslyn/issues/2136" rel="noreferrer">7.0</a> supports <a href="https://github.com/dotnet/roslyn/issues/215" rel="noreferrer">binary literals</a> (and optional digit separators via underscore characters).</p> <p>An example:</p> <pre><code>int myValue = 0b0010_0110_0000_0011; </code></pre> <p>You can also find more information on the <a href="https://github.com/dotnet/roslyn" rel="noreferrer">Roslyn GitHub page</a>.</p>
{ "question_id": 594720, "question_date": "2009-02-27T13:26:47.627Z", "question_score": 219, "tags": "c#|syntax|binary", "answer_id": 23546326, "answer_date": "2014-05-08T15:37:59.730Z", "answer_score": 174 }
Please answer the following Stack Overflow question: Title: Right mime type for SVG images with fonts embedded <p>This is the usual SVG mime type:</p> <pre><code>image/svg+xml </code></pre> <p>And it works great. However, when embedding an SVG font, chrome tells you the mime type is incorrect, obviously because you return a font instead of an image.</p> <p>Is there any universal mime type? is chrome wrong? is <code>application/svg+xml</code> accepted somehow?</p> <p>I guess this is still a gray area in HTML5 but someone here might know.</p>
<p>There's only <a href="http://www.w3.org/TR/SVG11/mimereg.html" rel="noreferrer">one registered mediatype</a> for SVG, and that's the one you listed, <code>image/svg+xml</code>. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the <code>image/svg+xml</code> mediatype.</p>
{ "question_id": 11918977, "question_date": "2012-08-12T01:15:31.910Z", "question_score": 219, "tags": "html|svg|font-face|mime-types", "answer_id": 11930514, "answer_date": "2012-08-13T08:20:29.017Z", "answer_score": 283 }
Please answer the following Stack Overflow question: Title: How to select an element with 2 classes <p>i have this elements</p> <pre><code>&lt;div class=&quot;a b&quot;&gt;&lt;/div&gt; &lt;div class=&quot;b&quot;&gt;&lt;/div&gt; &lt;div class=&quot;a&quot;&gt;&lt;/div&gt; </code></pre> <p>I want apply to element with class a and b the color #666. How can I do this with CSS?</p>
<p>You can chain class selectors <em>without a space</em> between them:</p> <pre><code>.a.b { color: #666; } </code></pre> <p>Note that, if it matters to you, IE6 treats <code>.a.b</code> as <code>.b</code>, so in that browser both <code>div.a.b</code> and <code>div.b</code> will have gray text. See <a href="https://stackoverflow.com/questions/3772290/css-selector-that-applies-to-elements-with-two-classes/3772305#3772305">this answer</a> for a comparison between proper browsers and IE6.</p>
{ "question_id": 5116288, "question_date": "2011-02-25T10:48:20.773Z", "question_score": 219, "tags": "css|css-selectors", "answer_id": 5116305, "answer_date": "2011-02-25T10:50:01.693Z", "answer_score": 378 }
Please answer the following Stack Overflow question: Title: Are PostgreSQL column names case-sensitive? <p>I have a db table say, <code>persons</code> in Postgres handed down by another team that has a column name say, <code>"first_Name"</code>. Now am trying to use PG commander to query this table on this column-name.</p> <pre><code>select * from persons where first_Name="xyz"; </code></pre> <p>And it just returns</p> <blockquote> <p>ERROR: column "first_Name" does not exist</p> </blockquote> <p>Not sure if I am doing something silly or is there a workaround to this problem that I am missing?</p>
<p><strong>Identifiers</strong> (including column names) that are <strong>not</strong> double-quoted are folded to lowercase in PostgreSQL. Column names that were created with <strong>double-quotes</strong> and thereby retained uppercase letters (and/or other syntax violations) have to be double-quoted for the rest of their life:</p> <pre><code>&quot;first_Name&quot; </code></pre> <p><strong>Values</strong> (string literals / constants) are enclosed in <em><strong>single quotes</strong></em>:</p> <pre><code>'xyz' </code></pre> <p>So, <em>yes</em>, PostgreSQL column names are case-sensitive (when double-quoted):</p> <pre><code>SELECT * FROM persons WHERE &quot;first_Name&quot; = 'xyz'; </code></pre> <p><a href="https://www.postgresql.org/docs/current/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS" rel="noreferrer">Read the manual on identifiers here.</a></p> <p>My standing advice is to use legal, lower-case names exclusively so double-quoting is not needed.</p>
{ "question_id": 20878932, "question_date": "2014-01-02T08:21:15.287Z", "question_score": 219, "tags": "sql|postgresql|identifier|case-sensitive|case-insensitive", "answer_id": 20880247, "answer_date": "2014-01-02T09:53:47.493Z", "answer_score": 410 }
Please answer the following Stack Overflow question: Title: How to fix error with xml2-config not found when installing PHP from sources? <p>When I try to install php 5.3 stable from source on Ubuntu (downloading compressed installation file from <a href="http://www.php.net/downloads.php">http://www.php.net/downloads.php</a>) and I run <code>./configure</code> I get this error:</p> <pre><code>configure: error: xml2-config not found. Please check your libxml2 installation. </code></pre>
<p>All you need to do instal install package libxml2-dev for example:</p> <pre><code>sudo apt-get install libxml2-dev </code></pre> <p>On CentOS/RHEL:</p> <pre><code>sudo yum install libxml2-devel </code></pre>
{ "question_id": 19904083, "question_date": "2013-11-11T10:30:04.823Z", "question_score": 219, "tags": "php|compilation|php-5.3", "answer_id": 19904084, "answer_date": "2013-11-11T10:30:04.823Z", "answer_score": 465 }
Please answer the following Stack Overflow question: Title: Assert an Exception using XUnit <p>I am a newbie to XUnit and Moq. I have a method which takes string as an argument.How to handle an exception using XUnit.</p> <pre><code>[Fact] public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException() { //arrange ProfileRepository profiles = new ProfileRepository(); //act var result = profiles.GetSettingsForUserID(""); //assert //The below statement is not working as expected. Assert.Throws&lt;ArgumentException&gt;(() =&gt; profiles.GetSettingsForUserID("")); } </code></pre> <p>Method under test</p> <pre><code>public IEnumerable&lt;Setting&gt; GetSettingsForUserID(string userid) { if (string.IsNullOrWhiteSpace(userid)) throw new ArgumentException("User Id Cannot be null"); var s = profiles.Where(e =&gt; e.UserID == userid).SelectMany(e =&gt; e.Settings); return s; } </code></pre>
<p>The <a href="https://github.com/xunit/assert.xunit/blob/main/ExceptionAsserts.cs#L27" rel="noreferrer">Assert.Throws</a> expression will catch the exception and assert the type. You are however calling the method under test outside of the assert expression and thus failing the test case.</p> <pre><code>[Fact] public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException() { //arrange ProfileRepository profiles = new ProfileRepository(); // act &amp; assert Assert.Throws&lt;ArgumentException&gt;(() =&gt; profiles.GetSettingsForUserID(&quot;&quot;)); } </code></pre> <p>If bent on following AAA you can extract the action into its own variable.</p> <pre><code>[Fact] public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException() { //arrange ProfileRepository profiles = new ProfileRepository(); //act Action act = () =&gt; profiles.GetSettingsForUserID(&quot;&quot;); //assert ArgumentException exception = Assert.Throws&lt;ArgumentException&gt;(act); //The thrown exception can be used for even more detailed assertions. Assert.Equal(&quot;expected error message here&quot;, exception.Message); } </code></pre> <p>Note how the exception can also be used for more detailed assertions</p> <p>If testing asynchronously, <a href="https://github.com/xunit/assert.xunit/blob/main/ExceptionAsserts.cs#L70" rel="noreferrer">Assert.ThrowsAsync</a> follows similarly to the previously given example, except that the assertion should be awaited,</p> <pre><code>public async Task Some_Async_Test() { //... //Act Func&lt;Task&gt; act = () =&gt; subject.SomeMethodAsync(); //Assert var exception = await Assert.ThrowsAsync&lt;InvalidOperationException&gt;(act); //... } </code></pre>
{ "question_id": 45017295, "question_date": "2017-07-10T16:30:07.177Z", "question_score": 219, "tags": "c#|unit-testing|xunit", "answer_id": 45017575, "answer_date": "2017-07-10T16:46:36.990Z", "answer_score": 361 }
Please answer the following Stack Overflow question: Title: Using querySelectorAll to retrieve direct children <p>I am able to do this:</p> <pre class="lang-html prettyprint-override"><code>&lt;div id="myDiv"&gt; &lt;div class="foo"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <pre class="lang-js prettyprint-override"><code>myDiv = getElementById("myDiv"); myDiv.querySelectorAll("#myDiv &gt; .foo"); </code></pre> <p>That is, I can successfully retrieve all the direct children of the <code>myDiv</code> element that have class <code>.foo</code>.</p> <p>The problem is, it bothers me that I must include the <code>#myDiv</code> in the selector, because I am running the query on the <code>myDiv</code> element (so it is obviously redundant).</p> <p>I ought to be able to leave the <code>#myDiv</code> off, but then the selector is not legal syntax since it starts with a <code>&gt;</code>.</p> <p>Does anyone know how to write a selector which gets just the direct children of the element that the selector is running on?</p>
<p>Good question. At the time it was asked, a universally-implemented way to do &quot;combinator rooted queries&quot; (as <a href="http://ejohn.org/blog/thoughts-on-queryselectorall/" rel="noreferrer">John Resig called them</a>) did not exist.</p> <p>Now the <a href="https://drafts.csswg.org/selectors-4/#the-scope-pseudo" rel="noreferrer">:scope</a> pseudo-class has been introduced. It is not <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/:scope#Browser_compatibility" rel="noreferrer">supported</a> on [pre-Chrominum] versions of Edge or IE, but has been supported by Safari for a few years already. Using that, your code could become:</p> <pre class="lang-js prettyprint-override"><code>let myDiv = getElementById(&quot;myDiv&quot;); myDiv.querySelectorAll(&quot;:scope &gt; .foo&quot;); </code></pre> <p>Note that in some cases you can also skip <code>.querySelectorAll</code> and use other good old-fashioned DOM API features. For example, instead of <code>myDiv.querySelectorAll(&quot;:scope &gt; *&quot;)</code> you could just write <code>myDiv.children</code>, for example.</p> <p>Otherwise if you can't yet rely on <code>:scope</code>, I can't think of another way to handle your situation without adding more custom filter logic (e.g. find <code>myDiv.getElementsByClassName(&quot;foo&quot;)</code> whose <code>.parentNode === myDiv</code>), and obviously not ideal if you're trying to support one code path that really just wants to take an arbitrary selector string as input and a list of matches as output! But if like me you ended up asking this question simply because you got stuck thinking &quot;all you had was a hammer&quot; don't forget there are a variety of <em>other</em> tools the DOM offers too.</p>
{ "question_id": 3680876, "question_date": "2010-09-09T21:57:27.463Z", "question_score": 219, "tags": "javascript|dom|css-selectors", "answer_id": 17206138, "answer_date": "2013-06-20T05:45:33.840Z", "answer_score": 233 }
Please answer the following Stack Overflow question: Title: How can prepared statements protect from SQL injection attacks? <p>How do <a href="http://en.wikipedia.org/wiki/Prepared_statement" rel="noreferrer">prepared statements</a> help us prevent <a href="http://en.wikipedia.org/wiki/SQL_injection" rel="noreferrer">SQL injection</a> attacks?</p> <p>Wikipedia says:</p> <blockquote> <p>Prepared statements are resilient against SQL injection, because parameter values, which are transmitted later using a different protocol, need not be correctly escaped. If the original statement template is not derived from external input, SQL injection cannot occur.</p> </blockquote> <p>I cannot see the reason very well. What would be a simple explanation in an easy English and some examples?</p>
<p>The idea is very simple - the query and the data are sent to the database server <em>separately</em>.<br> That's all.</p> <p>The root of the SQL injection problem is in the <strong>mixing of the code and the data.</strong> </p> <p>In fact, our SQL query is <strong>a legitimate program</strong>. And we are creating such a program dynamically, adding some data on the fly. Thus, the data may interfere with the <em>program code</em> and even alter it, as every SQL injection example shows it (all examples in PHP/Mysql):</p> <pre><code>$expected_data = 1; $query = "SELECT * FROM users where id=$expected_data"; </code></pre> <p>will produce a regular query </p> <pre><code>SELECT * FROM users where id=1 </code></pre> <p>while this code</p> <pre><code>$spoiled_data = "1; DROP TABLE users;" $query = "SELECT * FROM users where id=$spoiled_data"; </code></pre> <p>will produce a malicious sequence</p> <pre><code>SELECT * FROM users where id=1; DROP TABLE users; </code></pre> <p>It works because we are adding the data directly to the program body and it becomes a part of the program, so the data may alter the program, and depending on the data passed, we will either have a regular output or a table <code>users</code> deleted.</p> <p>While <strong>in case of prepared statements we don't alter our program, it remains intact</strong><br> That's the point. </p> <p>We are sending a <em>program</em> to the server first</p> <pre><code>$db-&gt;prepare("SELECT * FROM users where id=?"); </code></pre> <p>where the data is substituted by some <em>variable</em> called a parameter or a placeholder.</p> <p>Note that exactly the same query is sent to the server, without any data in it! And then we're sending the data with the <em>second</em> request, essentially separated from the query itself:</p> <pre><code>$db-&gt;execute($data); </code></pre> <p>so it can't alter our program and do any harm.<br> Quite simple - isn't it? </p> <p>The only thing I have to add that always omitted in the every manual:</p> <p>Prepared statements can protect only <em>data literals</em>, but cannot be used with any other query part.<br> So, once we have to add, say, a dynamical <strong>identifier</strong> - a field name, for example - prepared statements can't help us. I've <a href="https://stackoverflow.com/q/8255054/285587"><strong>explained the matter recently</strong></a>, so I won't repeat myself. </p>
{ "question_id": 8263371, "question_date": "2011-11-24T23:17:08.220Z", "question_score": 219, "tags": "sql|security|sql-injection|prepared-statement", "answer_id": 8265319, "answer_date": "2011-11-25T06:04:42.063Z", "answer_score": 369 }
Please answer the following Stack Overflow question: Title: How to send parameters from a notification-click to an activity? <p>I can find a way to send parameters to my activity from my notification.</p> <p>I have a service that creates a notification. When the user clicks on the notification I want to open my main activity with some special parameters. E.g an item id, so my activity can load and present a special item detail view. More specific, I'm downloading a file, and when the file is downloaded I want the notification to have an intent that when clicked it opens my activity in a special mode. I have tried to use <code>putExtra</code> on my intent, but cant seem to extract it, so I think I'm doing it wrong.</p> <p>Code from my service that creates the Notification:</p> <pre><code> // construct the Notification object. final Notification notif = new Notification(R.drawable.icon, tickerText, System.currentTimeMillis()); final RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_notification_layout); contentView.setImageViewResource(R.id.image, R.drawable.icon); contentView.setTextViewText(R.id.text, tickerText); contentView.setProgressBar(R.id.progress,100,0, false); notif.contentView = contentView; Intent notificationIntent = new Intent(context, Main.class); notificationIntent.putExtra("item_id", "1001"); // &lt;-- HERE I PUT THE EXTRA VALUE PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0); notif.contentIntent = contentIntent; nm.notify(id, notif); </code></pre> <p>Code from my Activity that tries to fetch the extra parameter from the notification:</p> <pre><code> public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Bundle extras = getIntent().getExtras(); if(extras != null){ Log.i( "dd","Extra:" + extras.getString("item_id") ); } </code></pre> <p>The extras is always null and I never gets anything into my log.</p> <p>Btw... the <code>onCreate</code> is only run when my activity starts, if my activity is already started I also want to collect the extras and present my activity according to the item_id I receive.</p> <p>Any ideas?</p>
<p>Take a look at this guide (<a href="http://developer.android.com/guide/topics/ui/notifiers/notifications.html" rel="noreferrer">creating a notification</a>) and to samples ApiDemos "StatusBarNotifications" and "NotificationDisplay".</p> <p>For managing if the activity is already running you have two ways:</p> <ol> <li><p>Add <strong>FLAG_ACTIVITY_SINGLE_TOP</strong> flag to the Intent when launching the activity, and then in the activity class implement <strong>onNewIntent(Intent intent)</strong> event handler, that way you can access the new intent that was called for the activity (which is not the same as just calling getIntent(), this will always return the first Intent that launched your activity.</p></li> <li><p>Same as number one, but instead of adding a flag to the Intent you must add <strong>"singleTop"</strong> in your activity AndroidManifest.xml.</p></li> </ol> <p>If you use intent extras, remeber to call <code>PendingIntent.getActivity()</code> with the flag <code>PendingIntent.FLAG_UPDATE_CURRENT</code>, otherwise the same extras will be reused for every notification.</p>
{ "question_id": 1198558, "question_date": "2009-07-29T07:29:21.523Z", "question_score": 219, "tags": "android|android-intent|bundle|notifications", "answer_id": 1201239, "answer_date": "2009-07-29T15:50:39.157Z", "answer_score": 252 }
Please answer the following Stack Overflow question: Title: How to rollback just one step using rake db:migrate <p>After adding migration files in the <code>db/migrate</code> folder and running <code>rake db:migrate</code>, I want get back to the previous step, I think using <code>VERSION=n</code> is the right way to do that, but I don't know the correct value of n to use. Is there any command to check the current n value?</p> <p>It would be great if anyone could provide full instructions on how to use <code>rake db:migrate</code>.</p>
<p>For starters</p> <p><code>rake db:rollback</code> will get you back one step</p> <p>then </p> <p><code>rake db:rollback STEP=n</code></p> <p>Will roll you back <code>n</code> migrations where <code>n</code> is the number of recent migrations you want to rollback. </p> <p>More references <a href="http://en.wikibooks.org/wiki/Ruby_on_Rails/ActiveRecord/Migrations">here</a>.</p>
{ "question_id": 4352848, "question_date": "2010-12-04T09:28:31.447Z", "question_score": 219, "tags": "ruby-on-rails|rake|dbmigrate", "answer_id": 4352910, "answer_date": "2010-12-04T09:43:35.820Z", "answer_score": 400 }
Please answer the following Stack Overflow question: Title: How do I update a Linq to SQL dbml file? <p>How do I update a Linq to SQL .dbml file?</p>
<p>There are three ways to keep the model in sync.</p> <ol> <li><p>Delete the modified tables from the designer, and drag them back onto the designer surface from the Database Explorer. I have found that, for this to work reliably, you have to:</p> <p>a. Refresh the database schema in the Database Explorer (right-click, refresh)<br> b. Save the designer after deleting the tables<br> c. Save again after dragging the tables back.</p> <p><strong>Note</strong> though that if you have modified any properties (for instance, turning off the child property of an association), this will obviously lose those modifications&nbsp;&mdash; you'll have to make them again.</p></li> <li><p>Use SQLMetal to regenerate the schema from your database. I have seen a number of blog posts that show <a href="http://blogs.vertigo.com/personal/petar/Blog/Lists/Posts/Post.aspx?ID=11" rel="noreferrer">how to script this</a>. </p></li> <li><p>Make changes directly in the Properties pane of the DBML. This works for simple changes, like allowing nulls on a field.</p></li> </ol> <p>The DBML designer is not installed by default in Visual Studio 2015, 2017 or 2019. You will have to close VS, start the VS installer and modify your installation. The <strong>LINQ to SQL tools</strong> is the feature you must install. For VS 2017/2019, you can find it under <em>Individual Components > Code Tools</em>.</p>
{ "question_id": 1110171, "question_date": "2009-07-10T15:18:22.920Z", "question_score": 219, "tags": "linq-to-sql", "answer_id": 1110258, "answer_date": "2009-07-10T15:30:37.877Z", "answer_score": 277 }
Please answer the following Stack Overflow question: Title: jQuery’s .bind() vs. .on() <p>I found two great articles talking about the new function <code>.on()</code>: <a href="http://www.jquery4u.com/jquery-functions/on-vs-live-review/#.UCEUoKPrFI0" rel="noreferrer">jquery4u.com</a>, <a href="http://www.elijahmanor.com/2012/02/differences-between-jquery-bind-vs-live.html" rel="noreferrer">elijahmanor.com</a>.</p> <p>Is there any way where the <code>.bind()</code> still is better to use than <code>.on()</code>?</p> <p>For example, I have a sample code that look like this:</p> <pre><code>$("#container").click( function( e ) {} ) </code></pre> <p>You can note that I just have one item retrieved by the selector and in my case, the <code>&lt;div&gt;</code> named <code>#container</code> already exists when my page was loaded; not added dynamically. It’s important to mention that I use the latest version of jQuery: 1.7.2.</p> <p>For that sample, should <code>.on()</code> be used instead of <code>.bind()</code> even if I don’t use the other features provided by the <code>.on()</code> function?</p>
<p>Internally, <code>.bind</code> maps directly to <code>.on</code> in the current version of jQuery. (The same goes for <code>.live</code>.) So there is a tiny but practically insignificant performance hit if you use <code>.bind</code> instead.</p> <p>However, <code>.bind</code> may be removed from future versions at any time. There is no reason to keep using <code>.bind</code> and every reason to prefer <code>.on</code> instead.</p>
{ "question_id": 11847021, "question_date": "2012-08-07T13:24:14.807Z", "question_score": 219, "tags": "javascript|jquery|jquery-selectors", "answer_id": 11847066, "answer_date": "2012-08-07T13:26:35.457Z", "answer_score": 329 }
Please answer the following Stack Overflow question: Title: iOS 7: UITableView shows under status bar <p>The first screen of my application is a <code>UITableViewController</code> without a navigation bar, which means that the content flows under the status bar so there's a lot of text collisions. I've adjusted both the properties for <code>Under top bars</code> and <code>Adjust scroll view insets</code> which do actually stop it from scrolling under, but at the cost of keeping the top of the table view under. I've attempted to set the <code>UITableView</code> frame to offset by 20 pixels, but it doesn't appear to take effect and as I currently need the app to be compatible with iOS 6 I can't jump to iOS 7 Storyboards to force autolayout to use the top height guide. Has anyone found a solution that works for both versions?</p> <p>Things I've tried: setting <code>edgesForExtendedLayout</code>, changing the settings within Storyboard for <code>Under top bars</code> and <code>Adjust scroll view</code>, forcing the frame to a new area.</p> <p>A picture is worth a thousand words: <img src="https://i.stack.imgur.com/6JcDv.png" alt="Status bar flow under"></p>
<p>For anyone interested in replicating this, simply follow these steps:</p> <ol> <li>Create a new iOS project</li> <li>Open the main storyboard and delete the default/initial <code>UIViewController</code></li> <li>Drag out a new <code>UITableViewController</code> from the Object Library</li> <li>Set it as the initial view controller</li> <li>Feed the table some test data</li> </ol> <p>If you follow the above steps, when you run the app, you will see that nothing, including tweaking Xcode's checkboxes to "Extend Edges Under {Top, Bottom, Opaque} Bars" works to stop the first row from appearing under the status bar, nor can you address this programmatically.</p> <p>E.g. In the above scenario, the following will have <strong>no</strong> effect:</p> <pre><code>// These do not work self.edgesForExtendedLayout=UIRectEdgeNone; self.extendedLayoutIncludesOpaqueBars=NO; self.automaticallyAdjustsScrollViewInsets=NO; </code></pre> <p>This issue can be very frustrating, and I believe it is a bug on Apple's end, especially because it shows up in their own pre-wired <code>UITableViewController</code> from the object library.</p> <p>I disagree with everyone who is trying to solve this by using any form of "Magic Numbers" e.g. "use a delta of 20px". This kind of tightly coupled programming is definitely not what Apple wants us to do here.</p> <p>I have discovered two solutions to this problem:</p> <ul> <li><p><strong>Preserving the <code>UITableViewController</code>'s scene</strong>:<br> If you would like to keep the <code>UITableViewController</code> in the storyboard, without manually placing it into another view, you can embed the <code>UITableViewController</code> in a <code>UINavigationController</code> (Editor > Embed In > Navigation Controller) and uncheck "Shows Navigation Bar" in the inspector. This solves the issue with no extra tweaking needed, and it also preserves your <code>UITableViewController</code>'s scene in the storyboard.</p></li> <li><p><strong>Using AutoLayout and embedding the <code>UITableView</code> into another view</strong> <em>(I believe this is how Apple wants us to do this)</em>:<br> Create an empty <code>UIViewController</code> and drag your <code>UITableView</code> in it. Then, Ctrl-drag from your <code>UITableView</code> towards the status bar. As the mouse gets to the bottom of the status bar, you will see an Autolayout bubble that says "Top Layout Guide". Release the mouse and choose "Vertical Spacing". That will tell the layout system to place it right below the status bar.</p></li> </ul> <p>I have tested both ways on an empty application and they both work. You may need to do some extra tweaking to make them work for your project.</p>
{ "question_id": 18900428, "question_date": "2013-09-19T16:40:36.373Z", "question_score": 219, "tags": "ios|ios7|uistatusbar", "answer_id": 18951786, "answer_date": "2013-09-23T04:28:03.423Z", "answer_score": 365 }
Please answer the following Stack Overflow question: Title: How to check if a file exists in Documents folder? <p>I have an application with In-App Purchase, that when the user buy something, download one html file into the Documents folder of my app.</p> <p>Now I must check if this HTML file exists, so if true, load this HTML file, else load my default html page.</p> <p>How I can do that? With <code>NSFileManager</code> I can't get outside of <code>mainBundle</code>..</p>
<h3>Swift 3:</h3> <pre><code>let documentsURL = try! FileManager().url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) </code></pre> <p>... gives you a file URL of the documents directory. The following checks if there's a file named foo.html:</p> <pre><code>let fooURL = documentsURL.appendingPathComponent("foo.html") let fileExists = FileManager().fileExists(atPath: fooURL.path) </code></pre> <h3>Objective-C:</h3> <pre><code>NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]; NSString* foofile = [documentsPath stringByAppendingPathComponent:@"foo.html"]; BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:foofile]; </code></pre>
{ "question_id": 1638834, "question_date": "2009-10-28T17:33:26.820Z", "question_score": 219, "tags": "ios|iphone|xcode|webview|nsfilemanager", "answer_id": 1638853, "answer_date": "2009-10-28T17:37:11.977Z", "answer_score": 526 }
Please answer the following Stack Overflow question: Title: pandas loc vs. iloc vs. at vs. iat? <p>Recently began branching out from my safe place (R) into Python and and am a bit confused by the cell localization/selection in <code>Pandas</code>. I've read the documentation but I'm struggling to understand the practical implications of the various localization/selection options.</p> <p>Is there a reason why I should ever use <code>.loc</code> or <code>.iloc</code> over <code>at</code>, and <code>iat</code> or vice versa? <strong>In what situations should I use which method?</strong></p> <hr /> <blockquote> <p><sub>Note: future readers be aware that this question is old and was written before pandas v0.20 when there used to exist a function called <code>.ix</code>. This method was later split into two - <code>loc</code> and <code>iloc</code> - to make the explicit distinction between positional and label based indexing. Please beware that <code>ix</code> was discontinued due to inconsistent behavior and being hard to grok, and no longer exists in current versions of pandas (&gt;= 1.0).</sub></p> </blockquote>
<p><strong>loc:</strong> only work on index<Br> <strong>iloc:</strong> work on position<Br> <strong>at:</strong> get scalar values. It's a very fast loc<Br> <strong>iat:</strong> Get scalar values. It's a very fast iloc<Br></p> <p>Also,</p> <blockquote> <p><code>at</code> and <code>iat</code> are meant to access a scalar, that is, a single element in the dataframe, while <code>loc</code> and <code>iloc</code> are ments to access several elements at the same time, potentially to perform vectorized operations.</p> </blockquote> <p><a href="http://pyciencia.blogspot.com/2015/05/obtener-y-filtrar-datos-de-un-dataframe.html" rel="noreferrer">http://pyciencia.blogspot.com/2015/05/obtener-y-filtrar-datos-de-un-dataframe.html</a></p>
{ "question_id": 28757389, "question_date": "2015-02-27T04:12:39.900Z", "question_score": 219, "tags": "python|pandas|performance|indexing|lookup", "answer_id": 30022658, "answer_date": "2015-05-04T04:31:58.457Z", "answer_score": 178 }
Please answer the following Stack Overflow question: Title: What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config? <p>While converting a project that used SlimDX, and therefore has unmanaged code, to .NET 4.0 I ran into the following error:</p> <blockquote> <p>Mixed mode assembly is built against version 'v2.0.50727' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.</p> </blockquote> <p>Googling around gave me the solution, which is to add this to the applications config:</p> <pre><code>&lt;configuration&gt; &lt;startup useLegacyV2RuntimeActivationPolicy="true"&gt; &lt;supportedRuntime version="v4.0"/&gt; &lt;/startup&gt; &lt;/configuration&gt; </code></pre> <p>My question is, what is the <code>useLegacyV2RuntimeActivationPolicy</code> doing? I can't find any documentation about it.</p>
<p>After a bit of time (and more searching), I found <a href="http://blogs.msdn.com/jomo_fisher/archive/2009/11/17/f-scripting-net-4-0-and-mixed-mode-assemblies.aspx" rel="noreferrer">this blog entry</a> by Jomo Fisher.</p> <blockquote> <p>One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:</p> <p><em>Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.</em></p> <p>[Snip]</p> <p>The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:</p> <pre><code>&lt;startup useLegacyV2RuntimeActivationPolicy=&quot;true&quot;&gt; &lt;supportedRuntime version=&quot;v4.0&quot;/&gt; &lt;/startup&gt; </code></pre> </blockquote> <p>So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the <code>useLegacyV2RuntimeActivationPolicy</code> attribute reverts back to CLR 2.0 loading.</p>
{ "question_id": 1604663, "question_date": "2009-10-22T02:03:39.933Z", "question_score": 219, "tags": ".net|.net-4.0|app-config|mixed-mode", "answer_id": 1752650, "answer_date": "2009-11-17T23:36:04.910Z", "answer_score": 166 }
Please answer the following Stack Overflow question: Title: How do I perform an insert and return inserted identity with Dapper? <p>How do I perform an insert to database and return inserted identity with Dapper?</p> <p>I've tried something like this:</p> <pre><code>string sql = "DECLARE @ID int; " + "INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff); " + "SELECT @ID = SCOPE_IDENTITY()"; var id = connection.Query&lt;int&gt;(sql, new { Stuff = mystuff}).First(); </code></pre> <p>But it did't work.</p> <p>@Marc Gravell thanks, for reply. I've tried your solution but, still same exception trace is below</p> <pre><code>System.InvalidCastException: Specified cast is not valid at Dapper.SqlMapper.&lt;QueryInternal&gt;d__a`1.MoveNext() in (snip)\Dapper\SqlMapper.cs:line 610 at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in (snip)\Dapper\SqlMapper.cs:line 538 at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param) in (snip)\Dapper\SqlMapper.cs:line 456 </code></pre>
<p>It does <em>support</em> input/output parameters (including <code>RETURN</code> value) if you use <code>DynamicParameters</code>, but in this case the simpler option is simply:</p> <pre class="lang-cs prettyprint-override"><code>var id = connection.QuerySingle&lt;int&gt;( @&quot; INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff); SELECT CAST(SCOPE_IDENTITY() as int)&quot;, new { Stuff = mystuff}); </code></pre> <p>Note that on more recent versions of SQL Server (2005+) you can use the <code>OUTPUT</code> clause:</p> <pre class="lang-cs prettyprint-override"><code>var id = connection.QuerySingle&lt;int&gt;( @&quot; INSERT INTO [MyTable] ([Stuff]) OUTPUT INSERTED.Id VALUES (@Stuff);&quot;, new { Stuff = mystuff}); </code></pre>
{ "question_id": 8270205, "question_date": "2011-11-25T14:02:15.923Z", "question_score": 219, "tags": "c#|sql-server|dapper", "answer_id": 8270264, "answer_date": "2011-11-25T14:07:03.813Z", "answer_score": 369 }
Please answer the following Stack Overflow question: Title: In-place edits with sed on OS X <p>I'd like edit a file with sed on OS X. I'm using the following command:</p> <pre><code>sed 's/oldword/newword/' file.txt </code></pre> <p>The output is sent to the terminal. <strong>file.txt</strong> is not modified. The changes are saved to <strong>file2.txt</strong> with this command:</p> <pre><code>sed 's/oldword/newword/' file1.txt &gt; file2.txt </code></pre> <p>However I don't want another file. I just want to edit <strong>file1.txt</strong>. How can I do this?</p> <p>I've tried the -i flag. This results in the following error:</p> <pre><code>sed: 1: "file1.txt": invalid command code f </code></pre>
<p>You can use the <code>-i</code> flag correctly by providing it with a suffix to add to the backed-up file. Extending your example: </p> <pre><code>sed -i.bu 's/oldword/newword/' file1.txt </code></pre> <p>Will give you two files: one with the name <code>file1.txt</code> that contains the substitution, and one with the name <code>file1.txt.bu</code> that has the original content. </p> <p><strong>Mildly dangerous</strong></p> <p>If you want to destructively overwrite the original file, use something like: </p> <pre><code>sed -i '' 's/oldword/newword/' file1.txt ^ note the space </code></pre> <p>Because of the way the line gets parsed, a space is required between the option flag and its argument <em>because the argument is zero-length.</em> </p> <p>Other than possibly trashing your original, I’m not aware of any further dangers of tricking sed this way. It should be noted, however, that if this invocation of <code>sed</code> is part of a script, The Unix Way™ would (IMHO) be to use <code>sed</code> non-destructively, test that it exited cleanly, and only then remove the extraneous file. </p>
{ "question_id": 7573368, "question_date": "2011-09-27T17:37:19.317Z", "question_score": 219, "tags": "macos|file-io|sed|in-place", "answer_id": 7573438, "answer_date": "2011-09-27T17:44:03.697Z", "answer_score": 394 }
Please answer the following Stack Overflow question: Title: How to use jQuery to wait for the end of CSS3 transitions? <p>I'd like to fade out an element (transitioning its opacity to 0) and then when finished remove the element from the DOM.</p> <p>In jQuery this is straight forward since you can specify the "Remove" to happen after an animation completes. But if I wish to animate using CSS3 transitions is there anyway to know when the transition/animation has completed?</p>
<p>For transitions you can use the following to detect the end of a transition via jQuery:</p> <pre><code>$("#someSelector").bind("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... }); </code></pre> <p>Mozilla has an excellent reference:</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions#Detecting_the_start_and_completion_of_a_transition" rel="noreferrer">https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions#Detecting_the_start_and_completion_of_a_transition</a></p> <p>For animations it's very similar:</p> <pre><code>$("#someSelector").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... }); </code></pre> <p>Note that you can pass all of the browser prefixed event strings into the bind() method simultaneously to support the event firing on all browsers that support it.</p> <p><strong>Update:</strong></p> <p>Per the comment left by Duck: you use jQuery's <code>.one()</code> method to ensure the handler only fires once. For example:</p> <pre><code>$("#someSelector").one("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(){ ... }); $("#someSelector").one("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){ ... }); </code></pre> <p><strong>Update 2:</strong></p> <p>jQuery <code>bind()</code> method has been deprecated, and <code>on()</code> method is preferred as of <code>jQuery 1.7</code>. <a href="http://api.jquery.com/bind/" rel="noreferrer"><code>bind()</code></a></p> <p>You can also use <code>off()</code> method on the callback function to ensure it will be fired only once. Here is an example which is equivalent to using <code>one()</code> method:</p> <pre><code>$("#someSelector") .on("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(e){ // do something here $(this).off(e); }); </code></pre> <p>References:</p> <ul> <li><p><a href="https://api.jquery.com/off/" rel="noreferrer"><code>.off()</code></a></p></li> <li><p><a href="http://api.jquery.com/one/" rel="noreferrer"><code>.one()</code></a></p></li> </ul>
{ "question_id": 9255279, "question_date": "2012-02-13T03:38:49.560Z", "question_score": 219, "tags": "javascript|jquery|css|css-transitions", "answer_id": 9255507, "answer_date": "2012-02-13T04:12:14.373Z", "answer_score": 348 }
Please answer the following Stack Overflow question: Title: Does Ruby have a string.startswith("abc") built in method? <p>Does Ruby have a <code>some_string.starts_with("abc")</code> method that's built in?</p>
<p>It's called <a href="http://RubyDoc.Info/docs/ruby-core/1.9.2/String#start_with%3F-instance_method" rel="noreferrer"><code>String#start_with?</code></a>, not <code>String#startswith</code>: In Ruby, the names of boolean-ish methods end with <code>?</code> and the words in method names are separated with an <code>_</code>. On Rails you can use the alias <a href="https://apidock.com/rails/ActiveSupport/CoreExtensions/String/StartsEndsWith/starts_with%3F" rel="noreferrer"><code>String#starts_with?</code></a> (note the plural - and note that this method is deprecated). Personally, I'd prefer <code>String#starts_with?</code> over the actual <code>String#start_with?</code></p>
{ "question_id": 4130364, "question_date": "2010-11-09T03:51:35.483Z", "question_score": 219, "tags": "ruby", "answer_id": 4130600, "answer_date": "2010-11-09T04:48:39.700Z", "answer_score": 368 }
Please answer the following Stack Overflow question: Title: Remove file from SVN repository without deleting local copy <p>How can I "delete" a file which is already in the SVN repository without deleting it from my file system?</p> <p>TortoiseSVN or command line instructions are welcome.</p> <p>The following works, but I am hoping for something nicer:</p> <ol> <li>Copy the file to some other location outside the repository.</li> <li>SVN Delete the file.</li> <li>Commit</li> <li>Copy the files back and make sure to ignore them on future commits.</li> </ol>
<pre><code>svn delete --keep-local the_file </code></pre>
{ "question_id": 542065, "question_date": "2009-02-12T16:12:59.623Z", "question_score": 219, "tags": "svn|tortoisesvn", "answer_id": 542100, "answer_date": "2009-02-12T16:18:39.330Z", "answer_score": 268 }
Please answer the following Stack Overflow question: Title: What is the purpose of a "Refresh Token"? <p>I have a program that integrates with the YouTube Live Streaming API. It runs on timers, so its been relatively easy for me to program in to fetch a new Access Token every 50 minutes with a Refresh Token. My question is, why?</p> <p>When I authenticated with YouTube, it gave me a Refresh Token. I then use this refresh token to get a new Access Token about once an hour. If I have the Refresh Token, I can ALWAYS use this to get a new Access Token, since it never expires. So I don't see how this is any more secure than just giving me an Access Token from the start and not bothering with the whole Refresh Token system.</p>
<p>Basically, refresh tokens are used to get new access token.</p> <p>To clearly differentiate these two tokens and avoid getting mixed up, here are their functions given in <a href="https://www.rfc-editor.org/rfc/rfc6749#section-1.4" rel="noreferrer">The OAuth 2.0 Authorization Framework</a>:</p> <blockquote> <ul> <li><strong>Access tokens</strong> are issued to third-party clients by an authorization server with the approval of the resource owner. The client uses the access token to access the protected resources hosted by the resource server.</li> <li><strong>Refresh Tokens</strong> are credentials used to obtain access tokens. Refresh tokens are issued to the client by the authorization server and are used to obtain a new access token when the current access token becomes invalid or expires, or to obtain additional access tokens with identical or narrower scope.</li> </ul> </blockquote> <p>Now, to answer your question on why you were still being issued a refresh token instead of just securing an access token, the main reason provided by Internet Engineering Task Force in <a href="http://www.ietf.org/mail-archive/web/oauth/current/msg06687.html" rel="noreferrer">Refresh tokens</a> is:</p> <blockquote> <p>There is a security reason, the <code>refresh_token</code> is only ever exchanged with authorization server whereas the <code>access_token</code> is exchanged with resource servers. This mitigates the risk of a long-lived access_token leaking in the &quot;an access token good for an hour, with a refresh token good for a year or good-till-revoked&quot; vs &quot;an access token good-till-revoked without a refresh token.&quot;</p> </blockquote> <p>For a more detailed and complete information of OAuth 2.0 Flow, please try going through the following references:</p> <ul> <li><a href="https://developers.google.com/youtube/v3/live/guides/auth/server-side-web-apps" rel="noreferrer"> OAuth 2.0 Flow: Server-side web apps</a></li> <li><a href="https://www.rfc-editor.org/rfc/rfc6749" rel="noreferrer">The OAuth 2.0 Authorization Framework</a> issued by Internet Engineering Task Force (IETF)</li> <li>SO post - <a href="https://stackoverflow.com/a/7209263">Why Does OAuth v2 Have Both Access and Refresh Tokens?</a></li> </ul>
{ "question_id": 38986005, "question_date": "2016-08-16T23:31:00.517Z", "question_score": 219, "tags": "authentication|oauth-2.0|youtube-api|access-token|refresh-token", "answer_id": 39003201, "answer_date": "2016-08-17T17:46:52.880Z", "answer_score": 161 }
Please answer the following Stack Overflow question: Title: Why is std::map implemented as a red-black tree? <p>Why is <code>std::map</code> implemented as a <a href="http://en.wikipedia.org/wiki/Red%E2%80%93black_tree" rel="noreferrer">red-black tree</a>?</p> <p>There are several balanced <a href="http://en.wikipedia.org/wiki/Binary_search_tree" rel="noreferrer">binary search trees</a> (BSTs) out there. What were design trade-offs in choosing a red-black tree?</p>
<p>Probably the two most common self balancing tree algorithms are <a href="http://en.wikipedia.org/wiki/Red-black_tree" rel="noreferrer">Red-Black trees</a> and <a href="http://en.wikipedia.org/wiki/AVL_tree" rel="noreferrer">AVL trees</a>. To balance the tree after an insertion/update both algorithms use the notion of rotations where the nodes of the tree are rotated to perform the re-balancing. </p> <p>While in both algorithms the insert/delete operations are O(log n), in the case of Red-Black tree re-balancing rotation is an <a href="http://en.wikipedia.org/wiki/Big_O_notation" rel="noreferrer">O(1)</a> operation while with AVL this is a <a href="http://en.wikipedia.org/wiki/Big_O_notation" rel="noreferrer">O(log n)</a> operation, making the Red-Black tree more efficient in this aspect of the re-balancing stage and one of the possible reasons that it is more commonly used.</p> <p>Red-Black trees are used in most collection libraries, including the offerings from Java and Microsoft .NET Framework. </p>
{ "question_id": 5288320, "question_date": "2011-03-13T08:33:58.577Z", "question_score": 219, "tags": "c++|dictionary|data-structures|stl|binary-search-tree", "answer_id": 5288357, "answer_date": "2011-03-13T08:47:40.457Z", "answer_score": 146 }
Please answer the following Stack Overflow question: Title: What's the difference between git reflog and log? <p>The man page says that log shows the commit logs and reflog manages reflog information. What exactly is reflog information and what does it have that the log doesn't? The log seems far more detailed.</p>
<p><code>git log</code> shows the current HEAD and its ancestry. That is, it prints the commit HEAD points to, then its parent, its parent, and so on. It traverses back through the repo's ancestry, by recursively looking up each commit's parent.</p> <p><em>(In practice, some commits have more than one parent. To see a more representative log, use a command like <code>git log --oneline --graph --decorate</code>.)</em></p> <p><code>git reflog</code> doesn't traverse HEAD's ancestry at all. The reflog is an ordered list of the commits that HEAD has pointed to: it's undo history for your repo. The reflog isn't part of the repo itself (it's stored separately to the commits themselves) and isn't included in pushes, fetches or clones; it's purely local.</p> <p><em>Aside: understanding the reflog means you can't really lose data from your repo once it's been committed. If you accidentally reset to an older commit, or rebase wrongly, or any other operation that visually "removes" commits, you can use the reflog to see where you were before and <code>git reset --hard</code> back to that ref to restore your previous state. Remember, refs imply not just the commit but the entire history behind it.</em></p>
{ "question_id": 17857723, "question_date": "2013-07-25T12:13:48.583Z", "question_score": 219, "tags": "git|git-log|git-reflog", "answer_id": 17860179, "answer_date": "2013-07-25T14:01:13.077Z", "answer_score": 287 }
Please answer the following Stack Overflow question: Title: What is the use of having destructor as private? <p>What is the use of having destructor as private?</p>
<p>Basically, any time you want some other class to be responsible for the life cycle of your class' objects, or you have reason to prevent the destruction of an object, you can make the destructor private.</p> <p>For instance, if you're doing some sort of reference counting thing, you can have the object (or manager that has been "friend"ed) responsible for counting the number of references to itself and delete it when the number hits zero. A private dtor would prevent anybody else from deleting it when there were still references to it.</p> <p>For another instance, what if you have an object that has a manager (or itself) that may destroy it or may decline to destroy it depending on other conditions in the program, such as a database connection being open or a file being written. You could have a "request_delete" method in the class or the manager that will check that condition and it will either delete or decline, and return a status telling you what it did. That's far more flexible that just calling "delete".</p>
{ "question_id": 631783, "question_date": "2009-03-10T18:59:52.460Z", "question_score": 219, "tags": "c++|private|destructor", "answer_id": 631791, "answer_date": "2009-03-10T19:02:44.747Z", "answer_score": 200 }
Please answer the following Stack Overflow question: Title: invalid context 0x0 under iOS 7.0 and system degradation <p>I've read as many search results I could find on this dreaded problem, unfortunatelly, each one seems to focus on a specific function call.</p> <p>My problem is that I get the same error from multiple functions, which I am guessing are being called back from functions that I use.</p> <p>To make matters worse, the actual code is within a custom private framework which is being imported in another project, and as such, debugging isn't as simple?</p> <p>Can anyone point me to the right direction? I have a feeling I'm calling certain methods wrongly or with bad context, but the output from xcode is not very helpful at this point.</p> <blockquote> <p>: CGContextSetFillColorWithColor: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.</p> <p>: CGContextSetStrokeColorWithColor: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.</p> <p>CGContextSaveGState: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.</p> <p>: CGContextSetFlatness: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.</p> <p>: CGContextAddPath: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.</p> <p>: CGContextDrawPath: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.</p> <p>: CGContextRestoreGState: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.</p> <p>: CGContextGetBlendMode: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.</p> </blockquote> <p>Those errors may occur when a custom view is presented, or one of its inherited classes. At which point they spawn multiple times, until the keyboard won't provide any input. Touch events are still registered, but system slows down, and eventually may lead to unallocated object errors.</p> <p><strong>EDIT #1:</strong> I do have access to the framework being imported, but I do not see anything weird in the classes which causing the issue.</p> <p><strong>EDIT #2:</strong> I just received an email that iOS 7.1 has been released for developers. I'm curious to see if this goes away, or become worse, or can be solved.</p>
<p>Others will ask you to post the code where you access a core graphics context, but I doubt that's the issue. These invalid context 0x0 error messages are common and easy to reproduce in iOS 7. In fact, I can reproduce the error using storyboard with zero code. I drag a UITextField onto the canvas in IB, run the app, and double tap inside the text field. </p> <p>In many situations, it's hard for me to take the invalid context 0x0 error messages seriously. I don't know if your situation warrants greater concern (I agree with Rob Napier that it's worth investigating, especially if you are explicitly using a graphics context).</p> <p>In my own projects, I'm hoping that many of these errors magically disappear some day (but that day did not come with 7.0.3).</p> <p><strong>Update:</strong> After installing Xcode 5.1 and targeting iOS 7.1, I can no longer reproduce the error by double tapping inside an empty text field. </p>
{ "question_id": 19599266, "question_date": "2013-10-25T20:53:19.493Z", "question_score": 219, "tags": "objective-c|ios7|core-graphics", "answer_id": 19599680, "answer_date": "2013-10-25T21:26:16.527Z", "answer_score": 162 }
Please answer the following Stack Overflow question: Title: Python - json without whitespaces <p>I just realized that <code>json.dumps()</code> adds spaces in the JSON object</p> <p>e.g.</p> <pre><code>{'duration': '02:55', 'name': 'flower', 'chg': 0} </code></pre> <p>how can remove the spaces in order to make the JSON more compact and save bytes to be sent via HTTP?</p> <p>such as:</p> <pre><code>{'duration':'02:55','name':'flower','chg':0} </code></pre>
<pre><code>json.dumps(separators=(',', ':')) </code></pre>
{ "question_id": 16311562, "question_date": "2013-05-01T01:42:00.480Z", "question_score": 219, "tags": "python|json|serialization", "answer_id": 16311587, "answer_date": "2013-05-01T01:45:32.510Z", "answer_score": 359 }
Please answer the following Stack Overflow question: Title: Converting Storyboard from iPhone to iPad <p>I have an <code>iPhone</code> application which has a storyboard. Now I want to provide an <code>iPad</code> application too. So I asked me whether there is a function which helps me convert my <code>iPhone</code> storyboard to an <code>iPad</code> storyboard.</p> <p>To be specific:</p> <p><strong>Is there a similar function or is there only the manual way ?</strong></p>
<p>I found out a kind of solution:</p> <ol> <li><p>Duplicate your iPhone-Storyboard and rename it <code>MainStoryboard_iPad.storyboard</code></p></li> <li><p>Close Xcode and then open this file any text editor.</p></li> <li><p>Search for <code>targetRuntime="iOS.CocoaTouch"</code>and change it to <code>targetRuntime="iOS.CocoaTouch.iPad"</code></p></li> <li><p>Change the code in the MainStoryboard_iPad.storyboard from: </p> <p><code>&lt;simulatedScreenMetrics key="destination" type="retina4"/&gt;</code> to</p> <p><code>&lt;simulatedScreenMetrics key="destination"/&gt;</code></p></li> <li><p>Now save everything and reopen Xcode. The iPad-Storyboard has the same contents as the iPhone-file but everyting could be disarranged.</p></li> </ol> <p>This saved me hours - hopefully this will help you</p>
{ "question_id": 8465769, "question_date": "2011-12-11T16:59:40.133Z", "question_score": 219, "tags": "ios|iphone|xcode|ipad|storyboard", "answer_id": 8694985, "answer_date": "2012-01-01T19:28:48.310Z", "answer_score": 537 }
Please answer the following Stack Overflow question: Title: How do I get the count of a Swift enum? <p>How can I determine the number of cases in a Swift enum?</p> <p>(I would like to avoid <a href="https://stackoverflow.com/a/24137319/17294">manually enumerating through all the values</a>, or using the old "<a href="https://stackoverflow.com/a/14717179/17294">enum_count trick</a>" if possible.)</p>
<p>As of Swift 4.2 (Xcode 10) you can declare conformance to the <code>CaseIterable</code> protocol, this works for all enumerations without associated values:</p> <pre><code>enum Stuff: CaseIterable { case first case second case third case forth } </code></pre> <p>The number of cases is now simply obtained with</p> <pre><code>print(Stuff.allCases.count) // 4 </code></pre> <p>For more information, see</p> <ul> <li><a href="https://github.com/apple/swift-evolution/blob/master/proposals/0194-derived-collection-of-enum-cases.md" rel="noreferrer">SE-0194 Derived Collection of Enum Cases</a></li> </ul>
{ "question_id": 27094878, "question_date": "2014-11-23T21:59:30.633Z", "question_score": 219, "tags": "swift|enums|count", "answer_id": 50177561, "answer_date": "2018-05-04T14:43:18.990Z", "answer_score": 242 }
Please answer the following Stack Overflow question: Title: How can you automatically remove trailing whitespace in vim <p>I am getting 'trailing whitespace' errors trying to commit some files in Git.</p> <p>I want to remove these trailing whitespace characters automatically right before I save Python files.</p> <p>Can you configure Vim to do this? If so, how?</p>
<p>I found the answer <a href="https://vim.fandom.com/wiki/Remove_unwanted_spaces#Automatically_removing_all_trailing_whitespace" rel="noreferrer">here</a>.</p> <p>Adding the following to my .vimrc file did the trick:</p> <pre class="lang-vim prettyprint-override"><code>autocmd BufWritePre *.py :%s/\s\+$//e </code></pre> <p>The <code>e</code> flag at the end means that the command doesn't issue an error message if the search pattern fails. See <a href="https://vimhelp.org/change.txt.html#%3As_flags" rel="noreferrer"><code>:h :s_flags</code></a> for more.</p>
{ "question_id": 356126, "question_date": "2008-12-10T14:02:31.267Z", "question_score": 219, "tags": "vim|automation|whitespace|removing-whitespace", "answer_id": 356130, "answer_date": "2008-12-10T14:03:53.387Z", "answer_score": 221 }
Please answer the following Stack Overflow question: Title: How do I move a Git branch out into its own repository? <p>I have a branch that I'd like to move into a separate Git repository, and ideally keep that branch's history in the process. So far I've been looking at <code>git filter-branch</code>, but I can't make out whether it can do what I want to do.</p> <p>How do I extract a Git branch out into its own repository?</p>
<p>You can simply push a branch to a new repository. All of its history will go with it. You can then choose whether to delete the branch from the original repository.</p> <p>e.g.</p> <pre><code>git push url://to/new/repository.git branch-to-move:new-branch-name </code></pre> <p>For a new repository, new-branch-name is typically master.</p> <p>Creating a new, empty repository can be done with <code>git init</code>.</p>
{ "question_id": 2227062, "question_date": "2010-02-09T05:50:08.523Z", "question_score": 219, "tags": "git|branch|extract", "answer_id": 2227571, "answer_date": "2010-02-09T07:59:39.667Z", "answer_score": 355 }
Please answer the following Stack Overflow question: Title: How to remove an item for a OR'd enum? <p>I have an enum like:</p> <pre><code>public enum Blah { RED = 2, BLUE = 4, GREEN = 8, YELLOW = 16 } Blah colors = Blah.RED | Blah.BLUE | Blah.YELLOW; </code></pre> <p>How could I remove the color blue from the variable colors?</p>
<p>You need to <code>&amp;</code> it with the <code>~</code> (complement) of 'BLUE'.</p> <p>The complement operator essentially reverses or 'flips' all bits for the given data type. As such, if you use the <code>AND</code> operator (<code>&amp;</code>) with some value (let's call that value 'X') and the complement of one or more set bits (let's call those bits <code>Q</code> and their complement <code>~Q</code>), the statement <code>X &amp; ~Q</code> clears any bits that were set in <code>Q</code> from <code>X</code> and returns the result.</p> <p>So to remove or clear the <code>BLUE</code> bits, you use the following statement:</p> <pre><code>colorsWithoutBlue = colors &amp; ~Blah.BLUE colors &amp;= ~Blah.BLUE // This one removes the bit from 'colors' itself </code></pre> <p>You can also specify multiple bits to clear, as follows:</p> <pre><code>colorsWithoutBlueOrRed = colors &amp; ~(Blah.BLUE | Blah.RED) colors &amp;= ~(Blah.BLUE | Blah.RED) // This one removes both bits from 'colors' itself </code></pre> <p>or alternately...</p> <pre><code>colorsWithoutBlueOrRed = colors &amp; ~Blah.BLUE &amp; ~Blah.RED colors &amp;= ~Blah.BLUE &amp; ~Blah.RED // This one removes both bits from 'colors' itself </code></pre> <p>So to summarize:</p> <ul> <li><code>X | Q</code> sets bit(s) <code>Q</code></li> <li><code>X &amp; ~Q</code> clears bit(s) <code>Q</code></li> <li><code>~X</code> flips/inverts all bits in <code>X</code></li> </ul>
{ "question_id": 4778166, "question_date": "2011-01-24T02:51:34.973Z", "question_score": 219, "tags": "c#|enums", "answer_id": 4778181, "answer_date": "2011-01-24T02:54:10.673Z", "answer_score": 391 }
Please answer the following Stack Overflow question: Title: What does auto&& tell us? <p>If you read code like</p> <p><code>auto&amp;&amp; var = foo();</code></p> <p>where <code>foo</code> is any function returning by value of type <code>T</code>. Then <code>var</code> is an lvalue of type rvalue reference to <code>T</code>. But what does this imply for <code>var</code>? Does it mean, we are allowed to steal the resources of <code>var</code>? Are there any reasonable situations when you should use <code>auto&amp;&amp;</code> to tell the reader of your code something like you do when you return a <code>unique_ptr&lt;&gt;</code> to tell that you have exclusive ownership? And what about for example <code>T&amp;&amp;</code> when <code>T</code> is of class type?</p> <p>I just want to understand, if there are any other use cases of <code>auto&amp;&amp;</code> than those in template programming; like the ones discussed in the examples in this article <a href="http://isocpp.org/blog/2012/11/universal-references-in-c11-scott-meyers" rel="noreferrer">Universal References</a> by Scott Meyers.</p>
<p>By using <code>auto&amp;&amp; var = &lt;initializer&gt;</code> you are saying: <strong>I will accept any initializer regardless of whether it is an lvalue or rvalue expression and I will preserve its constness</strong>. This is typically used for <em>forwarding</em> (usually with <code>T&amp;&amp;</code>). The reason this works is because a "universal reference", <code>auto&amp;&amp;</code> or <code>T&amp;&amp;</code>, will bind to <em>anything</em>.</p> <p>You might say, well why not just use a <code>const auto&amp;</code> because that will <em>also</em> bind to anything? The problem with using a <code>const</code> reference is that it's <code>const</code>! You won't be able to later bind it to any non-const references or invoke any member functions that are not marked <code>const</code>.</p> <p>As an example, imagine that you want to get a <code>std::vector</code>, take an iterator to its first element and modify the value pointed to by that iterator in some way:</p> <pre><code>auto&amp;&amp; vec = some_expression_that_may_be_rvalue_or_lvalue; auto i = std::begin(vec); (*i)++; </code></pre> <p>This code will compile just fine regardless of the initializer expression. The alternatives to <code>auto&amp;&amp;</code> fail in the following ways:</p> <pre><code>auto =&gt; will copy the vector, but we wanted a reference auto&amp; =&gt; will only bind to modifiable lvalues const auto&amp; =&gt; will bind to anything but make it const, giving us const_iterator const auto&amp;&amp; =&gt; will bind only to rvalues </code></pre> <p>So for this, <code>auto&amp;&amp;</code> works perfectly! An example of using <code>auto&amp;&amp;</code> like this is in a range-based <code>for</code> loop. See <a href="https://stackoverflow.com/q/13241108/150634">my other question</a> for more details.</p> <p>If you then use <code>std::forward</code> on your <code>auto&amp;&amp;</code> reference to preserve the fact that it was originally either an lvalue or an rvalue, your code says: <strong>Now that I've got your object from either an lvalue or rvalue expression, I want to preserve whichever valueness it originally had so I can use it most efficiently - this might invalidate it.</strong> As in:</p> <pre><code>auto&amp;&amp; var = some_expression_that_may_be_rvalue_or_lvalue; // var was initialized with either an lvalue or rvalue, but var itself // is an lvalue because named rvalues are lvalues use_it_elsewhere(std::forward&lt;decltype(var)&gt;(var)); </code></pre> <p>This allows <code>use_it_elsewhere</code> to rip its guts out for the sake of performance (avoiding copies) when the original initializer was a modifiable rvalue.</p> <p>What does this mean as to whether we can or when we can steal resources from <code>var</code>? Well since the <code>auto&amp;&amp;</code> will bind to anything, we cannot possibly try to rip out <code>var</code>s guts ourselves - it may very well be an lvalue or even const. We can however <code>std::forward</code> it to other functions that may totally ravage its insides. As soon as we do this, we should consider <code>var</code> to be in an invalid state.</p> <p>Now let's apply this to the case of <code>auto&amp;&amp; var = foo();</code>, as given in your question, where foo returns a <code>T</code> by value. In this case we know for sure that the type of <code>var</code> will be deduced as <code>T&amp;&amp;</code>. Since we know for certain that it's an rvalue, we don't need <code>std::forward</code>'s permission to steal its resources. In this specific case, <em>knowing that <code>foo</code> returns by value</em>, the reader should just read it as: <strong>I'm taking an rvalue reference to the temporary returned from <code>foo</code>, so I can happily move from it.</strong></p> <hr> <p>As an addendum, I think it's worth mentioning when an expression like <code>some_expression_that_may_be_rvalue_or_lvalue</code> might turn up, other than a "well your code might change" situation. So here's a contrived example:</p> <pre><code>std::vector&lt;int&gt; global_vec{1, 2, 3, 4}; template &lt;typename T&gt; T get_vector() { return global_vec; } template &lt;typename T&gt; void foo() { auto&amp;&amp; vec = get_vector&lt;T&gt;(); auto i = std::begin(vec); (*i)++; std::cout &lt;&lt; vec[0] &lt;&lt; std::endl; } </code></pre> <p>Here, <code>get_vector&lt;T&gt;()</code> is that lovely expression that could be either an lvalue or rvalue depending on the generic type <code>T</code>. We essentially change the return type of <code>get_vector</code> through the template parameter of <code>foo</code>.</p> <p>When we call <code>foo&lt;std::vector&lt;int&gt;&gt;</code>, <code>get_vector</code> will return <code>global_vec</code> by value, which gives an rvalue expression. Alternatively, when we call <code>foo&lt;std::vector&lt;int&gt;&amp;&gt;</code>, <code>get_vector</code> will return <code>global_vec</code> by reference, resulting in an lvalue expression.</p> <p>If we do:</p> <pre><code>foo&lt;std::vector&lt;int&gt;&gt;(); std::cout &lt;&lt; global_vec[0] &lt;&lt; std::endl; foo&lt;std::vector&lt;int&gt;&amp;&gt;(); std::cout &lt;&lt; global_vec[0] &lt;&lt; std::endl; </code></pre> <p>We get the following output, as expected:</p> <pre><code>2 1 2 2 </code></pre> <p>If you were to change the <code>auto&amp;&amp;</code> in the code to any of <code>auto</code>, <code>auto&amp;</code>, <code>const auto&amp;</code>, or <code>const auto&amp;&amp;</code> then we won't get the result we want.</p> <hr> <p>An alternative way to change program logic based on whether your <code>auto&amp;&amp;</code> reference is initialised with an lvalue or rvalue expression is to use type traits:</p> <pre><code>if (std::is_lvalue_reference&lt;decltype(var)&gt;::value) { // var was initialised with an lvalue expression } else if (std::is_rvalue_reference&lt;decltype(var)&gt;::value) { // var was initialised with an rvalue expression } </code></pre>
{ "question_id": 13230480, "question_date": "2012-11-05T10:46:05.350Z", "question_score": 219, "tags": "c++|c++11|auto|forwarding-reference", "answer_id": 13242177, "answer_date": "2012-11-05T23:37:02.893Z", "answer_score": 305 }
Please answer the following Stack Overflow question: Title: C# - Keyword usage virtual+override vs. new <p>What are differences between declaring a method in a base type "<code>virtual</code>" and then overriding it in a child type using the "<code>override</code>" keyword as opposed to simply using the "<code>new</code>" keyword when declaring the matching method in the child type? </p>
<p>The "new" keyword doesn't override, it signifies a new method that has nothing to do with the base class method. </p> <pre><code>public class Foo { public bool DoSomething() { return false; } } public class Bar : Foo { public new bool DoSomething() { return true; } } public class Test { public static void Main () { Foo test = new Bar (); Console.WriteLine (test.DoSomething ()); } } </code></pre> <p><strong>This prints false, if you used override it would have printed true.</strong></p> <p>(Base code taken from Joseph Daigle)</p> <p>So, if you are doing real polymorphism you <strong>SHOULD ALWAYS OVERRIDE</strong>. The only place where you need to use "new" is when the method is not related in any way to the base class version.</p>
{ "question_id": 159978, "question_date": "2008-10-01T22:06:52.400Z", "question_score": 219, "tags": "c#|syntax|overriding|method-hiding|member-hiding", "answer_id": 159993, "answer_date": "2008-10-01T22:10:01.223Z", "answer_score": 196 }
Please answer the following Stack Overflow question: Title: What is the difference between a thread and a fiber? <p>What is the difference between a thread and a fiber? I've heard of fibers from ruby and I've read heard they're available in other languages, could somebody explain to me in simple terms what is the difference between a thread and a fiber.</p>
<p>In the most simple terms, threads are generally considered to be preemptive (although this may not always be true, depending on the operating system) while fibers are considered to be light-weight, cooperative threads. Both are separate execution paths for your application.</p> <p>With threads: the current execution path may be interrupted or preempted at any time (note: this statement is a generalization and may not always hold true depending on OS/threading package/etc.). This means that for threads, data integrity is a big issue because one thread may be stopped in the middle of updating a chunk of data, leaving the integrity of the data in a bad or incomplete state. This also means that the operating system can take advantage of multiple CPUs and CPU cores by running more than one thread at the same time and leaving it up to the developer to guard data access.</p> <p>With fibers: the current execution path is only interrupted when the fiber yields execution (same note as above). This means that fibers always start and stop in well-defined places, so data integrity is much less of an issue. Also, because fibers are often managed in the user space, expensive context switches and CPU state changes need not be made, making changing from one fiber to the next extremely efficient. On the other hand, since no two fibers can run at exactly the same time, just using fibers alone will not take advantage of multiple CPUs or multiple CPU cores.</p>
{ "question_id": 796217, "question_date": "2009-04-28T04:27:20.073Z", "question_score": 219, "tags": "multithreading|concurrency|coroutine|fibers", "answer_id": 796255, "answer_date": "2009-04-28T04:40:19.980Z", "answer_score": 192 }
Please answer the following Stack Overflow question: Title: What's the difference between a proc and a lambda in Ruby? <p>And when would you use one rather than the other?</p>
<p>One difference is in the way they handle arguments. Creating a proc using <code>proc {}</code> and <code>Proc.new {}</code> are equivalent. However, using <code>lambda {}</code> gives you a proc that checks the number of arguments passed to it. From <code>ri Kernel#lambda</code>:</p> <blockquote> <p>Equivalent to <strong>Proc.new</strong>, except the resulting Proc objects check the number of parameters passed when called.</p> </blockquote> <p>An example:</p> <pre><code>p = Proc.new {|a, b| puts a**2+b**2 } # =&gt; #&lt;Proc:0x3c7d28@(irb):1&gt; p.call 1, 2 # =&gt; 5 p.call 1 # =&gt; NoMethodError: undefined method `**' for nil:NilClass p.call 1, 2, 3 # =&gt; 5 l = lambda {|a, b| puts a**2+b**2 } # =&gt; #&lt;Proc:0x15016c@(irb):5 (lambda)&gt; l.call 1, 2 # =&gt; 5 l.call 1 # =&gt; ArgumentError: wrong number of arguments (1 for 2) l.call 1, 2, 3 # =&gt; ArgumentError: wrong number of arguments (3 for 2) </code></pre> <p>In addition, as Ken points out, using <code>return</code> inside a lambda returns the value of that lambda, but using <code>return</code> in a proc returns from the enclosing block.</p> <pre><code>lambda { return :foo }.call # =&gt; :foo return # =&gt; LocalJumpError: unexpected return Proc.new { return :foo }.call # =&gt; LocalJumpError: unexpected return </code></pre> <p>So for most quick uses they're the same, but if you want automatic strict argument checking (which can also sometimes help with debugging), or if you need to use the <code>return</code> statement to return the value of the proc, use <code>lambda</code>.</p>
{ "question_id": 1740046, "question_date": "2009-11-16T04:29:50.107Z", "question_score": 219, "tags": "ruby", "answer_id": 1740083, "answer_date": "2009-11-16T04:42:53.660Z", "answer_score": 300 }
Please answer the following Stack Overflow question: Title: How can I tell which homebrew formulae are upgradable? <p>I know when I <code>brew update</code>, it lists all <code>==&gt; Updated Formulae</code>, but when I've updated several times without running <code>brew upgrade</code>, how do I get a list of all apps that could be upgraded?</p>
<p>Per <a href="https://github.com/Homebrew/brew/blob/master/Library/Homebrew/cmd/outdated.rb" rel="noreferrer">homebrew code on github</a>, this shows all apps that can be updated:</p> <pre><code>brew outdated </code></pre> <p><code>brew help</code> does not list the command, but it is documented in <a href="https://docs.brew.sh/Manpage" rel="noreferrer"><code>man brew</code></a>.</p>
{ "question_id": 12946505, "question_date": "2012-10-18T03:11:35.503Z", "question_score": 219, "tags": "homebrew", "answer_id": 13039286, "answer_date": "2012-10-23T21:09:37.057Z", "answer_score": 363 }
Please answer the following Stack Overflow question: Title: Default constructor with empty brackets <p>Is there any good reason that an empty set of round brackets (parentheses) isn't valid for calling the default constructor in C++?</p> <pre><code>MyObject object; // ok - default ctor MyObject object(blah); // ok MyObject object(); // error </code></pre> <p>I seem to type "()" automatically everytime. Is there a good reason this isn't allowed?</p>
<p><strong>Most vexing parse</strong></p> <p>This is related to what is known as "C++'s most vexing parse". Basically, anything that can be interpreted by the compiler as a function declaration will be interpreted as a function declaration.</p> <p>Another instance of the same problem:</p> <pre><code>std::ifstream ifs("file.txt"); std::vector&lt;T&gt; v(std::istream_iterator&lt;T&gt;(ifs), std::istream_iterator&lt;T&gt;()); </code></pre> <p><code>v</code> is interpreted as a declaration of function with 2 parameters.</p> <p>The workaround is to add another pair of parentheses:</p> <pre><code>std::vector&lt;T&gt; v((std::istream_iterator&lt;T&gt;(ifs)), std::istream_iterator&lt;T&gt;()); </code></pre> <p>Or, if you have C++11 and list-initialization (also known as uniform initialization) available:</p> <pre><code>std::vector&lt;T&gt; v{std::istream_iterator&lt;T&gt;{ifs}, std::istream_iterator&lt;T&gt;{}}; </code></pre> <p>With this, there is no way it could be interpreted as a function declaration.</p>
{ "question_id": 180172, "question_date": "2008-10-07T20:13:10.967Z", "question_score": 219, "tags": "c++|constructor|default-constructor|c++-faq|most-vexing-parse", "answer_id": 181463, "answer_date": "2008-10-08T05:30:31.543Z", "answer_score": 183 }
Please answer the following Stack Overflow question: Title: How does Chrome decide what to highlight when you double-click Japanese text? <p>If you double-click English text in Chrome, the whitespace-delimited word you clicked on is highlighted. This is not surprising. However, the other day I was clicking while reading some text in Japanese and noticed that some words were highlighted at word boundaries, even though Japanese doesn't have spaces. Here's some example text:</p> <blockquote> <p>どこで生れたかとんと見当がつかぬ。何でも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。</p> </blockquote> <p>For example, if you click on 薄暗い, Chrome will correctly highlight it as a single word, even though it's not a single character class (this is a mix of kanji and hiragana). Not all the highlights are correct, but they don't seem random. </p> <p>How does Chrome decide what to highlight here? I tried searching the Chrome source for "japanese word" but only found tests for an <a href="https://source.chromium.org/chromium/chromium/src/+/master:v8/test/intl/segmenter/segment-word-next.js?q=japanese%20word&amp;ss=chromium&amp;originalUrl=https:%2F%2Fcs.chromium.org%2F" rel="noreferrer">experimental module</a> that doesn't seem active in my version of Chrome.</p>
<p>So it turns out v8 has a non-standard multi-language word segmenter and it handles Japanese. </p> <pre class="lang-js prettyprint-override"><code>function tokenizeJA(text) { var it = Intl.v8BreakIterator(['ja-JP'], {type:'word'}) it.adoptText(text) var words = [] var cur = 0, prev = 0 while (cur &lt; text.length) { prev = cur cur = it.next() words.push(text.substring(prev, cur)) } return words } console.log(tokenizeJA('どこで生れたかとんと見当がつかぬ。何でも薄暗いじめじめした所でニャーニャー泣いていた事だけは記憶している。')) // ["どこ", "で", "生れ", "たか", "とんと", "見当", "が", "つ", "か", "ぬ", "。", "何でも", "薄暗い", "じめじめ", "した", "所", "で", "ニャーニャー", "泣", "い", "て", "いた事", "だけ", "は", "記憶", "し", "て", "いる", "。"] </code></pre> <p>I also made a <a href="https://jsfiddle.net/97v0yo23/" rel="noreferrer">jsfiddle</a> that shows this. </p> <p>The quality is not amazing but I'm surprised this is supported at all.</p>
{ "question_id": 61672829, "question_date": "2020-05-08T05:50:01.827Z", "question_score": 219, "tags": "javascript|google-chrome|cjk", "answer_id": 61673028, "answer_date": "2020-05-08T06:06:36.637Z", "answer_score": 169 }
Please answer the following Stack Overflow question: Title: What is the reason why “synchronized” is not allowed in Java 8 interface methods? <p>In Java 8, I can easily write: </p> <pre><code>interface Interface1 { default void method1() { synchronized (this) { // Something } } static void method2() { synchronized (Interface1.class) { // Something } } } </code></pre> <p>I will get the full synchronisation semantics that I can use also in classes. I cannot, however, use the <code>synchronized</code> modifier on method declarations:</p> <pre><code>interface Interface2 { default synchronized void method1() { // ^^^^^^^^^^^^ Modifier 'synchronized' not allowed here } static synchronized void method2() { // ^^^^^^^^^^^^ Modifier 'synchronized' not allowed here } } </code></pre> <p>Now, one can argue that the two interfaces behave the same way except that <code>Interface2</code> establishes a <em>contract</em> on <code>method1()</code> and on <code>method2()</code>, which is a bit stronger than what <code>Interface1</code> does. Of course, we might also argue that <code>default</code> implementations should not make any assumptions about concrete implementation state, or that such a keyword simply wouldn't pull its weight.</p> <h3>Question:</h3> <p>What is the reason why the JSR-335 expert group decided not to support <code>synchronized</code> on interface methods?</p>
<p>While at first it might seem obvious that one would want to support the <code>synchronized</code> modifier on default methods, it turns out that doing so would be dangerous, and so was prohibited. </p> <p>Synchronized methods are a shorthand for a method which behaves as if the entire body is enclosed in a <code>synchronized</code> block whose lock object is the receiver. It might seem sensible to extend this semantics to default methods as well; after all, they are instance methods with a receiver too. (Note that <code>synchronized</code> methods are entirely a syntactic optimization; they're not needed, they're just more compact than the corresponding <code>synchronized</code> block. There's a reasonable argument to be made that this was a premature syntactic optimization in the first place, and that synchronized methods cause more problems than they solve, but that ship sailed a long time ago.) </p> <p>So, why are they dangerous? Synchronization is about locking. Locking is about coordinating shared access to mutable state. Each object should have a synchronization policy that determines which locks guard which state variables. (See <a href="http://amzn.to/1jyE5Kx" rel="noreferrer">Java Concurrency in Practice</a>, section 2.4.) </p> <p>Many objects use as their synchronization policy the <em>Java Monitor Pattern</em> (JCiP 4.1), in which an object's state is guarded by its intrinsic lock. There is nothing magic or special about this pattern, but it is convenient, and the use of the <code>synchronized</code> keyword on methods implicitly assumes this pattern. </p> <p>It is the class that owns the state that gets to determine that object's synchronization policy. But interfaces do not own the state of the objects into which they are mixed in. So using a synchronized method in an interface assumes a particular synchronization policy, but one which you have no reasonable basis for assuming, so it might well be the case that the use of synchronization provides no additional thread safety whatsoever (you might be synchronizing on the wrong lock). This would give you the false sense of confidence that you have done something about thread safety, and no error message tells you that you're assuming the wrong synchronization policy. </p> <p>It is already hard enough to consistently maintain a synchronization policy for a single source file; it is even harder to ensure that a subclass correctly adhere to the synchronization policy defined by its superclass. Trying to do so between such loosely coupled classes (an interface and the possibly many classes which implement it) would be nearly impossible and highly error-prone. </p> <p>Given all those arguments against, what would be the argument for? It seems they're mostly about making interfaces behave more like traits. While this is an understandable desire, the design center for default methods is interface evolution, not "Traits--". Where the two could be consistently achieved, we strove to do so, but where one is in conflict with the other, we had to choose in favor of the primary design goal. </p>
{ "question_id": 23453568, "question_date": "2014-05-04T07:06:00.790Z", "question_score": 219, "tags": "java|java-8|synchronized|default-method|jsr335", "answer_id": 23463334, "answer_date": "2014-05-05T00:50:29.813Z", "answer_score": 271 }
Please answer the following Stack Overflow question: Title: Is there a reason that Swift array assignment is inconsistent (neither a reference nor a deep copy)? <p>I'm reading the documentation and I am constantly shaking my head at some of the design decisions of the language. But the thing that really got me puzzled is how arrays are handled.</p> <p>I rushed to the playground and tried these out. You can try them too. So the first example:</p> <pre><code>var a = [1, 2, 3] var b = a a[1] = 42 a b </code></pre> <p>Here <code>a</code> and <code>b</code> are both <code>[1, 42, 3]</code>, which I can accept. Arrays are referenced - OK!</p> <p>Now see this example:</p> <pre><code>var c = [1, 2, 3] var d = c c.append(42) c d </code></pre> <p><code>c</code> is <code>[1, 2, 3, 42]</code> BUT <code>d</code> is <code>[1, 2, 3]</code>. That is, <code>d</code> saw the change in the last example but doesn't see it in this one. The documentation says that's because the length changed.</p> <p>Now, how about this one:</p> <pre><code>var e = [1, 2, 3] var f = e e[0..2] = [4, 5] e f </code></pre> <p><code>e</code> is <code>[4, 5, 3]</code>, which is cool. It's nice to have a multi-index replacement, but <code>f</code> STILL doesn't see the change even though the length has not changed.</p> <p>So to sum it up, common references to an array see changes if you change 1 element, but if you change multiple elements or append items, a copy is made.</p> <p>This seems like a very poor design to me. Am I right in thinking this? Is there a reason I don't see why arrays should act like this?</p> <p><em>EDIT</em>: Arrays have changed and now have value semantics. Much more sane!</p>
<p>Note that <strong>array semantics and syntax was changed in Xcode beta 3 version</strong> (<a href="https://medium.com/swift-programming/swift-arrays-are-fixed-c8310d916dea" rel="noreferrer">blog post</a>), so the question no longer applies. The following answer applied to beta 2:</p> <hr> <p>It's for performance reasons. Basically, they try to avoid copying arrays as long as they can (and claim "C-like performance"). To quote the language <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_112" rel="noreferrer">book</a>:</p> <blockquote> <p>For arrays, copying only takes place when you perform an action that has the potential to modify the length of the array. This includes appending, inserting, or removing items, or using a ranged subscript to replace a range of items in the array.</p> </blockquote> <p>I agree that this is a bit confusing, but at least there is a clear and simple description of how it works.</p> <p>That section also includes information on how to make sure an array is uniquely referenced, how to force-copy arrays, and how to check whether two arrays share storage.</p>
{ "question_id": 24081009, "question_date": "2014-06-06T11:41:14.423Z", "question_score": 219, "tags": "arrays|swift", "answer_id": 24081412, "answer_date": "2014-06-06T12:03:58.863Z", "answer_score": 111 }
Please answer the following Stack Overflow question: Title: How to set 'X-Frame-Options' on iframe? <p>If I create an <code>iframe</code> like this: </p> <pre><code>var dialog = $('&lt;div id="' + dialogId + '" align="center"&gt;&lt;iframe id="' + frameId + '" src="' + url + '" width="100%" frameborder="0" height="'+frameHeightForIe8+'" data-ssotoken="' + token + '"&gt;&lt;/iframe&gt;&lt;/div&gt;').dialog({ </code></pre> <p>How can I fix the error:</p> <blockquote> <p>Refused to display <code>'https://www.google.com.ua/?gws_rd=ssl'</code> in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.</p> </blockquote> <p>with JavaScript?</p>
<p>You can't set <code>X-Frame-Options</code> on the <code>iframe</code>. That is a response header set by the domain from which you are requesting the resource (<code>google.com.ua</code> in your example). They have set the header to <code>SAMEORIGIN</code> in this case, which means that they have disallowed loading of the resource in an <code>iframe</code> outside of their domain. For more information see <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options">The X-Frame-Options response header</a> on MDN.</p> <p>A quick inspection of the headers (shown here in Chrome developer tools) reveals the <code>X-Frame-Options</code> value returned from the host.</p> <p><img src="https://i.stack.imgur.com/bjM2C.png" alt="enter image description here"></p>
{ "question_id": 27358966, "question_date": "2014-12-08T13:20:44.490Z", "question_score": 218, "tags": "javascript|x-frame-options", "answer_id": 27359031, "answer_date": "2014-12-08T13:23:55.353Z", "answer_score": 277 }
Please answer the following Stack Overflow question: Title: Shell Script: Execute a python program from within a shell script <p>I've tried googling the answer but with no luck.</p> <p>I need to use my works supercomputer server, but for my python script to run, it must be executed via a shell script.</p> <p>For example I want <code>job.sh</code> to execute <code>python_script.py</code></p> <p>How can this be accomplished?</p>
<p>Just make sure the python executable is in your PATH environment variable then add in your script</p> <pre><code>python path/to/the/python_script.py </code></pre> <p>Details:</p> <ul> <li>In the file job.sh, put this</li> </ul> <blockquote> <pre><code>#!/bin/sh python python_script.py </code></pre> </blockquote> <ul> <li>Execute this command to make the script runnable for you : <code>chmod u+x job.sh</code></li> <li>Run it : <code>./job.sh</code></li> </ul>
{ "question_id": 4377109, "question_date": "2010-12-07T13:30:53.493Z", "question_score": 218, "tags": "python|shell", "answer_id": 4377147, "answer_date": "2010-12-07T13:34:45.980Z", "answer_score": 266 }
Please answer the following Stack Overflow question: Title: How can I loop through a List<T> and grab each item? <p>How can I loop through a List and grab each item? </p> <p>I want the output to look like this:</p> <pre><code>Console.WriteLine("amount is {0}, and type is {1}", myMoney.amount, myMoney.type); </code></pre> <p>Here is my code:</p> <pre><code>static void Main(string[] args) { List&lt;Money&gt; myMoney = new List&lt;Money&gt; { new Money{amount = 10, type = "US"}, new Money{amount = 20, type = "US"} }; } class Money { public int amount { get; set; } public string type { get; set; } } </code></pre>
<p><code>foreach</code>:</p> <pre><code>foreach (var money in myMoney) { Console.WriteLine("Amount is {0} and type is {1}", money.amount, money.type); } </code></pre> <p><a href="http://msdn.microsoft.com/en-us/library/vstudio/ttw7t8t6.aspx">MSDN Link</a></p> <p>Alternatively, because it is a <code>List&lt;T&gt;</code>.. which implements an indexer method <code>[]</code>, you can use a normal <code>for</code> loop as well.. although its less readble (IMO):</p> <pre><code>for (var i = 0; i &lt; myMoney.Count; i++) { Console.WriteLine("Amount is {0} and type is {1}", myMoney[i].amount, myMoney[i].type); } </code></pre>
{ "question_id": 18863187, "question_date": "2013-09-18T03:03:24.423Z", "question_score": 218, "tags": "c#|for-loop|collections", "answer_id": 18863216, "answer_date": "2013-09-18T03:08:14.467Z", "answer_score": 333 }
Please answer the following Stack Overflow question: Title: SQL Server String or binary data would be truncated <p>I am involved in a data migration project. I am getting the following error when I try to insert data from one table into another table (SQL Server 2005):</p> <blockquote> <p>Msg 8152, Level 16, State 13, Line 1<br> String or binary data would be truncated.</p> </blockquote> <p>The source data columns match the data type and are within the length definitions of the destination table columns so I am at a loss as to what could be causing this error.</p>
<p>You will need to post the table definitions for the source and destination tables for us to figure out where the issue is but <strong>the bottom line is that one of your columns in the source table is bigger than your destination columns</strong>. It could be that you are changing formats in a way you were not aware of. The database model you are moving from is important in figuring that out as well.</p>
{ "question_id": 6388756, "question_date": "2011-06-17T16:24:33.787Z", "question_score": 218, "tags": "sql-server|tsql|sql-server-2005|migration|data-migration", "answer_id": 6388820, "answer_date": "2011-06-17T16:30:29.873Z", "answer_score": 251 }
Please answer the following Stack Overflow question: Title: Tomcat: How to find out running Tomcat version? <p>I'm trying to get Appfuse + Tomcat + jRebel working.</p> <p>Appfuse by default uses Cargo to download tomcat (ver. 7.0.33) and deploy the application to it. I wish to use an already installed tomcat (ver. 7.0.27) instead of the downloaded one. I made the change following the <a href="http://appfuse.org/display/APF/FAQ#FAQ-useexistingtomcat" rel="noreferrer">appfuse FAQ</a>.</p> <p>After deploying with <code>mvn cargo:run</code>, how can I know that the actual running tomcat is indeed 7.0.27?</p> <p>I used to type a wrong URL (ex. <em>localhost:8080/dfsfsdf</em>) to see it in the error page, but now it shows nothing.</p> <p>My <code>$CATALINA_HOME</code> points to my own tomcat 7.0.27. sorry forgot to mention, it's for Windows.</p> <p>Update:</p> <p>Since this question had become somehow popular, I would like to explain why that accepted answer. simple, it was the first one which solved my problem.</p> <p>I am looking at the title of the question, <a href="https://stackoverflow.com/a/21773359/247869">@Tech Junkie</a> and <a href="https://stackoverflow.com/a/14925114/247869">@CPU 100</a> really have the best answer, but not for the scenario I was encountered. (I was wanting to know if <code>mvn cargo:run</code> runs my installed tomcat or a &quot;project embeded&quot; tomcat) <code>:)</code></p>
<p>if you can upload a JSP file you may print out some info like in this example: <a href="http://www.bestdesigns.co.in/blog/check-jsp-tomcat-version" rel="noreferrer">bestdesigns.co.in/blog/check-jsp-tomcat-version</a></p> <p>Save this code into a file called tomcat_version.jsp:</p> <pre><code> Tomcat Version : &lt;%= application.getServerInfo() %&gt;&lt;br&gt; Servlet Specification Version : &lt;%= application.getMajorVersion() %&gt;.&lt;%= application.getMinorVersion() %&gt; &lt;br&gt; JSP version : &lt;%=JspFactory.getDefaultFactory().getEngineInfo().getSpecificationVersion() %&gt;&lt;br&gt; </code></pre> <p>When you access, <a href="http://example.com/tomcat_version.jsp" rel="noreferrer">http://example.com/tomcat_version.jsp</a>, the output should look similar to:</p> <pre><code>Tomcat Version : Apache Tomcat/5.5.25 Servlet Specification Version : 2.4 JSP version: 2.0 </code></pre>
{ "question_id": 14925073, "question_date": "2013-02-17T19:22:20.593Z", "question_score": 218, "tags": "java|tomcat|appfuse", "answer_id": 14938856, "answer_date": "2013-02-18T14:42:47.300Z", "answer_score": 52 }
Please answer the following Stack Overflow question: Title: How to return 2 values from a Java method? <p>I am trying to return 2 values from a Java method but I get these errors. Here is my code:</p> <pre><code>// Method code public static int something(){ int number1 = 1; int number2 = 2; return number1, number2; } // Main method code public static void main(String[] args) { something(); System.out.println(number1 + number2); } </code></pre> <p>Error:</p> <pre><code>Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - missing return statement at assignment.Main.something(Main.java:86) at assignment.Main.main(Main.java:53) </code></pre> <p>Java Result: 1</p>
<p>Instead of returning an array that contains the two values or using a generic <code>Pair</code> class, consider creating a class that represents the result that you want to return, and return an instance of that class. Give the class a meaningful name. The benefits of this approach over using an array are type safety and it will make your program much easier to understand.</p> <p>Note: A generic <code>Pair</code> class, as proposed in some of the other answers here, also gives you type safety, but doesn't convey what the result represents.</p> <p>Example (which doesn't use really meaningful names):</p> <pre><code>final class MyResult { private final int first; private final int second; public MyResult(int first, int second) { this.first = first; this.second = second; } public int getFirst() { return first; } public int getSecond() { return second; } } // ... public static MyResult something() { int number1 = 1; int number2 = 2; return new MyResult(number1, number2); } public static void main(String[] args) { MyResult result = something(); System.out.println(result.getFirst() + result.getSecond()); } </code></pre>
{ "question_id": 2832472, "question_date": "2010-05-14T07:22:49.047Z", "question_score": 218, "tags": "java|function|return-value", "answer_id": 2832629, "answer_date": "2010-05-14T07:58:06.050Z", "answer_score": 279 }
Please answer the following Stack Overflow question: Title: Change size of axes title and labels in ggplot2 <p>I have a really simple question, which I am struggling to find the answer to. I hoped someone here might be able to help me.</p> <p>An example dataframe is presented below:</p> <pre><code>a &lt;- c(1:10) b &lt;- c(10:1) df &lt;- data.frame(a,b) library(ggplot2) g = ggplot(data=df) + geom_point(aes(x=a, y=b)) + xlab("x axis") g </code></pre> <p>I just want to learn how I change the text size of the axes titles and the axes labels.</p>
<p>You can change axis text and label size with arguments <code>axis.text=</code> and <code>axis.title=</code> in function <code>theme()</code>. If you need, for example, change only x axis title size, then use <code>axis.title.x=</code>.</p> <pre><code>g+theme(axis.text=element_text(size=12), axis.title=element_text(size=14,face=&quot;bold&quot;)) </code></pre> <p>There is good examples about setting of different <code>theme()</code> parameters in <a href="https://ggplot2.tidyverse.org/reference/theme.html" rel="noreferrer">ggplot2 page</a>.</p>
{ "question_id": 14942681, "question_date": "2013-02-18T18:10:39.593Z", "question_score": 218, "tags": "r|ggplot2", "answer_id": 14942760, "answer_date": "2013-02-18T18:15:27.513Z", "answer_score": 414 }
Please answer the following Stack Overflow question: Title: What exactly does the .join() method do? <p>I'm pretty new to Python and am completely confused by <code>.join()</code> which I have read is the preferred method for concatenating strings.</p> <p>I tried:</p> <pre><code>strid = repr(595) print array.array('c', random.sample(string.ascii_letters, 20 - len(strid))) .tostring().join(strid) </code></pre> <p>and got something like:</p> <pre><code>5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5 </code></pre> <p>Why does it work like this? Shouldn't the <code>595</code> just be automatically appended?</p>
<p>Look carefully at your output:</p> <pre><code>5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5 ^ ^ ^ </code></pre> <p>I've highlighted the "5", "9", "5" of your original string. The Python <a href="https://docs.python.org/3/library/stdtypes.html#str.join" rel="noreferrer"><code>join()</code></a> method is a string method, and takes a <em>list</em> of things to join with the string. A simpler example might help explain:</p> <pre><code>&gt;&gt;&gt; ",".join(["a", "b", "c"]) 'a,b,c' </code></pre> <p>The "," is inserted between each element of the given list. In your case, your "list" is the string representation "595", which is treated as the list ["5", "9", "5"].</p> <p>It appears that you're looking for <code>+</code> instead:</p> <pre><code>print array.array('c', random.sample(string.ascii_letters, 20 - len(strid))) .tostring() + strid </code></pre>
{ "question_id": 1876191, "question_date": "2009-12-09T19:22:04.747Z", "question_score": 218, "tags": "python|list|string", "answer_id": 1876206, "answer_date": "2009-12-09T19:25:02.400Z", "answer_score": 312 }
Please answer the following Stack Overflow question: Title: pandas: multiple conditions while indexing data frame - unexpected behavior <p>I am filtering rows in a dataframe by values in two columns.</p> <p>For some reason the OR operator behaves like I would expect AND operator to behave and vice versa.</p> <p>My test code:</p> <pre class="lang-py prettyprint-override"><code>df = pd.DataFrame({'a': range(5), 'b': range(5) }) # let's insert some -1 values df['a'][1] = -1 df['b'][1] = -1 df['a'][3] = -1 df['b'][4] = -1 df1 = df[(df.a != -1) &amp; (df.b != -1)] df2 = df[(df.a != -1) | (df.b != -1)] print(pd.concat([df, df1, df2], axis=1, keys = [ 'original df', 'using AND (&amp;)', 'using OR (|)',])) </code></pre> <p>And the result:</p> <pre class="lang-none prettyprint-override"><code> original df using AND (&amp;) using OR (|) a b a b a b 0 0 0 0 0 0 0 1 -1 -1 NaN NaN NaN NaN 2 2 2 2 2 2 2 3 -1 3 NaN NaN -1 3 4 4 -1 NaN NaN 4 -1 [5 rows x 6 columns] </code></pre> <p>As you can see, the <code>AND</code> operator drops every row in which at least one value equals <code>-1</code>. On the other hand, the <code>OR</code> operator requires both values to be equal to <code>-1</code> to drop them. I would expect exactly the opposite result. Could anyone explain this behavior?</p> <p>I am using pandas 0.13.1.</p>
<blockquote> <p>As you can see, the AND operator drops every row in which at least one value equals -1. On the other hand, the OR operator requires both values to be equal to -1 to drop them.</p> </blockquote> <p>That's right. Remember that you're writing the condition in terms of what you want to <em>keep</em>, not in terms of what you want to drop. For <code>df1</code>:</p> <pre><code>df1 = df[(df.a != -1) &amp; (df.b != -1)] </code></pre> <p>You're saying "keep the rows in which <code>df.a</code> isn't -1 and <code>df.b</code> isn't -1", which is the same as dropping every row in which at least one value is -1.</p> <p>For <code>df2</code>:</p> <pre><code>df2 = df[(df.a != -1) | (df.b != -1)] </code></pre> <p>You're saying "keep the rows in which either <code>df.a</code> or <code>df.b</code> is not -1", which is the same as dropping rows where both values are -1.</p> <p>PS: chained access like <code>df['a'][1] = -1</code> can get you into trouble. It's better to get into the habit of using <code>.loc</code> and <code>.iloc</code>.</p>
{ "question_id": 22591174, "question_date": "2014-03-23T12:52:59.133Z", "question_score": 218, "tags": "python|pandas|dataframe|indexing|boolean-logic", "answer_id": 22591267, "answer_date": "2014-03-23T13:02:05.893Z", "answer_score": 342 }
Please answer the following Stack Overflow question: Title: Left Join With Where Clause <p>I need to retrieve all default settings from the settings table but also grab the character setting if exists for x character. </p> <p>But this query is only retrieving those settings where character is = 1, not the default settings if the user havent setted anyone.</p> <pre><code>SELECT `settings`.*, `character_settings`.`value` FROM (`settings`) LEFT JOIN `character_settings` ON `character_settings`.`setting_id` = `settings`.`id` WHERE `character_settings`.`character_id` = '1' </code></pre> <p>So i should need something like this:</p> <pre><code>array( '0' =&gt; array('somekey' =&gt; 'keyname', 'value' =&gt; 'thevalue'), '1' =&gt; array('somekey2' =&gt; 'keyname2'), '2' =&gt; array('somekey3' =&gt; 'keyname3') ) </code></pre> <p>Where key 1 and 2 are the default values when key 0 contains the default value with the character value.</p>
<p>The <code>where</code> clause is filtering away rows where the <code>left join</code> doesn't succeed. Move it to the join:</p> <pre><code>SELECT `settings`.*, `character_settings`.`value` FROM `settings` LEFT JOIN `character_settings` ON `character_settings`.`setting_id` = `settings`.`id` AND `character_settings`.`character_id` = '1' </code></pre>
{ "question_id": 4752455, "question_date": "2011-01-20T20:52:47.713Z", "question_score": 218, "tags": "sql|left-join|where-clause", "answer_id": 4752507, "answer_date": "2011-01-20T20:57:58.437Z", "answer_score": 456 }
Please answer the following Stack Overflow question: Title: Fastest way to download a GitHub project <p>I need to download the source code of the project <a href="https://github.com/SpringSource/spring-data-graph-examples/" rel="noreferrer">Spring data graph example</a> into my box. It has public read-only access. Is there is an extremely fast way of downloading this code?</p> <p>I have no idea of working on GitHub/committing code and most tutorials out there on the web seems to assume that "I would want to setup a project in GitHub" and inundate me with 15-20 step processes. To me, if a source repository is available for the public, it should take less than 10 seconds to have that code in my filesystem.</p> <p>Tutorials that provide me with 15-20 step processes:</p> <ul> <li><a href="https://github.com/oscurrency/oscurrency/wiki/Setting-up-development-environment-on-ubuntu/" rel="noreferrer">Setting up development environment on Ubuntu</a></li> <li><a href="http://help.github.com/win-set-up-git/" rel="noreferrer">Win Setup on GIT</a></li> </ul> <p>I need something very very very simple. Just pull the source code, and I am more interested in seeing the source code and <em>not learn GitHub</em>.</p> <p>Are there any fast pointers/tutorials? (I have a GitHub account.)</p>
<p>When you are on a project page, you can press the <code>Download ZIP</code> button which is located under the green <code>&lt;&gt; Code</code> drop down:</p> <p><a href="https://i.stack.imgur.com/89Oxe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/89Oxe.png" alt="Screenshot showing &quot;Download ZIP&quot; button" /></a></p> <p>This allows you to download the most recent version of the code as a zip archive.</p> <p>If you aren't seeing that button, it is likely because you aren't on the main project page. To get there, click on the left-most tab labeled <code>&lt;&gt; Code</code>.</p>
{ "question_id": 6466945, "question_date": "2011-06-24T11:13:57.547Z", "question_score": 218, "tags": "git|github", "answer_id": 6466993, "answer_date": "2011-06-24T11:18:05.697Z", "answer_score": 262 }
Please answer the following Stack Overflow question: Title: Bootstrap table without stripe / borders <p>I'm kinda stuck with a CSS problem while using Bootstrap. I'm also using Angular JS with Angular UI.bootstrap (which might be part of the problem).</p> <p>I'm making a website that displays data in a table. Sometime, the data contains object that I have to display in tables. So I want to put borderless tables inside a normal table while keeping inside separation lines for the borderless tables. </p> <p>But it seems that even if I specifically say to not show the borders on a table, it is forced:</p> <p>HTML:</p> <pre><code>&lt;table class='table borderless'&gt; </code></pre> <p>CSS:</p> <pre><code>.borderless table { border-top-style: none; border-left-style: none; border-right-style: none; border-bottom-style: none; } </code></pre> <p>So here, what I want is just the inside borders.</p>
<p>The border styling is set on the <code>td</code> elements.</p> <p>html:</p> <pre><code>&lt;table class='table borderless'&gt; </code></pre> <p>css:</p> <pre><code>.borderless td, .borderless th { border: none; } </code></pre> <p><strong>Update:</strong> Since Bootstrap 4.1 you can use <code>.table-borderless</code> to remove the border.</p> <p><a href="https://getbootstrap.com/docs/4.1/content/tables/#borderless-table" rel="noreferrer">https://getbootstrap.com/docs/4.1/content/tables/#borderless-table</a></p>
{ "question_id": 18075794, "question_date": "2013-08-06T08:59:52.373Z", "question_score": 218, "tags": "html|css|twitter-bootstrap", "answer_id": 18076167, "answer_date": "2013-08-06T09:18:12.247Z", "answer_score": 337 }
Please answer the following Stack Overflow question: Title: CSS checkbox input styling <p>Any style for <code>input</code> affects every input element. Is there a way to specify styling to apply for only checkboxes without applying a class to each check box element?</p>
<p>With CSS 2 you can do this:</p> <pre><code>input[type='checkbox'] { ... } </code></pre> <p>This should be pretty widely supported by now. <a href="https://webdesign.tutsplus.com/articles/quick-tip-easy-css3-checkboxes-and-radio-buttons--webdesign-8953" rel="noreferrer">See support for browsers</a></p>
{ "question_id": 1120879, "question_date": "2009-07-13T17:22:09.220Z", "question_score": 218, "tags": "css", "answer_id": 1120886, "answer_date": "2009-07-13T17:23:58.373Z", "answer_score": 381 }
Please answer the following Stack Overflow question: Title: How do I fix a NoSuchMethodError? <p>I'm getting a <code>NoSuchMethodError</code> error when running my Java program. What's wrong and how do I fix it?</p>
<p>Without any more information it is difficult to pinpoint the problem, but the root cause is that you most likely have compiled a class against a different version of the class that is missing a method, than the one you are using when running it.</p> <p>Look at the stack trace ... If the exception appears when calling a method on an object in a library, you are most likely using separate versions of the library when compiling and running. Make sure you have the right version both places.</p> <p>If the exception appears when calling a method on objects instantiated by classes <em>you</em> made, then your build process seems to be faulty. Make sure the class files that you are actually running are updated when you compile.</p>
{ "question_id": 35186, "question_date": "2008-08-29T20:04:27.643Z", "question_score": 218, "tags": "java|nosuchmethoderror", "answer_id": 35210, "answer_date": "2008-08-29T20:14:56.353Z", "answer_score": 265 }
Please answer the following Stack Overflow question: Title: Difference between two dates in Python <p>I have two different dates and I want to know the difference in days between them. The format of the date is YYYY-MM-DD.</p> <p>I have a function that can ADD or SUBTRACT a given number to a date:</p> <pre><code>def addonDays(a, x): ret = time.strftime("%Y-%m-%d",time.localtime(time.mktime(time.strptime(a,"%Y-%m-%d"))+x*3600*24+3600)) return ret </code></pre> <p>where A is the date and x the number of days I want to add. And the result is another date.</p> <p>I need a function where I can give two dates and the result would be an int with date difference in days.</p>
<p>Use <code>-</code> to get the difference between two <code>datetime</code> objects and take the <code>days</code> member.</p> <pre><code>from datetime import datetime def days_between(d1, d2): d1 = datetime.strptime(d1, "%Y-%m-%d") d2 = datetime.strptime(d2, "%Y-%m-%d") return abs((d2 - d1).days) </code></pre>
{ "question_id": 8419564, "question_date": "2011-12-07T17:17:20.177Z", "question_score": 218, "tags": "python|date", "answer_id": 8419655, "answer_date": "2011-12-07T17:22:50.453Z", "answer_score": 417 }
Please answer the following Stack Overflow question: Title: How to parse JSON string in Typescript <p>Is there a way to parse strings as JSON in Typescript.<br> Example: In JS, we can use <code>JSON.parse()</code>. Is there a similar function in Typescript?</p> <p>I have a JSON object string as follows:</p> <pre class="lang-json prettyprint-override"><code>{"name": "Bob", "error": false} </code></pre>
<p>Typescript is (a superset of) javascript, so you just use <code>JSON.parse</code> as you would in javascript:</p> <pre><code>let obj = JSON.parse(jsonString); </code></pre> <p>Only that in typescript you can have a type to the resulting object:</p> <pre><code>interface MyObj { myString: string; myNumber: number; } let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }'); console.log(obj.myString); console.log(obj.myNumber); </code></pre> <p>(<a href="https://www.typescriptlang.org/play/#src=interface%20MyObj%20%7B%0D%0A%20%20%20%20myString%3A%20string%3B%0D%0A%20%20%20%20myNumber%3A%20number%3B%0D%0A%7D%0D%0A%0D%0Alet%20obj%3A%20MyObj%20%3D%20JSON.parse(&#39;%7B%20%22myString%22%3A%20%22string%22%2C%20%22myNumber%22%3A%204%20%7D&#39;)%3B%0D%0Aconsole.log(obj.myString)%3B%0D%0Aconsole.log(obj.myNumber)%3B" rel="noreferrer">code in playground</a>)</p>
{ "question_id": 38688822, "question_date": "2016-07-31T22:15:32.880Z", "question_score": 218, "tags": "javascript|json|string|typescript", "answer_id": 38688861, "answer_date": "2016-07-31T22:22:37.743Z", "answer_score": 305 }
Please answer the following Stack Overflow question: Title: Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal <p>Even though JRE 8 is installed on my MAC OS Yosemite 10.10.3,while running the Android present in tools in sdk - the error - " No Java Runtime present,requesting to install " gets displayed in terminal- how do i solve this issue?</p> <ol> <li><p>I wanted to install Xamarin test recorder - after installing they asked me to install Android sdk</p></li> <li><p>SDK is downloaded in Library/Developer/Xamarin/android-sdk </p></li> <li><p>Now when I run Android present in tools folder - I get the error - No Java run time </p></li> <li><p>I've installed JRE 8 with get the verified java version from their site</p></li> </ol> <p>Can someone please help!!</p>
<p>You have to install the full JDK, not only the JRE.</p> <p>I had the same issue and solved by installing JDK.</p> <p>Please use <a href="https://www.oracle.com/java/technologies/downloads/#java18" rel="noreferrer">this link</a> to download the latest JDK version 18.</p>
{ "question_id": 44009058, "question_date": "2017-05-16T18:31:09.023Z", "question_score": 218, "tags": "java|xamarin", "answer_id": 46828380, "answer_date": "2017-10-19T10:59:11.020Z", "answer_score": 205 }
Please answer the following Stack Overflow question: Title: How to trigger jQuery change event in code <p>I have a change event that is working fine but I need to get it to recurse.</p> <p>So I have a function that is triggered on change that will &quot;change&quot; other drop downs based on a class selector (notice &quot;drop downS&quot;, there could be more than one). This proxy change does not trigger the function and so fails. How can I get it to work?</p> <h3>Code</h3> <pre><code>$(document).ready(function () { var activeDropBox = null; $(&quot;select.drop-box&quot;).change(function () { var questionId = $(this).attr(&quot;questionId&quot;); var selectedAnswer = $(this).val(); activeDropBox = this; alert(this.questionId); $.ajax( { type: &quot;POST&quot;, url: answerChangedActionUrl, data: { questionId: questionId, selectedValue: selectedAnswer }, success: function (data) { SetElementVisibility(data.ShowElement, questionId); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert('XMLHttpRequest:' + XMLHttpRequest.responseText); alert('textStatus:' + textStatus); alert('errorThrown:' + errorThrown); } }); }); function SetElementVisibility(visible, questionId) { // I would like each child to then trigger the change event... $(&quot;.childOf&quot; + questionId)[visible ? 'show' : 'hide']('slow'); // Suggested code //$(&quot;.childOf&quot; + questionId + &quot; select&quot;).trigger(&quot;change&quot;); if (!visible) { $(&quot;.childOf&quot; + questionId + &quot; select&quot;).attr('selectedIndex', 0); } } } </code></pre> <p>The suggestions so far seem to work, but as the change event triggers an ajax post it now seems to fail here. I'm going to play around with it but that is something for another question I feel.</p>
<p>Use the <a href="http://api.jquery.com/trigger/" rel="noreferrer">trigger() method</a> </p> <pre><code>$(selector).trigger("change"); </code></pre>
{ "question_id": 4247264, "question_date": "2010-11-22T15:48:30.617Z", "question_score": 218, "tags": "javascript|jquery|jquery-events", "answer_id": 4247299, "answer_date": "2010-11-22T15:51:14.110Z", "answer_score": 482 }
Please answer the following Stack Overflow question: Title: bash : Bad Substitution <pre><code>#!/bin/bash jobname=&quot;job_201312161447_0003&quot; jobname_pre=${jobname:0:16} jobname_post=${jobname:17} </code></pre> <p>This bash script gives me Bad substitution error on ubuntu. Any help will be highly appreciated.</p>
<p>The default shell (<code>/bin/sh</code>) under Ubuntu points to <code>dash</code>, not <code>bash</code>.</p> <pre><code>me@pc:~$ readlink -f $(which sh) /bin/dash </code></pre> <p>So if you <code>chmod +x your_script_file.sh</code> and then run it with <code>./your_script_file.sh</code>, or if you run it with <code>bash your_script_file.sh</code>, it should work fine.</p> <p>Running it with <code>sh your_script_file.sh</code> will not work because the hashbang line will be ignored and the script will be interpreted by <code>dash</code>, which does not support that string substitution syntax.</p>
{ "question_id": 20615217, "question_date": "2013-12-16T16:01:20.163Z", "question_score": 218, "tags": "string|bash|ubuntu|substitution", "answer_id": 20616103, "answer_date": "2013-12-16T16:44:24.003Z", "answer_score": 268 }
Please answer the following Stack Overflow question: Title: Return a `struct` from a function in C <p>Today I was teaching a couple of friends how to use C <code>struct</code>s. One of them asked if you could return a <code>struct</code> from a function, to which I replied: &quot;No! You'd return pointers to dynamically <code>malloc</code>ed <code>struct</code>s instead.&quot;</p> <p>Coming from someone who primarily does C++, I was expecting not be able to return <code>struct</code>s by values. In C++ you can overload the <code>operator =</code> for your objects and makes complete sense to have a function to return your object by value. In C, however, you do not have that option and so it got me thinking what the compiler is actually doing. Consider the following:</p> <pre><code>struct MyObj{ double x, y; }; struct MyObj foo(){ struct MyObj a; a.x = 10; a.y = 10; return a; } int main () { struct MyObj a; a = foo(); // This DOES work struct b = a; // This does not work return 0; } </code></pre> <p>I understand why <code>struct b = a;</code> should not work -- you cannot overload <code>operator =</code> for your data type. How is it that <code>a = foo();</code> compiles fine? Does it mean something other than <code>struct b = a;</code>? Maybe the question to ask is: What exactly does the <code>return</code> statement in conjunction to <code>=</code> sign do?</p>
<p>You can return a structure from a function (or use the <code>=</code> operator) without any problems. It's a well-defined part of the language. The only problem with <code>struct b = a</code> is that you didn't provide a complete type. <code>struct MyObj b = a</code> will work just fine. You can pass structures <em>to</em> functions as well - a structure is exactly the same as any built-in type for purposes of parameter passing, return values, and assignment.</p> <p>Here's a simple demonstration program that does all three - passes a structure as a parameter, returns a structure from a function, and uses structures in assignment statements:</p> <pre><code>#include &lt;stdio.h&gt; struct a { int i; }; struct a f(struct a x) { struct a r = x; return r; } int main(void) { struct a x = { 12 }; struct a y = f(x); printf("%d\n", y.i); return 0; } </code></pre> <p>The next example is pretty much exactly the same, but uses the built-in <code>int</code> type for demonstration purposes. The two programs have the same behaviour with respect to pass-by-value for parameter passing, assignment, etc.:</p> <pre><code>#include &lt;stdio.h&gt; int f(int x) { int r = x; return r; } int main(void) { int x = 12; int y = f(x); printf("%d\n", y); return 0; } </code></pre>
{ "question_id": 9653072, "question_date": "2012-03-11T06:59:31.863Z", "question_score": 218, "tags": "c", "answer_id": 9653083, "answer_date": "2012-03-11T07:01:49.733Z", "answer_score": 261 }
Please answer the following Stack Overflow question: Title: ALTER TABLE to add a composite primary key <p>I have a table called <code>provider</code>. I have three columns called <code>person</code>, <code>place</code>, <code>thing</code>. There can be duplicate persons, duplicate places, and duplicate things, but there can never be a dupicate person-place-thing combination.</p> <p>How would I ALTER TABLE to add a composite primary key for this table in MySQL with the these three columns?</p>
<pre><code>ALTER TABLE provider ADD PRIMARY KEY(person,place,thing); </code></pre> <p>If a primary key already exists then you want to do this</p> <pre><code>ALTER TABLE provider DROP PRIMARY KEY, ADD PRIMARY KEY(person, place, thing); </code></pre>
{ "question_id": 8859353, "question_date": "2012-01-14T01:20:26.803Z", "question_score": 218, "tags": "mysql|sql|primary-key|alter-table|composite-primary-key", "answer_id": 8859374, "answer_date": "2012-01-14T01:24:58.120Z", "answer_score": 476 }
Please answer the following Stack Overflow question: Title: Converting a Date object to a calendar object <p>So I get a date attribute from an incoming object in the form:</p> <pre><code>Tue May 24 05:05:16 EDT 2011 </code></pre> <p>I am writing a simple helper method to convert it to a calendar method, I was using the following code:</p> <pre><code> public static Calendar DateToCalendar(Date date ) { Calendar cal = null; try { DateFormat formatter = new SimpleDateFormat("yyyyMMdd"); date = (Date)formatter.parse(date.toString()); cal=Calendar.getInstance(); cal.setTime(date); } catch (ParseException e) { System.out.println("Exception :"+e); } return cal; } </code></pre> <p>To simulate the incoming object I am just assigning the values within the code currently using:</p> <pre><code>private Date m_lastActivityDate = new Date(); </code></pre> <p>However this is givin me a null pointer once the method reaches:</p> <pre><code>date = (Date)formatter.parse(date.toString()); </code></pre>
<p>Here's your method:</p> <pre><code>public static Calendar toCalendar(Date date){ Calendar cal = Calendar.getInstance(); cal.setTime(date); return cal; } </code></pre> <p>Everything else you are doing is both wrong and unnecessary.</p> <p>BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: <code>dateToCalendar</code> or <code>toCalendar</code> (as shown).</p> <hr> <p>OK, let's milk your code, shall we?</p> <pre><code>DateFormat formatter = new SimpleDateFormat("yyyyMMdd"); date = (Date)formatter.parse(date.toString()); </code></pre> <p><code>DateFormat</code> is used to convert Strings to Dates (<code>parse()</code>) or Dates to Strings (<code>format()</code>). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?</p>
{ "question_id": 6185966, "question_date": "2011-05-31T10:05:17.727Z", "question_score": 218, "tags": "java|date|calendar|nullpointerexception", "answer_id": 6186006, "answer_date": "2011-05-31T10:09:33.597Z", "answer_score": 502 }
Please answer the following Stack Overflow question: Title: Could not connect to Redis at 127.0.0.1:6379: Connection refused with homebrew <p>Using homebrew to install Redis but when I try to ping Redis it shows this error:</p> <pre><code>Could not connect to Redis at 127.0.0.1:6379: Connection refused </code></pre> <p><strong>Note :</strong> I tried to turn off firewall and edit conf file but still cannot ping. I am using macOS Sierra and homebrew version 1.1.11</p>
<p>After installing <code>redis</code>, type from <code>terminal</code>:</p> <pre><code>redis-server </code></pre> <p>And Redis-Server will be started</p>
{ "question_id": 42857551, "question_date": "2017-03-17T12:27:14.333Z", "question_score": 218, "tags": "redis|redis-server", "answer_id": 42858651, "answer_date": "2017-03-17T13:20:25.243Z", "answer_score": 475 }
Please answer the following Stack Overflow question: Title: How to make a countdown timer in Android? <p>I have two EditTexts in XML. In one EditText, the user can put a number as minutes and in another EditText, a number as seconds. After clicking the finish button, the seconds EditText should start to countdown and update its text every second. </p> <p>Additionally, how can I keep it updating until it gets to zero minutes and zero seconds?</p>
<p>As shown in <a href="https://developer.android.com/reference/android/os/CountDownTimer#java" rel="noreferrer">the documentation for <code>CountDownTimer</code></a>:</p> <blockquote> <pre class="lang-java prettyprint-override"><code>new CountDownTimer(30000, 1000) { public void onTick(long millisUntilFinished) { mTextField.setText(&quot;seconds remaining: &quot; + millisUntilFinished / 1000); // logic to set the EditText could go here } public void onFinish() { mTextField.setText(&quot;done!&quot;); } }.start(); </code></pre> </blockquote>
{ "question_id": 10032003, "question_date": "2012-04-05T16:02:33.977Z", "question_score": 218, "tags": "android|timer|countdown", "answer_id": 10032406, "answer_date": "2012-04-05T16:30:20.540Z", "answer_score": 506 }
Please answer the following Stack Overflow question: Title: Search for all occurrences of a string in a mysql database <p>I'm trying to figure out how to locate all occurrences of a url in a database. I want to search all tables and all fields. But I have no idea where to start or if it's even possible.</p>
<p>A simple solution would be doing something like this:</p> <pre class="lang-sh prettyprint-override"><code>mysqldump -u myuser --no-create-info --extended-insert=FALSE databasename | grep -i "&lt;search string&gt;" </code></pre>
{ "question_id": 562457, "question_date": "2009-02-18T19:23:17.357Z", "question_score": 218, "tags": "mysql", "answer_id": 562501, "answer_date": "2009-02-18T19:34:55.317Z", "answer_score": 244 }
Please answer the following Stack Overflow question: Title: How do I center text vertically and horizontally in Flutter? <p>I'd like to know how to center the contents of a Text widget vertically and horizontally in Flutter. I only know how to center the widget itself using <code>Center(child: Text(&quot;test&quot;))</code> but not the content itself. By default, it's aligned to the left. In Android, I believe the property of a TextView that achieves this is called <code>gravity</code>.</p> <p>Example of what I want:</p> <p><a href="https://i.stack.imgur.com/mRIob.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mRIob.png" alt="centered text example" /></a></p>
<p>Text alignment center property setting only horizontal alignment. </p> <p><a href="https://i.stack.imgur.com/4CP6P.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4CP6P.png" alt="enter image description here"></a></p> <p>I used below code to set text vertically and horizontally center.</p> <p><a href="https://i.stack.imgur.com/SI557.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SI557.png" alt="enter image description here"></a></p> <p>Code:</p> <pre><code> child: Center( child: Text( "Hello World", textAlign: TextAlign.center, ), ), </code></pre>
{ "question_id": 50554110, "question_date": "2018-05-27T16:16:37.900Z", "question_score": 218, "tags": "user-interface|text|widget|alignment|flutter", "answer_id": 53407050, "answer_date": "2018-11-21T07:21:20.413Z", "answer_score": 469 }
Please answer the following Stack Overflow question: Title: how to mysqldump remote db from local machine <p>I need to do a mysqldump of a database on a remote server, but the server does not have mysqldump installed. I would like to use the mysqldump on my machine to connect to the remote database and do the dump on my machine.</p> <p>I have tried to create an ssh tunnel and then do the dump, but this does not seem to work. I tried:</p> <pre><code>ssh -f -L3310:remote.server:3306 [email protected] -N </code></pre> <p>The tunnel is created with success. If I do </p> <pre><code>telnet localhost 3310 </code></pre> <p>I get some blurb which shows the correct server mysql version. However, doing the following seems to try to connect locally</p> <pre><code>mysqldump -P 3310 -h localhost -u mysql_user -p database_name table_name </code></pre>
<p>As I haven't seen it at serverfault yet, and the answer is quite simple:</p> <p>Change:</p> <pre><code>ssh -f -L3310:remote.server:3306 [email protected] -N </code></pre> <p>To:</p> <pre><code>ssh -f -L3310:localhost:3306 [email protected] -N </code></pre> <p>And change:</p> <pre><code>mysqldump -P 3310 -h localhost -u mysql_user -p database_name table_name </code></pre> <p>To: </p> <pre><code>mysqldump -P 3310 -h 127.0.0.1 -u mysql_user -p database_name table_name </code></pre> <p>(do not use localhost, it's one of these 'special meaning' nonsense that probably connects by socket rather then by port)</p> <p><strong>edit</strong>: well, to elaborate: if host is set to <code>localhost</code>, a configured (or default) <code>--socket</code> option is assumed. See <a href="http://dev.mysql.com/doc/refman/5.5/en/option-files.html" rel="noreferrer">the manual</a> for which option files are sought / used. Under Windows, this can be a named pipe.</p>
{ "question_id": 2989724, "question_date": "2010-06-07T13:06:46.300Z", "question_score": 218, "tags": "mysql|mysqldump", "answer_id": 2990732, "answer_date": "2010-06-07T15:21:09.940Z", "answer_score": 281 }
Please answer the following Stack Overflow question: Title: What is time_t ultimately a typedef to? <p>I searched my Linux box and saw this typedef:</p> <pre><code>typedef __time_t time_t; </code></pre> <p>But I could not find the <code>__time_t</code> definition.</p>
<p>The <a href="http://en.wikipedia.org/w/index.php?title=Time_t&amp;oldid=450752800" rel="noreferrer">time_t Wikipedia article</a> article sheds some light on this. The bottom line is that the type of <code>time_t</code> is not guaranteed in the C specification.</p> <blockquote> <p>The <code>time_t</code> datatype is a data type in the ISO C library defined for storing system time values. Such values are returned from the standard <code>time()</code> library function. This type is a typedef defined in the standard header. <strong>ISO C defines time_t as an arithmetic type, but does not specify any particular type</strong>, range, resolution, or encoding for it. Also unspecified are the meanings of arithmetic operations applied to time values.</p> <p><strong>Unix and POSIX-compliant systems implement the <code>time_t</code> type as a <code>signed integer</code> (typically 32 or 64 bits wide) which represents the number of seconds since the start of the Unix epoch</strong>: midnight UTC of January 1, 1970 (not counting leap seconds). Some systems correctly handle negative time values, while others do not. Systems using a 32-bit <code>time_t</code> type are susceptible to the <a href="http://en.wikipedia.org/wiki/Year_2038_problem" rel="noreferrer">Year 2038 problem</a>.</p> </blockquote>
{ "question_id": 471248, "question_date": "2009-01-22T23:12:55.203Z", "question_score": 218, "tags": "c|linux|types", "answer_id": 471287, "answer_date": "2009-01-22T23:29:26.887Z", "answer_score": 193 }
Please answer the following Stack Overflow question: Title: How do I convert a PDF document to a preview image in PHP? <p>What libraries, extensions etc. would be required to render a portion of a PDF document to an image file?</p> <p>Most PHP PDF libraries that I have found center around creating PDF documents, but is there a simple way to render a document to an image format suitable for web use?</p> <p>Our environment is a LAMP stack.</p>
<p>You need <a href="http://us3.php.net/imagick" rel="noreferrer"><code>ImageMagick</code></a> and <a href="https://www.ghostscript.com/download.html" rel="noreferrer"><code>GhostScript</code></a></p> <pre><code>&lt;?php $im = new imagick('file.pdf[0]'); $im-&gt;setImageFormat('jpg'); header('Content-Type: image/jpeg'); echo $im; ?&gt; </code></pre> <p>The <code>[0]</code> means <code>page 1</code>. </p>
{ "question_id": 467793, "question_date": "2009-01-22T01:47:25.610Z", "question_score": 218, "tags": "php|image|pdf|lamp", "answer_id": 467805, "answer_date": "2009-01-22T01:57:08.460Z", "answer_score": 244 }
Please answer the following Stack Overflow question: Title: Difference between window.location.href=window.location.href and window.location.reload() <p>What is the difference between JavaScript's</p> <pre><code>window.location.href = window.location.href </code></pre> <p>and </p> <pre><code>window.location.reload() </code></pre> <p>functions?</p>
<p>If I remember correctly, <code>window.location.reload()</code> reloads the current page with POST data, while <code>window.location.href=window.location.href</code> does not include the POST data.</p> <p>As noted by @W3Max in the comments below, <code>window.location.href=window.location.href</code> will not reload the page if there's an anchor (#) in the URL - You must use <code>window.location.reload()</code> in this case.</p> <p>Also, as noted by @Mic below, <code>window.location.reload()</code> takes an additional argument <code>skipCache</code> so that with using <code>window.location.reload(true)</code> the browser will skip the cache and reload the page from the server. <code>window.location.reload(false)</code> will do the opposite, and load the page from cache if possible.</p>
{ "question_id": 2405117, "question_date": "2010-03-08T22:00:32.617Z", "question_score": 218, "tags": "javascript", "answer_id": 2405203, "answer_date": "2010-03-08T22:14:10.540Z", "answer_score": 276 }
Please answer the following Stack Overflow question: Title: How can I remove a key and its value from an associative array? <p>Given an associative array:</p> <pre><code>array("key1" =&gt; "value1", "key2" =&gt; "value2", ...) </code></pre> <p>How would I go about removing a certain key-value pair, given the key?</p>
<p>You can use <a href="https://www.php.net/manual/en/function.unset.php" rel="nofollow noreferrer"><code>unset</code></a>:</p> <pre><code>unset($array['key-here']); </code></pre> <p><strong>Example:</strong></p> <pre><code>$array = array(&quot;key1&quot; =&gt; &quot;value1&quot;, &quot;key2&quot; =&gt; &quot;value2&quot;); print_r($array); unset($array['key1']); print_r($array); unset($array['key2']); print_r($array); </code></pre> <p><strong>Output:</strong></p> <pre><code>Array ( [key1] =&gt; value1 [key2] =&gt; value2 ) Array ( [key2] =&gt; value2 ) Array ( ) </code></pre>
{ "question_id": 3053517, "question_date": "2010-06-16T13:14:01.930Z", "question_score": 218, "tags": "php|arrays", "answer_id": 3053528, "answer_date": "2010-06-16T13:15:15.927Z", "answer_score": 424 }
Please answer the following Stack Overflow question: Title: How to create a Java Date object of midnight today and midnight tomorrow? <p>In my code I need to find all my things that happened today. So I need to compare against dates from today at 00:00 AM (midnight early this morning) to 12:00 PM (midnight tonight).</p> <p>I know ...</p> <pre><code>Date today = new Date(); </code></pre> <p>... gets me right now. And ...</p> <pre><code>Date beginning = new Date(0); </code></pre> <p>... gets me zero time on Jan 1, 1970. But what's an easy way to get zero time today and zero time tomorrow?</p> <hr /> <h2>UPDATE</h2> <p>I did this, but surely there's an easier way?</p> <pre><code>Calendar calStart = new GregorianCalendar(); calStart.setTime(new Date()); calStart.set(Calendar.HOUR_OF_DAY, 0); calStart.set(Calendar.MINUTE, 0); calStart.set(Calendar.SECOND, 0); calStart.set(Calendar.MILLISECOND, 0); Date midnightYesterday = calStart.getTime(); Calendar calEnd = new GregorianCalendar(); calEnd.setTime(new Date()); calEnd.set(Calendar.DAY_OF_YEAR, calEnd.get(Calendar.DAY_OF_YEAR)+1); calEnd.set(Calendar.HOUR_OF_DAY, 0); calEnd.set(Calendar.MINUTE, 0); calEnd.set(Calendar.SECOND, 0); calEnd.set(Calendar.MILLISECOND, 0); Date midnightTonight = calEnd.getTime(); </code></pre>
<h1>java.util.Calendar</h1> <pre><code>// today Calendar date = new GregorianCalendar(); // reset hour, minutes, seconds and millis date.set(Calendar.HOUR_OF_DAY, 0); date.set(Calendar.MINUTE, 0); date.set(Calendar.SECOND, 0); date.set(Calendar.MILLISECOND, 0); // next day date.add(Calendar.DAY_OF_MONTH, 1); </code></pre> <hr> <h1>JDK 8 - java.time.LocalTime and java.time.LocalDate</h1> <pre><code>LocalTime midnight = LocalTime.MIDNIGHT; LocalDate today = LocalDate.now(ZoneId.of("Europe/Berlin")); LocalDateTime todayMidnight = LocalDateTime.of(today, midnight); LocalDateTime tomorrowMidnight = todayMidnight.plusDays(1); </code></pre> <hr> <h1>Joda-Time</h1> <p>If you're using a JDK &lt; 8, I recommend <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda Time</a>, because the API is really nice: <strike></p> <pre><code>DateTime date = new DateTime().toDateMidnight().toDateTime(); DateTime tomorrow = date.plusDays(1); </code></pre> <h2></strike></h2> <p>Since version 2.3 of Joda Time <code>DateMidnight</code> is <strong>deprecated</strong>, so use this:</p> <pre><code>DateTime today = new DateTime().withTimeAtStartOfDay(); DateTime tomorrow = today.plusDays(1).withTimeAtStartOfDay(); </code></pre> <p>Pass a time zone if you don't want the JVM’s current default time zone.</p> <pre><code>DateTimeZone timeZone = DateTimeZone.forID("America/Montreal"); DateTime today = new DateTime(timeZone).withTimeAtStartOfDay(); // Pass time zone to constructor. </code></pre>
{ "question_id": 6850874, "question_date": "2011-07-27T20:34:18.947Z", "question_score": 218, "tags": "java|date", "answer_id": 6850919, "answer_date": "2011-07-27T20:37:55.243Z", "answer_score": 404 }
Please answer the following Stack Overflow question: Title: Keras, How to get the output of each layer? <p>I have trained a binary classification model with CNN, and here is my code</p> <pre><code>model = Sequential() model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1], border_mode='valid', input_shape=input_shape)) model.add(Activation('relu')) model.add(Convolution2D(nb_filters, kernel_size[0], kernel_size[1])) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=pool_size)) # (16, 16, 32) model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1])) model.add(Activation('relu')) model.add(Convolution2D(nb_filters*2, kernel_size[0], kernel_size[1])) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=pool_size)) # (8, 8, 64) = (2048) model.add(Flatten()) model.add(Dense(1024)) model.add(Activation('relu')) model.add(Dropout(0.5)) model.add(Dense(2)) # define a binary classification problem model.add(Activation('softmax')) model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size, nb_epoch=nb_epoch, verbose=1, validation_data=(x_test, y_test)) </code></pre> <p>And here, I wanna get the output of each layer just like TensorFlow, how can I do that?</p>
<p>You can easily get the outputs of any layer by using: <code>model.layers[index].output</code></p> <p>For all layers use this:</p> <pre><code>from keras import backend as K inp = model.input # input placeholder outputs = [layer.output for layer in model.layers] # all layer outputs functors = [K.function([inp, K.learning_phase()], [out]) for out in outputs] # evaluation functions # Testing test = np.random.random(input_shape)[np.newaxis,...] layer_outs = [func([test, 1.]) for func in functors] print layer_outs </code></pre> <p>Note: To simulate Dropout use <code>learning_phase</code> as <code>1.</code> in <code>layer_outs</code> otherwise use <code>0.</code></p> <p><strong>Edit:</strong> (based on comments)</p> <p><code>K.function</code> creates theano/tensorflow tensor functions which is later used to get the output from the symbolic graph given the input. </p> <p>Now <code>K.learning_phase()</code> is required as an input as many Keras layers like Dropout/Batchnomalization depend on it to change behavior during training and test time. </p> <p>So if you remove the dropout layer in your code you can simply use:</p> <pre><code>from keras import backend as K inp = model.input # input placeholder outputs = [layer.output for layer in model.layers] # all layer outputs functors = [K.function([inp], [out]) for out in outputs] # evaluation functions # Testing test = np.random.random(input_shape)[np.newaxis,...] layer_outs = [func([test]) for func in functors] print layer_outs </code></pre> <p><strong>Edit 2: More optimized</strong></p> <p>I just realized that the previous answer is not that optimized as for each function evaluation the data will be transferred CPU->GPU memory and also the tensor calculations needs to be done for the lower layers over-n-over. </p> <p>Instead this is a much better way as you don't need multiple functions but a single function giving you the list of all outputs:</p> <pre><code>from keras import backend as K inp = model.input # input placeholder outputs = [layer.output for layer in model.layers] # all layer outputs functor = K.function([inp, K.learning_phase()], outputs ) # evaluation function # Testing test = np.random.random(input_shape)[np.newaxis,...] layer_outs = functor([test, 1.]) print layer_outs </code></pre>
{ "question_id": 41711190, "question_date": "2017-01-18T04:07:16.950Z", "question_score": 218, "tags": "python|tensorflow|deep-learning|keras", "answer_id": 41712013, "answer_date": "2017-01-18T05:28:56.300Z", "answer_score": 233 }
Please answer the following Stack Overflow question: Title: Visual Studio Code - Convert spaces to tabs <p>I have both TypeScript and HTML files in my project, in both files tabs are converted to spaces.</p> <p>I want to turn the auto-conversion off and make sure that my project has only tabs.</p> <p>Edit:</p> <p>With this setting it seems to work in HTML files but not in TypeScript files.</p> <pre class="lang-json prettyprint-override"><code>{ &quot;editor.insertSpaces&quot;: false } </code></pre>
<p>There are 3 options in <code>.vscode/settings.json</code>:</p> <pre class="lang-json prettyprint-override"><code>// The number of spaces a tab is equal to. &quot;editor.tabSize&quot;: 4, // Insert spaces when pressing Tab. &quot;editor.insertSpaces&quot;: true, // When opening a file, `editor.tabSize` and `editor.insertSpaces` will be detected based on the file contents. &quot;editor.detectIndentation&quot;: true </code></pre> <p><code>editor.detectIndentation</code> detects it from your file, you have to disable it. If it didn't help, check that you have no settings with higher priority. For example when you save it to User settings it could be overwritten by Workspace settings which are in your project folder.</p> <p><em><strong>Update:</strong></em></p> <p>To access these settings, you can open <strong>File</strong> » <strong>Preferences</strong> » <strong>Settings</strong>, click the <em>Manage</em> cog icon at the bottom left, or use the keyboard shortcut:</p> <p><kbd><strong>CTRL</strong></kbd><strong>+</strong><kbd><strong>,</strong></kbd> <em>(Windows, Linux)</em></p> <p><kbd><strong>⌘</strong></kbd><strong>+</strong><kbd><strong>,</strong></kbd> <em>(Mac)</em></p> <p><em><strong>Update:</strong></em></p> <p>Now you have an alternative to editing those options manually. <br> Click on selector <strong>Spaces:4</strong> at the bottom-right of the editor:<br> <a href="https://i.stack.imgur.com/dYwfk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dYwfk.png" alt=" Ln44, Col . [Spaces:4] . UTF-8 with BOM . CTRLF . HTML . :)" /></a></p> <p><strong>EDIT:</strong><br> To convert existing indentation from spaces to tabs hit <kbd><strong>Ctrl</strong></kbd><strong>+</strong><kbd><strong>Shift</strong></kbd><strong>+</strong><kbd><strong>P</strong></kbd> and type:</p> <pre><code>&gt;Convert indentation to Tabs </code></pre> <p>This will change the indentation for your document based on the defined settings to Tabs.</p>
{ "question_id": 36814642, "question_date": "2016-04-23T18:14:54.937Z", "question_score": 218, "tags": "visual-studio-code|tabs|spaces", "answer_id": 36814851, "answer_date": "2016-04-23T18:34:09.550Z", "answer_score": 371 }
Please answer the following Stack Overflow question: Title: How might I find the largest number contained in a JavaScript array? <p>I have a simple JavaScript Array object containing a few numbers.</p> <pre><code>[267, 306, 108] </code></pre> <p>Is there a function that would find the largest number in this array?</p>
<p><a href="http://ejohn.org/blog/fast-javascript-maxmin/" rel="noreferrer">Resig to the rescue:</a></p> <pre><code>Array.max = function( array ){ return Math.max.apply( Math, array ); }; </code></pre> <p><strong>Warning</strong>: since <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply#Using_apply_and_built-in_functions" rel="noreferrer">the maximum number of arguments is as low as 65535 on some VMs</a>, use a for loop if you're not certain the array is that small.</p>
{ "question_id": 1379553, "question_date": "2009-09-04T14:17:51.780Z", "question_score": 218, "tags": "javascript|algorithm|arrays|max", "answer_id": 1379556, "answer_date": "2009-09-04T14:19:21.967Z", "answer_score": 323 }
Please answer the following Stack Overflow question: Title: How to transfer some data to another Fragment? <p>How to transfer some data to another <code>Fragment</code> likewise it was done with <code>extras</code> for <code>intents</code>?</p>
<p>Use a <code>Bundle</code>. Here's an example:</p> <pre><code>Fragment fragment = new Fragment(); Bundle bundle = new Bundle(); bundle.putInt(key, value); fragment.setArguments(bundle); </code></pre> <p>Bundle has put methods for lots of data types. See <a href="http://developer.android.com/reference/android/os/Bundle.html">this</a></p> <p>Then in your <code>Fragment</code>, retrieve the data (e.g. in <strong><code>onCreate()</code></strong> method) with:</p> <pre><code>Bundle bundle = this.getArguments(); if (bundle != null) { int myInt = bundle.getInt(key, defaultValue); } </code></pre>
{ "question_id": 7149802, "question_date": "2011-08-22T15:29:03.417Z", "question_score": 218, "tags": "android|android-fragments", "answer_id": 7149906, "answer_date": "2011-08-22T15:36:26.790Z", "answer_score": 521 }
Please answer the following Stack Overflow question: Title: How can I send an email by Java application using GMail, Yahoo, or Hotmail? <p>Is it possible to send an email from my Java application using a GMail account? I have configured my company mail server with Java app to send email, but that's not going to cut it when I distribute the application. Answers with any of using Hotmail, Yahoo or GMail are acceptable.</p>
<p>First download the <a href="https://java.net/projects/javamail/pages/Home" rel="noreferrer">JavaMail API</a> and make sure the relevant jar files are in your classpath.</p> <p>Here's a full working example using GMail.</p> <pre><code>import java.util.*; import javax.mail.*; import javax.mail.internet.*; public class Main { private static String USER_NAME = "*****"; // GMail user name (just the part before "@gmail.com") private static String PASSWORD = "********"; // GMail password private static String RECIPIENT = "[email protected]"; public static void main(String[] args) { String from = USER_NAME; String pass = PASSWORD; String[] to = { RECIPIENT }; // list of recipient email addresses String subject = "Java send mail example"; String body = "Welcome to JavaMail!"; sendFromGMail(from, pass, to, subject, body); } private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) { Properties props = System.getProperties(); String host = "smtp.gmail.com"; props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); InternetAddress[] toAddress = new InternetAddress[to.length]; // To get the array of addresses for( int i = 0; i &lt; to.length; i++ ) { toAddress[i] = new InternetAddress(to[i]); } for( int i = 0; i &lt; toAddress.length; i++) { message.addRecipient(Message.RecipientType.TO, toAddress[i]); } message.setSubject(subject); message.setText(body); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (AddressException ae) { ae.printStackTrace(); } catch (MessagingException me) { me.printStackTrace(); } } } </code></pre> <p>Naturally, you'll want to do more in the <code>catch</code> blocks than print the stack trace as I did in the example code above. (Remove the <code>catch</code> blocks to see which method calls from the JavaMail API throw exceptions so you can better see how to properly handle them.)</p> <hr> <p>Thanks to <a href="https://stackoverflow.com/users/4223/jodonnell">@jodonnel</a> and everyone else who answered. I'm giving him a bounty because his answer led me about 95% of the way to a complete answer.</p>
{ "question_id": 46663, "question_date": "2008-09-05T19:23:00.303Z", "question_score": 218, "tags": "java|email|gmail|jakarta-mail|mail-server", "answer_id": 47452, "answer_date": "2008-09-06T13:19:58.280Z", "answer_score": 200 }
Please answer the following Stack Overflow question: Title: Uint8Array to string in Javascript <p>I have some UTF-8 encoded data living in a range of Uint8Array elements in Javascript. Is there an efficient way to decode these out to a regular javascript string (I believe Javascript uses 16 bit Unicode)? I dont want to add one character at the time as the string concaternation would become to CPU intensive. </p>
<p><code>TextEncoder</code> and <code>TextDecoder</code> from the <a href="https://encoding.spec.whatwg.org/" rel="noreferrer">Encoding standard</a>, which is polyfilled by the <a href="https://github.com/inexorabletash/text-encoding" rel="noreferrer">stringencoding library</a>, converts between strings and ArrayBuffers:</p> <pre class="lang-js prettyprint-override"><code>var uint8array = new TextEncoder().encode(&quot;¢&quot;); var string = new TextDecoder().decode(uint8array); </code></pre>
{ "question_id": 8936984, "question_date": "2012-01-20T05:07:22.230Z", "question_score": 218, "tags": "javascript", "answer_id": 36949791, "answer_date": "2016-04-30T01:38:32.120Z", "answer_score": 330 }
Please answer the following Stack Overflow question: Title: psql: FATAL: Peer authentication failed for user "dev" <p>when i create a new user, but it cannot login the database.<br> I do that like this:</p> <pre><code>postgres@Aspire:/home/XXX$ createuser dev Shall the new role be a superuser? (y/n) n Shall the new role be allowed to create databases? (y/n) y Shall the new role be allowed to create more new roles? (y/n) y </code></pre> <p>then create a database: </p> <pre><code>postgres@Aspire:/home/XXX$ createdb -O dev test_development </code></pre> <p>after that, I try <code>psql -U dev -W test_development</code> to login, but get the error:</p> <pre><code>psql: FATAL: Peer authentication failed for user "dev" </code></pre> <p>I tried to solve the problem but failed.</p>
<p>Try:</p> <pre><code>psql -U user_name -h 127.0.0.1 -d db_name </code></pre> <p>where</p> <ul> <li><code>-U</code> is the database user name</li> <li><code>-h</code> is the hostname/IP of the local server, thus avoiding Unix domain sockets</li> <li><code>-d</code> is the database name to connect to</li> </ul> <p>This is then evaluated as a "network" connection by Postgresql rather than a Unix domain socket connection, thus not evaluated as a "local" connect as you might see in <code>pg_hba.conf</code>:</p> <pre><code>local all all peer </code></pre>
{ "question_id": 17443379, "question_date": "2013-07-03T08:39:19.397Z", "question_score": 218, "tags": "postgresql", "answer_id": 26183931, "answer_date": "2014-10-03T17:39:12.033Z", "answer_score": 357 }
Please answer the following Stack Overflow question: Title: UDP vs TCP, how much faster is it? <p>For general protocol message exchange, which can tolerate some packet loss. How much more efficient is UDP over TCP?</p>
<p>UDP is faster than TCP, and the simple reason is because its non-existent acknowledge packet (ACK) that permits a continuous packet stream, instead of TCP that acknowledges a set of packets, calculated by using the TCP window size and round-trip time (RTT).</p> <p>For more information, I recommend the simple, but very comprehensible <a href="http://www.skullbox.net/tcpudp.php" rel="noreferrer">Skullbox explanation (TCP vs. UDP)</a></p>
{ "question_id": 47903, "question_date": "2008-09-06T22:46:36.373Z", "question_score": 218, "tags": "networking|tcp|udp", "answer_id": 47929, "answer_date": "2008-09-06T23:03:04.773Z", "answer_score": 92 }
Please answer the following Stack Overflow question: Title: Remove All Event Listeners of Specific Type <p>I want to remove all event listeners of a specific type that were added using <code>addEventListener()</code>. All the resources I'm seeing are saying you need to do this:</p> <pre><code>elem.addEventListener('mousedown',specific_function); elem.removeEventListener('mousedown',specific_function); </code></pre> <p>But I want to be able to clear it without knowing what it is currently, like this:</p> <pre><code>elem.addEventListener('mousedown',specific_function); elem.removeEventListener('mousedown'); </code></pre>
<p>That is not possible without intercepting <code>addEventListener</code> calls and keep track of the listeners or use a library that allows such features unfortunately. It would have been if the listeners collection was accessible but the <a href="https://stackoverflow.com/questions/7810534/have-any-browsers-implemented-the-dom3-eventlistenerlist">feature wasn't implemented</a>.</p> <p>The closest thing you can do is to remove all listeners by cloning the element, which will not clone the listeners collection.</p> <p><em>Note: This will also remove listeners on element's children.</em></p> <pre><code>var el = document.getElementById('el-id'), elClone = el.cloneNode(true); el.parentNode.replaceChild(elClone, el); </code></pre>
{ "question_id": 19469881, "question_date": "2013-10-19T19:03:56.203Z", "question_score": 218, "tags": "javascript|events", "answer_id": 19470348, "answer_date": "2013-10-19T19:47:21.717Z", "answer_score": 273 }
Please answer the following Stack Overflow question: Title: How can I quantify difference between two images? <p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
<h2>General idea</h2> <p>Option 1: Load both images as arrays (<code>scipy.misc.imread</code>) and calculate an element-wise (pixel-by-pixel) difference. Calculate the norm of the difference.</p> <p>Option 2: Load both images. Calculate some feature vector for each of them (like a histogram). Calculate distance between feature vectors rather than images.</p> <p>However, there are some decisions to make first.</p> <h2>Questions</h2> <p>You should answer these questions first:</p> <ul> <li><p>Are images of the same shape and dimension?</p> <p>If not, you may need to resize or crop them. PIL library will help to do it in Python.</p> <p>If they are taken with the same settings and the same device, they are probably the same.</p></li> <li><p>Are images well-aligned?</p> <p>If not, you may want to run cross-correlation first, to find the best alignment first. SciPy has functions to do it.</p> <p>If the camera and the scene are still, the images are likely to be well-aligned.</p></li> <li><p>Is exposure of the images always the same? (Is lightness/contrast the same?)</p> <p>If not, you may want <a href="http://en.wikipedia.org/wiki/Normalization_(image_processing)" rel="noreferrer">to normalize</a> images.</p> <p>But be careful, in some situations this may do more wrong than good. For example, a single bright pixel on a dark background will make the normalized image very different.</p></li> <li><p>Is color information important?</p> <p>If you want to notice color changes, you will have a vector of color values per point, rather than a scalar value as in gray-scale image. You need more attention when writing such code.</p></li> <li><p>Are there distinct edges in the image? Are they likely to move?</p> <p>If yes, you can apply edge detection algorithm first (e.g. calculate gradient with Sobel or Prewitt transform, apply some threshold), then compare edges on the first image to edges on the second.</p></li> <li><p>Is there noise in the image?</p> <p>All sensors pollute the image with some amount of noise. Low-cost sensors have more noise. You may wish to apply some noise reduction before you compare images. Blur is the most simple (but not the best) approach here.</p></li> <li><p>What kind of changes do you want to notice?</p> <p>This may affect the choice of norm to use for the difference between images.</p> <p>Consider using Manhattan norm (the sum of the absolute values) or zero norm (the number of elements not equal to zero) to measure how much the image has changed. The former will tell you how much the image is off, the latter will tell only how many pixels differ.</p></li> </ul> <h2>Example</h2> <p>I assume your images are well-aligned, the same size and shape, possibly with different exposure. For simplicity, I convert them to grayscale even if they are color (RGB) images.</p> <p>You will need these imports:</p> <pre><code>import sys from scipy.misc import imread from scipy.linalg import norm from scipy import sum, average </code></pre> <p>Main function, read two images, convert to grayscale, compare and print results:</p> <pre><code>def main(): file1, file2 = sys.argv[1:1+2] # read images as 2D arrays (convert to grayscale for simplicity) img1 = to_grayscale(imread(file1).astype(float)) img2 = to_grayscale(imread(file2).astype(float)) # compare n_m, n_0 = compare_images(img1, img2) print "Manhattan norm:", n_m, "/ per pixel:", n_m/img1.size print "Zero norm:", n_0, "/ per pixel:", n_0*1.0/img1.size </code></pre> <p>How to compare. <code>img1</code> and <code>img2</code> are 2D SciPy arrays here:</p> <pre><code>def compare_images(img1, img2): # normalize to compensate for exposure difference, this may be unnecessary # consider disabling it img1 = normalize(img1) img2 = normalize(img2) # calculate the difference and its norms diff = img1 - img2 # elementwise for scipy arrays m_norm = sum(abs(diff)) # Manhattan norm z_norm = norm(diff.ravel(), 0) # Zero norm return (m_norm, z_norm) </code></pre> <p>If the file is a color image, <code>imread</code> returns a 3D array, average RGB channels (the last array axis) to obtain intensity. No need to do it for grayscale images (e.g. <code>.pgm</code>):</p> <pre><code>def to_grayscale(arr): "If arr is a color image (3D array), convert it to grayscale (2D array)." if len(arr.shape) == 3: return average(arr, -1) # average over the last axis (color channels) else: return arr </code></pre> <p>Normalization is trivial, you may choose to normalize to [0,1] instead of [0,255]. <code>arr</code> is a SciPy array here, so all operations are element-wise:</p> <pre><code>def normalize(arr): rng = arr.max()-arr.min() amin = arr.min() return (arr-amin)*255/rng </code></pre> <p>Run the <code>main</code> function:</p> <pre><code>if __name__ == "__main__": main() </code></pre> <p>Now you can put this all in a script and run against two images. If we compare image to itself, there is no difference:</p> <pre><code>$ python compare.py one.jpg one.jpg Manhattan norm: 0.0 / per pixel: 0.0 Zero norm: 0 / per pixel: 0.0 </code></pre> <p>If we blur the image and compare to the original, there is some difference:</p> <pre><code>$ python compare.py one.jpg one-blurred.jpg Manhattan norm: 92605183.67 / per pixel: 13.4210411116 Zero norm: 6900000 / per pixel: 1.0 </code></pre> <p>P.S. Entire <a href="http://gist.github.com/626356" rel="noreferrer">compare.py</a> script.</p> <h2>Update: relevant techniques</h2> <p>As the question is about a video sequence, where frames are likely to be almost the same, and you look for something unusual, I'd like to mention some alternative approaches which may be relevant:</p> <ul> <li>background subtraction and segmentation (to detect foreground objects)</li> <li>sparse optical flow (to detect motion)</li> <li>comparing histograms or some other statistics instead of images</li> </ul> <p>I strongly recommend taking a look at “Learning OpenCV” book, Chapters 9 (Image parts and segmentation) and 10 (Tracking and motion). The former teaches to use Background subtraction method, the latter gives some info on optical flow methods. All methods are implemented in OpenCV library. If you use Python, I suggest to use OpenCV ≥ 2.3, and its <code>cv2</code> Python module.</p> <p>The most simple version of the background subtraction:</p> <ul> <li>learn the average value μ and standard deviation σ for every pixel of the background</li> <li>compare current pixel values to the range of (μ-2σ,μ+2σ) or (μ-σ,μ+σ)</li> </ul> <p>More advanced versions make take into account time series for every pixel and handle non-static scenes (like moving trees or grass).</p> <p>The idea of optical flow is to take two or more frames, and assign velocity vector to every pixel (dense optical flow) or to some of them (sparse optical flow). To estimate sparse optical flow, you may use <a href="http://en.wikipedia.org/wiki/Lucas%E2%80%93Kanade_method" rel="noreferrer">Lucas-Kanade method</a> (it is also implemented in OpenCV). Obviously, if there is a lot of flow (high average over max values of the velocity field), then something is moving in the frame, and subsequent images are more different.</p> <p>Comparing histograms may help to detect sudden changes between consecutive frames. This approach was used in <a href="http://www.sciencedirect.com/science/article/pii/S0967066110000808" rel="noreferrer">Courbon et al, 2010</a>:</p> <blockquote> <p><em>Similarity of consecutive frames.</em> The distance between two consecutive frames is measured. If it is too high, it means that the second frame is corrupted and thus the image is eliminated. The <a href="https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence" rel="noreferrer">Kullback–Leibler distance</a>, or mutual entropy, on the histograms of the two frames:</p> <p><img src="https://i.imgur.com/hdeh8ni.gif" alt="$$ d(p,q) = \sum_i p(i) \log (p(i)/q(i)) $$"></p> <p>where <em>p</em> and <em>q</em> are the histograms of the frames is used. The threshold is fixed on 0.2.</p> </blockquote>
{ "question_id": 189943, "question_date": "2008-10-10T02:39:33.650Z", "question_score": 218, "tags": "python|image-processing|background-subtraction|image-comparison|timelapse", "answer_id": 3935002, "answer_date": "2010-10-14T15:43:55.083Z", "answer_score": 303 }
Please answer the following Stack Overflow question: Title: HTTP POST Returns Error: 417 "Expectation Failed." <p>When I try to POST to a URL it results in the following exception:</p> <blockquote> <p>The remote server returned an error: (417) Expectation Failed.</p> </blockquote> <p>Here's a sample code:</p> <pre><code>var client = new WebClient(); var postData = new NameValueCollection(); postData.Add("postParamName", "postParamValue"); byte[] responseBytes = client.UploadValues("http://...", postData); string response = Encoding.UTF8.GetString(responseBytes); // (417) Expectation Failed. </code></pre> <p>Using an <code>HttpWebRequest/HttpWebResponse</code> pair or an <code>HttpClient</code> doesn't make a difference.</p> <p>What's causing this exception?</p>
<p>System.Net.HttpWebRequest adds the header 'HTTP header "Expect: 100-Continue"' to every request unless you explicitly ask it not to by setting <a href="http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.expect100continue(VS.80).aspx" rel="noreferrer">this static property</a> to false:</p> <pre><code>System.Net.ServicePointManager.Expect100Continue = false; </code></pre> <p>Some servers choke on that header and send back the 417 error you're seeing. </p> <p>Give that a shot.</p>
{ "question_id": 566437, "question_date": "2009-02-19T17:57:16.027Z", "question_score": 218, "tags": "c#|.net|http|http-post|webclient", "answer_id": 566847, "answer_date": "2009-02-19T19:45:45.263Z", "answer_score": 481 }
Please answer the following Stack Overflow question: Title: Format bytes to kilobytes, megabytes, gigabytes <p>Scenario: the size of various files are stored in a database as bytes. What's the best way to format this size info to kilobytes, megabytes and gigabytes? For instance I have an MP3 that Ubuntu displays as "5.2 MB (5445632 bytes)". How would I display this on a web page as "5.2 MB" AND have files less than one megabyte display as KB and files one gigabyte and above display as GB?</p>
<pre><code>function formatBytes($bytes, $precision = 2) { $units = array('B', 'KB', 'MB', 'GB', 'TB'); $bytes = max($bytes, 0); $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); $pow = min($pow, count($units) - 1); // Uncomment one of the following alternatives // $bytes /= pow(1024, $pow); // $bytes /= (1 &lt;&lt; (10 * $pow)); return round($bytes, $precision) . ' ' . $units[$pow]; } </code></pre> <p>(Taken from <a href="http://php.net/manual/de/function.filesize.php" rel="noreferrer">php.net</a>, there are many other examples there, but I like this one best :-)</p>
{ "question_id": 2510434, "question_date": "2010-03-24T18:34:55.860Z", "question_score": 218, "tags": "php", "answer_id": 2510459, "answer_date": "2010-03-24T18:38:43.103Z", "answer_score": 362 }
Please answer the following Stack Overflow question: Title: How do I convert an interval into a number of hours with postgres? <p>Say I have an interval like</p> <pre><code>4 days 10:00:00 </code></pre> <p>in postgres. How do I convert that to a number of hours (106 in this case?) Is there a function or should I bite the bullet and do something like</p> <pre><code>extract(days, my_interval) * 24 + extract(hours, my_interval) </code></pre>
<p>Probably the easiest way is:</p> <pre><code>SELECT EXTRACT(epoch FROM my_interval)/3600 </code></pre>
{ "question_id": 952493, "question_date": "2009-06-04T19:08:19.560Z", "question_score": 218, "tags": "datetime|postgresql|intervals", "answer_id": 952600, "answer_date": "2009-06-04T19:23:07.970Z", "answer_score": 421 }
Please answer the following Stack Overflow question: Title: Download JSON object as a file from browser <p>I have the following code to let users download data strings in csv file.</p> <pre><code>exportData = 'data:text/csv;charset=utf-8,'; exportData += 'some csv strings'; encodedUri = encodeURI(exportData); newWindow = window.open(encodedUri); </code></pre> <p>It works just fine that if client runs the code it generates blank page and starts downloading the data in csv file.</p> <p>So I tried to do this with JSON object like</p> <pre><code>exportData = 'data:text/json;charset=utf-8,'; exportData += escape(JSON.stringify(jsonObject)); encodedUri = encodeURI(exportData); newWindow = window.open(encodedUri); </code></pre> <p>But I see only a page with the JSON data displayed on it, not downloading it.</p> <p>I went through some research and <a href="https://stackoverflow.com/questions/8080929/how-to-save-a-file-at-client-side-using-javascript">this one</a> claims to work but I don't see any difference to my code.</p> <p>Am I missing something in my code?</p> <p>Thanks for reading my question:)</p>
<p>This is how I solved it for my application:</p> <p>HTML: <code>&lt;a id="downloadAnchorElem" style="display:none"&gt;&lt;/a&gt;</code></p> <p>JS (pure JS, not jQuery here):</p> <pre><code>var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(storageObj)); var dlAnchorElem = document.getElementById('downloadAnchorElem'); dlAnchorElem.setAttribute("href", dataStr ); dlAnchorElem.setAttribute("download", "scene.json"); dlAnchorElem.click(); </code></pre> <p>In this case, <code>storageObj</code> is the js object you want to store, and "scene.json" is just an example name for the resulting file.</p> <p>This approach has the following advantages over other proposed ones:</p> <ul> <li>No HTML element needs to be clicked</li> <li>Result will be named as you want it</li> <li>no jQuery needed</li> </ul> <p>I needed this behavior without explicit clicking since I want to trigger the download automatically at some point from js.</p> <p>JS solution (no HTML required):</p> <pre><code> function downloadObjectAsJson(exportObj, exportName){ var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(exportObj)); var downloadAnchorNode = document.createElement('a'); downloadAnchorNode.setAttribute("href", dataStr); downloadAnchorNode.setAttribute("download", exportName + ".json"); document.body.appendChild(downloadAnchorNode); // required for firefox downloadAnchorNode.click(); downloadAnchorNode.remove(); } </code></pre>
{ "question_id": 19721439, "question_date": "2013-11-01T05:42:15.607Z", "question_score": 218, "tags": "javascript|json", "answer_id": 30800715, "answer_date": "2015-06-12T10:23:11.753Z", "answer_score": 383 }
Please answer the following Stack Overflow question: Title: How to create key or append an element to key? <p>I have an empty dictionary. Name: <code>dict_x</code> It is to have keys of which values are lists.</p> <p>From a separate iteration, I obtain a key (ex: <code>key_123</code>), and an item (a tuple) to place in the list of <code>dict_x</code>'s value <code>key_123</code>.</p> <p>If this key already exists, I want to append this item. If this key does not exist, I want to create it with an empty list and then append to it or just create it with a tuple in it.</p> <p>In future when again this key comes up, since it exists, I want the value to be appended again.</p> <p>My code consists of this:</p> <blockquote> <p>Get key and value.</p> <p>See if <strong>NOT</strong> key exists in <code>dict_x</code>.</p> <p>and if not create it: <code>dict_x[key] == []</code></p> <p>Afterwards: <code>dict_x[key].append(value)</code></p> </blockquote> <p>Is this the way to do it? Shall I try to use <code>try/except</code> blocks?</p>
<p>Use <a href="http://docs.python.org/library/stdtypes.html#dict.setdefault" rel="noreferrer"><code>dict.setdefault()</code></a>:</p> <pre><code>dict.setdefault(key,[]).append(value) </code></pre> <p><strong>help(dict.setdefault)</strong>:</p> <pre><code> setdefault(...) D.setdefault(k[,d]) -&gt; D.get(k,d), also set D[k]=d if k not in D </code></pre>
{ "question_id": 12905999, "question_date": "2012-10-16T00:42:07.373Z", "question_score": 218, "tags": "python|dictionary", "answer_id": 12906014, "answer_date": "2012-10-16T00:43:35.667Z", "answer_score": 363 }