input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: JavaScript plus sign in front of function expression <p>I’ve been looking for information about immediately invoked functions, and somewhere I stumbled on this notation:</p> <pre><code>+function(){console.log("Something.")}() </code></pre> <p>Can someone explain to me what the <code>+</code> sign in front of the function means/does?</p>
<p>It forces the parser to treat the part following the <code>+</code> as an expression. This is usually used for functions that are invoked immediately, e.g.:</p> <pre><code>+function() { console.log("Foo!"); }(); </code></pre> <p>Without the <code>+</code> there, if the parser is in a state where it's expecting a statement (which can be an expression or several non-expression statements), the word <code>function</code> looks like the beginning of a function <em>declaration</em> rather than a function <em>expression</em> and so the <code>()</code> following it (the ones at the end of the line above) would be a syntax error (as would the absense of a name, in that example). <em>With</em> the <code>+</code>, it makes it a function expression, which means the name is optional and which results in a reference to the function, which can be invoked, so the parentheses are valid.</p> <p><code>+</code> is just one of the options. It can also be <code>-</code>, <code>!</code>, <code>~</code>, or just about any other unary operator. Alternately, you can use parentheses (this is more common, but neither more nor less correct syntactically):</p> <pre><code>(function() { console.log("Foo!"); })(); // or (function() { console.log("Foo!"); }()); </code></pre>
{ "question_id": 13341698, "question_date": "2012-11-12T10:06:23.017Z", "question_score": 906, "tags": "javascript|function|operators|iife|self-invoking-function", "answer_id": 13341710, "answer_date": "2012-11-12T10:07:25.483Z", "answer_score": 1352 }
Please answer the following Stack Overflow question: Title: Link to the issue number on GitHub within a commit message <p>Is it somehow possible to <strong>automatically</strong> have a link to GitHub issue number in the <code>git commit</code> message?</p>
<p><strong>Just include <code>#xxx</code> in your commit message to reference an issue without closing it.</strong></p> <p>With new <a href="https://github.blog/2011-04-09-issues-2-0-the-next-generation/" rel="noreferrer">GitHub issues 2.0</a> you can use these synonyms to <a href="https://github.blog/2013-01-22-closing-issues-via-commit-messages/" rel="noreferrer">reference an issue and close</a> it (in your commit message):</p> <ul> <li><code>fix #xxx</code></li> <li><code>fixes #xxx</code></li> <li><code>fixed #xxx</code></li> <li><code>close #xxx</code></li> <li><code>closes #xxx</code></li> <li><code>closed #xxx</code></li> <li><code>resolve #xxx</code></li> <li><code>resolves #xxx</code></li> <li><code>resolved #xxx</code></li> </ul> <p>You can also substitute <code>#xxx</code> with <code>gh-xxx</code>.</p> <p>Referencing and <a href="https://github.blog/2013-03-18-closing-issues-across-repositories/" rel="noreferrer">closing issues across repos</a> also works:</p> <pre><code>fixes user/repo#xxx </code></pre> <p>Check out <a href="https://help.github.com/en/articles/closing-issues-using-keywords" rel="noreferrer">the documentation</a> available in their Help section.</p>
{ "question_id": 1687262, "question_date": "2009-11-06T12:27:52.527Z", "question_score": 904, "tags": "git|github|git-commit", "answer_id": 6742691, "answer_date": "2011-07-19T05:36:09.487Z", "answer_score": 1195 }
Please answer the following Stack Overflow question: Title: python setup.py uninstall <p>I have installed a python package with <code>python setup.py install</code>.</p> <p>How do I uninstall it?</p>
<p>Note: Avoid using <code>python setup.py install</code> use <code>pip install .</code></p> <p>You need to remove all files manually, and also undo any other stuff that installation did manually.</p> <p>If you don't know the list of all files, you can reinstall it with the <code>--record</code> option, and take a look at the list this produces.</p> <p>To record a list of installed files, you can use:</p> <pre><code>python setup.py install --record files.txt </code></pre> <p>Once you want to uninstall you can use xargs to do the removal:</p> <pre><code>xargs rm -rf &lt; files.txt </code></pre> <p>Or if you're running Windows, use Powershell: </p> <pre><code>Get-Content files.txt | ForEach-Object {Remove-Item $_ -Recurse -Force} </code></pre> <p>Then delete also the containing directory, e.g. <code>/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/my_module-0.1.egg/</code> on <code>macOS</code>. It has no files, but Python will still import an empty module:</p> <pre><code>&gt;&gt;&gt; import my_module &gt;&gt;&gt; my_module.__file__ None </code></pre> <p>Once deleted, Python shows:</p> <pre><code>&gt;&gt;&gt; import my_module Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'my_module' </code></pre>
{ "question_id": 1550226, "question_date": "2009-10-11T09:06:56.323Z", "question_score": 904, "tags": "python|setup.py|pypi", "answer_id": 1550235, "answer_date": "2009-10-11T09:12:27.953Z", "answer_score": 1118 }
Please answer the following Stack Overflow question: Title: How do I add an existing directory tree to a project in Visual Studio? <p>The issue is simple really. Instead of creating folders in Visual Studio, I create a directory structure for my project on the file system. How do I include all the folders and files in a project, keeping the structure?</p> <p>If I "Add Existing File" on a folder named Services and navigate to a file in the directory structure .. Services > AccountManagement > CreateAccount.cs, it appears in Visual Studio like so: Services > CreateAccount.cs. I do not want this.</p> <p>I have an entire directory structure worked out already, as I am mimicking our client developers using the same structure for organization. How do I add all the folders and files to the project in Visual Studio? Or do I have to do what most Microsoft users do and "put up with it" and recreate each and every folder through Visual Studio?</p>
<p>You need to put your directory structure in your project directory. And then click "Show All Files" icon in the top of Solution Explorer toolbox. After that, the added directory will be shown up. You will then need to select this directory, right click, and choose "Include in Project."</p> <p><a href="https://i.stack.imgur.com/ub2DI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ub2DI.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/oIDP1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/oIDP1.png" alt="enter image description here"></a></p>
{ "question_id": 392473, "question_date": "2008-12-25T03:17:13.993Z", "question_score": 904, "tags": "visual-studio", "answer_id": 392477, "answer_date": "2008-12-25T03:25:40.997Z", "answer_score": 1553 }
Please answer the following Stack Overflow question: Title: What part of Hindley-Milner do you not understand? <p>I <em>swear</em> there used to be a <strong>T-shirt</strong> for sale featuring the immortal words:</p> <hr> <p>What part of</p> <p><img src="https://i.stack.imgur.com/xkKgE.png" alt="Hindley-Milner"></p> <p>do you <em>not</em> understand?</p> <hr> <p>In my case, the answer would be... all of it!</p> <p>In particular, I often see notation like this in Haskell papers, but I have no clue what any of it means. I have no idea what branch of mathematics it's supposed to be.</p> <p>I recognize the letters of the Greek alphabet of course and symbols such as "∉" (which usually means that something is not an element of a set).</p> <p>On the other hand, I've never seen "⊢" before (<a href="https://en.wikipedia.org/wiki/List_of_mathematical_symbols" rel="noreferrer">Wikipedia claims it might mean "partition"</a>). I'm also unfamiliar with the use of the vinculum here. (Usually, it denotes a fraction, but that does not <em>appear</em> to be the case here.)</p> <p>If somebody could at least tell me where to start looking to comprehend what this sea of symbols means, that would be helpful.</p>
<ul> <li>The <em>horizontal bar</em> means that "[above] <strong>implies</strong> [below]".</li> <li>If there are <em>multiple expressions</em> in [above], then consider them <strong>anded</strong> together; all of the [above] must be true in order to guarantee the [below].</li> <li><code>:</code> means <strong>has type</strong></li> <li><code>∈</code> means <strong>is in</strong>. (Likewise <code>∉</code> means "is not in".)</li> <li><code>Γ</code> is usually used to refer to an <strong>environment</strong> or context; in this case it can be thought of as a set of type annotations, pairing an identifier with its type. Therefore <code>x : σ ∈ Γ</code> means that the environment <code>Γ</code> includes the fact that <code>x</code> has type <code>σ</code>.</li> <li><code>⊢</code> can be read as <strong>proves</strong> or determines. <code>Γ ⊢ x : σ</code> means that the environment <code>Γ</code> determines that <code>x</code> has type <code>σ</code>.</li> <li><code>,</code> is a way of <strong>including</strong> specific additional assumptions into an environment <code>Γ</code>.<br> Therefore, <code>Γ, x : τ ⊢ e : τ'</code> means that environment <code>Γ</code>, <em>with the additional, overriding assumption that <code>x</code> has type <code>τ</code></em>, proves that <code>e</code> has type <code>τ'</code>.</li> </ul> <hr> <p>As requested: operator precedence, from highest to lowest:</p> <ul> <li>Language-specific infix and mixfix operators, such as <code>λ x . e</code>, <code>∀ α . σ</code>, and <code>τ → τ'</code>, <code>let x = e0 in e1</code>, and whitespace for function application.</li> <li><code>:</code></li> <li><code>∈</code> and <code>∉</code></li> <li><code>,</code> (left-associative)</li> <li><code>⊢</code></li> <li>whitespace separating multiple propositions (associative)</li> <li>the horizontal bar</li> </ul>
{ "question_id": 12532552, "question_date": "2012-09-21T14:29:44.620Z", "question_score": 904, "tags": "haskell|functional-programming|lambda-calculus|hindley-milner|denotational-semantics", "answer_id": 12535304, "answer_date": "2012-09-21T17:28:50.993Z", "answer_score": 697 }
Please answer the following Stack Overflow question: Title: How do I update the password for Git? <p>I'm using BitBucket with Xcode and Git for version control, and recently I changed all of my passwords (<em>thanks Adobe!</em>).</p> <p>Unsurprisingly, I'm no longer able to push my local commits to my repository on BitBucket (<code>Authentication failed for 'https://______.git'</code>), but I'm forgetting how to update the cached password on my iMac. Somehow I've been unable to find it on Google or Stack&nbsp;Overflow, though it seems to me it should be rather straightforward...</p>
<p>To fix this on macOS, you can use </p> <pre><code>git config --global credential.helper osxkeychain </code></pre> <p>A username and password prompt will appear with your next Git action (pull, clone, push, etc.).</p> <p>For Windows, it's the same command with a different argument:</p> <pre><code>git config --global credential.helper wincred </code></pre>
{ "question_id": 20195304, "question_date": "2013-11-25T14:15:14.190Z", "question_score": 903, "tags": "macos|git|change-password", "answer_id": 20195558, "answer_date": "2013-11-25T14:27:41.450Z", "answer_score": 1289 }
Please answer the following Stack Overflow question: Title: TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes <p>Per <a href="http://dev.mysql.com/doc/refman/5.7/en/blob.html" rel="noreferrer">the MySQL docs</a>, there are four TEXT types:</p> <ol> <li>TINYTEXT</li> <li>TEXT</li> <li>MEDIUMTEXT</li> <li>LONGTEXT</li> </ol> <p>What is the maximum length that I can store in a column of each data type assuming the character encoding is UTF-8?</p>
<p>From the <a href="https://dev.mysql.com/doc/refman/8.0/en/storage-requirements.html#data-types-storage-reqs-strings" rel="noreferrer">documentation (MySQL 8)</a> :</p> <pre> Type | Maximum length -----------+------------------------------------- TINYTEXT | 255 (2<sup> 8</sup>&minus;1) bytes TEXT | 65,535 (2<sup>16</sup>&minus;1) bytes = 64 KiB MEDIUMTEXT | 16,777,215 (2<sup>24</sup>&minus;1) bytes = 16 MiB LONGTEXT | 4,294,967,295 (2<sup>32</sup>&minus;1) bytes = 4 GiB </pre> <p>Note that the number of <em>characters</em> that can be stored in your column will depend on the <em>character encoding</em>.</p>
{ "question_id": 13932750, "question_date": "2012-12-18T12:13:35.297Z", "question_score": 903, "tags": "mysql|innodb", "answer_id": 13932834, "answer_date": "2012-12-18T12:18:06.890Z", "answer_score": 1686 }
Please answer the following Stack Overflow question: Title: Why does Python code run faster in a function? <pre><code>def main(): for i in xrange(10**8): pass main() </code></pre> <p>This piece of code in Python runs in (Note: The timing is done with the time function in BASH in Linux.)</p> <pre><code>real 0m1.841s user 0m1.828s sys 0m0.012s </code></pre> <p>However, if the for loop isn't placed within a function, </p> <pre><code>for i in xrange(10**8): pass </code></pre> <p>then it runs for a much longer time:</p> <pre><code>real 0m4.543s user 0m4.524s sys 0m0.012s </code></pre> <p>Why is this?</p>
<p>You might ask <em>why</em> it is faster to store local variables than globals. This is a CPython implementation detail.</p> <p>Remember that CPython is compiled to bytecode, which the interpreter runs. When a function is compiled, the local variables are stored in a fixed-size array (<em>not</em> a <code>dict</code>) and variable names are assigned to indexes. This is possible because you can't dynamically add local variables to a function. Then retrieving a local variable is literally a pointer lookup into the list and a refcount increase on the <code>PyObject</code> which is trivial.</p> <p>Contrast this to a global lookup (<code>LOAD_GLOBAL</code>), which is a true <code>dict</code> search involving a hash and so on. Incidentally, this is why you need to specify <code>global i</code> if you want it to be global: if you ever assign to a variable inside a scope, the compiler will issue <code>STORE_FAST</code>s for its access unless you tell it not to.</p> <p>By the way, global lookups are still pretty optimised. Attribute lookups <code>foo.bar</code> are the <em>really</em> slow ones!</p> <p>Here is small <a href="https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Local_Variables" rel="noreferrer">illustration</a> on local variable efficiency.</p>
{ "question_id": 11241523, "question_date": "2012-06-28T09:18:34.850Z", "question_score": 903, "tags": "python|performance|profiling|benchmarking|cpython", "answer_id": 11242447, "answer_date": "2012-06-28T10:15:08.067Z", "answer_score": 579 }
Please answer the following Stack Overflow question: Title: How does "cat << EOF" work in bash? <p>I needed to write a script to enter multi-line input to a program (<code>psql</code>).</p> <p>After a bit of googling, I found the following syntax works:</p> <pre><code>cat &lt;&lt; EOF | psql ---params BEGIN; `pg_dump ----something` update table .... statement ...; END; EOF </code></pre> <p>This correctly constructs the multi-line string (from <code>BEGIN;</code> to <code>END;</code>, inclusive) and pipes it as an input to <code>psql</code>.</p> <p>But I have no idea how/why it works, can some one please explain?</p> <p>I'm referring mainly to <code>cat &lt;&lt; EOF</code>, I know <code>&gt;</code> outputs to a file, <code>&gt;&gt;</code> appends to a file, <code>&lt;</code> reads input from file. </p> <p>What does <code>&lt;&lt;</code> exactly do?</p> <p>And is there a man page for it?</p>
<p>This is called <strong><em>heredoc</strong> format</em> to provide a string into stdin. See <a href="https://en.wikipedia.org/wiki/Here_document#Unix_shells" rel="noreferrer">https://en.wikipedia.org/wiki/Here_document#Unix_shells</a> for more details.</p> <hr> <p>From <code>man bash</code>:</p> <blockquote> <h2>Here Documents</h2> <p>This type of redirection instructs the shell to read input from the current source until a line containing only word (with no trailing blanks) is seen.</p> <p>All of the lines read up to that point are then used as the standard input for a command.</p> <p>The format of here-documents is:</p> <pre><code> &lt;&lt;[-]word here-document delimiter </code></pre> <p>No parameter expansion, command substitution, arithmetic expansion, or pathname expansion is performed on <strong>word</strong>. If any characters in <strong>word</strong> are quoted, the <strong>delimiter</strong> is the result of quote removal on <strong>word</strong>, and the lines in the <strong>here-document</strong> are not expanded. If <strong>word</strong> is unquoted, all lines of the <strong>here-document</strong> are subjected to parameter expansion, command substitution, and arithmetic expansion. In the latter case, the character sequence <code>\&lt;newline&gt;</code> is ignored, and <code>\</code> must be used to quote the characters <code>\</code>, <code>$</code>, and <code>`</code>.</p> <p>If the redirection operator is <code>&lt;&lt;-</code>, then all leading tab characters are stripped from input lines and the line containing <strong>delimiter</strong>. This allows here-documents within shell scripts to be indented in a natural fashion.</p> </blockquote>
{ "question_id": 2500436, "question_date": "2010-03-23T13:57:35.677Z", "question_score": 902, "tags": "linux|bash|scripting|heredoc", "answer_id": 2500451, "answer_date": "2010-03-23T13:58:41.800Z", "answer_score": 663 }
Please answer the following Stack Overflow question: Title: Remove empty strings from a list of strings <p>I want to remove all empty strings from a list of strings in python.</p> <p>My idea looks like this:</p> <pre><code>while '' in str_list: str_list.remove('') </code></pre> <p>Is there any more pythonic way to do this?</p>
<p>I would use <a href="http://docs.python.org/library/functions.html#filter" rel="noreferrer"><code>filter</code></a>:</p> <pre><code>str_list = filter(None, str_list) str_list = filter(bool, str_list) str_list = filter(len, str_list) str_list = filter(lambda item: item, str_list) </code></pre> <p>Python 3 returns an iterator from <code>filter</code>, so should be wrapped in a call to <code>list()</code></p> <pre><code>str_list = list(filter(None, str_list)) </code></pre>
{ "question_id": 3845423, "question_date": "2010-10-02T11:21:10.247Z", "question_score": 902, "tags": "python|string|list", "answer_id": 3845453, "answer_date": "2010-10-02T11:28:50.580Z", "answer_score": 1456 }
Please answer the following Stack Overflow question: Title: How can I exclude all "permission denied" messages from "find"? <p>I need to hide all <em>permission denied</em> messages from:</p> <pre><code>find . &gt; files_and_folders </code></pre> <p>I am experimenting when such message arises. I need to gather all folders and files, to which it does not arise. </p> <p>Is it possible to direct the permission levels to the <code>files_and_folders</code> file? </p> <p>How can I hide the errors at the same time?</p>
<p>Note:</p> <ul> <li>This answer probably goes deeper than the use case warrants, and <strong><code>find 2&gt;/dev/null</code> may be good enough in many situations</strong>. It may still be of interest for a cross-platform perspective and for its discussion of some advanced shell techniques in the interest of finding a solution that is as robust as possible, even though the cases guarded against may be largely hypothetical.</li> </ul> <hr /> <p>If your <strong>shell is <code>bash</code> or <code>zsh</code></strong>, there's <strong>a solution that is robust while being reasonably simple</strong>, using <strong>only POSIX-compliant <code>find</code> features</strong>; while <code>bash</code> itself is not part of POSIX, most modern Unix platforms come with it, making this solution widely portable:</p> <pre><code>find . &gt; files_and_folders 2&gt; &gt;(grep -v 'Permission denied' &gt;&amp;2) </code></pre> <p>Note:</p> <ul> <li><p><strong>If your system is configured to show <em>localized</em> error messages, prefix the <code>find</code> calls below with <code>LC_ALL=C </code></strong> (<code>LC_ALL=C find ...</code>) to ensure that <em>English</em> messages are reported, so that <code>grep -v 'Permission denied'</code> works as intended. Invariably, however, any error messages that <em>do</em> get displayed will then be in English as well.</p> </li> <li><p><code>&gt;(...)</code> is a (rarely used) <em>output</em> <a href="http://mywiki.wooledge.org/ProcessSubstitution" rel="noreferrer">process substitution</a> that allows redirecting output (in this case, <em>stderr</em> output (<code>2&gt;</code>) to the stdin of the command inside <code>&gt;(...)</code>.<br /> In addition to <code>bash</code> and <code>zsh</code>, <code>ksh</code> supports them as well <em>in principle</em>, but trying to combine them with redirection from <em>stderr</em>, as is done here (<code>2&gt; &gt;(...)</code>), appears to be silently ignored (in <code>ksh 93u+</code>).</p> <ul> <li><p><code>grep -v 'Permission denied'</code> filters <em>out</em> (<code>-v</code>) all lines (from the <code>find</code> command's stderr stream) that contain the phrase <code>Permission denied</code> and outputs the remaining lines to stderr (<code>&gt;&amp;2</code>).</p> </li> <li><p>Note: There's a small chance that some of <code>grep</code>'s output may arrive <em>after</em> <code>find</code> completes, because the overall command doesn't wait for the command inside <code>&gt;(...)</code> to finish. In <code>bash</code>, you can prevent this by appending <code>| cat</code> to the command.</p> </li> </ul> </li> </ul> <p>This approach is:</p> <ul> <li><p><strong>robust</strong>: <code>grep</code> is only applied to <em>error messages</em> (and not to a combination of file paths and error messages, potentially leading to false positives), and error messages other than permission-denied ones are passed through, to stderr.</p> </li> <li><p><strong>side-effect free</strong>: <code>find</code>'s exit code is preserved: the inability to access at least one of the filesystem items encountered results in exit code <code>1</code> (although that won't tell you whether errors <em>other</em> than permission-denied ones occurred (too)).</p> </li> </ul> <hr /> <h3>POSIX-compliant solutions:</h3> <p>Fully POSIX-compliant solutions either have limitations or require additional work.</p> <p><strong>If <code>find</code>'s output is to be captured in a <em>file</em> anyway</strong> (or suppressed altogether), then the pipeline-based solution from <a href="https://stackoverflow.com/a/762360/45375">Jonathan Leffler's answer</a> is simple, robust, and POSIX-compliant:</p> <pre><code>find . 2&gt;&amp;1 &gt;files_and_folders | grep -v 'Permission denied' &gt;&amp;2 </code></pre> <p>Note that the order of the redirections matters: <code>2&gt;&amp;1</code> must come <em>first</em>.</p> <p>Capturing stdout output in a file up front allows <code>2&gt;&amp;1</code> to send <em>only</em> error messages through the pipeline, which <code>grep</code> can then unambiguously operate on.</p> <p>The <strong>only downside is that the <em>overall exit code</em> will be the <code>grep</code> command's</strong>, not <code>find</code>'s, which in this case means: if there are <em>no</em> errors at all or <em>only</em> permission-denied errors, the exit code will be <code>1</code> (signaling <em>failure</em>), otherwise (errors other than permission-denied ones) <code>0</code> - which is the opposite of the intent.<br /> <strong>That said, <code>find</code>'s exit code is rarely used anyway</strong>, as it often conveys little information beyond <em>fundamental</em> failure such as passing a non-existent path.<br /> However, the specific case of even only <em>some</em> of the input paths being inaccessible due to lack of permissions <em>is</em> reflected in <code>find</code>'s exit code (in both GNU and BSD <code>find</code>): if a permissions-denied error occurs for <em>any</em> of the files processed, the exit code is set to <code>1</code>.</p> <p>The following variation addresses that:</p> <pre><code>find . 2&gt;&amp;1 &gt;files_and_folders | { grep -v 'Permission denied' &gt;&amp;2; [ $? -eq 1 ]; } </code></pre> <p>Now, the exit code indicates whether any errors <em>other than</em> <code>Permission denied</code> occurred: <code>1</code> if so, <code>0</code> otherwise.<br /> In other words: the exit code now reflects the true intent of the command: success (<code>0</code>) is reported, if no errors at all or <em>only</em> permission-denied errors occurred.<br /> This is arguably even better than just passing <code>find</code>'s exit code through, as in the solution at the top.</p> <hr /> <p><a href="https://stackoverflow.com/users/1815797/gniourf-gniourf">gniourf_gniourf</a> in the comments proposes a (still POSIX-compliant) <strong>generalization of this solution using sophisticated redirections</strong>, which <strong>works even with the default behavior of printing the file paths to <em>stdout</em></strong>:</p> <pre><code>{ find . 3&gt;&amp;2 2&gt;&amp;1 1&gt;&amp;3 | grep -v 'Permission denied' &gt;&amp;3; } 3&gt;&amp;2 2&gt;&amp;1 </code></pre> <p>In short: Custom file descriptor <code>3</code> is used to temporarily swap stdout (<code>1</code>) and stderr (<code>2</code>), so that error messages <em>alone</em> can be piped to <code>grep</code> via stdout.</p> <p>Without these redirections, both data (file paths) <em>and</em> error messages would be piped to <code>grep</code> via stdout, and <code>grep</code> would then not be able to distinguish between <em>error message</em> <code>Permission denied</code> and a (hypothetical) <em>file whose name happens to contain</em> the phrase <code>Permission denied</code>.</p> <p>As in the first solution, however, the the exit code reported will be <code>grep</code>'s, not <code>find</code>'s, but the same fix as above can be applied.</p> <hr /> <h3>Notes on the existing answers:</h3> <ul> <li><p>There are several points to note about <a href="https://stackoverflow.com/a/25234419/45375">Michael Brux's answer</a>, <code>find . ! -readable -prune -o -print</code>:</p> <ul> <li><p>It requires <em>GNU</em> <code>find</code>; notably, it won't work on macOS. Of course, if you only ever need the command to work with GNU <code>find</code>, this won't be a problem for you.</p> </li> <li><p>Some <code>Permission denied</code> errors may <em>still</em> surface: <code>find ! -readable -prune</code> reports such errors for the <em>child</em> items of directories for which the current user does have <code>r</code> permission, but lacks <code>x</code> (executable) permission. The reason is that because the directory itself <em>is</em> readable, <code>-prune</code> is not executed, and the attempt to descend <em>into</em> that directory then triggers the error messages. That said, the <em>typical</em> case is for the <code>r</code> permission to be missing.</p> </li> <li><p>Note: The following point is a matter of philosophy and/or specific use case, and you may decide it is not relevant to you and that the command fits your needs well, especially if simply <em>printing</em> the paths is all you do:</p> <ul> <li><em>If</em> you conceptualize the filtering of the permission-denied error messages a <em>separate</em> task that you want to be able to apply to <em>any</em> <code>find</code> command, then the opposite approach of proactively <em>preventing</em> permission-denied errors requires introducing &quot;noise&quot; into the <code>find</code> command, which also introduces complexity and logical <em>pitfalls</em>.</li> <li>For instance, the most up-voted comment on Michael's answer (as of this writing) attempts to show how to <em>extend</em> the command by including a <code>-name</code> filter, as follows:<br /> <code>find . ! -readable -prune -o -name '*.txt'</code><br /> This, however, does <em>not</em> work as intended, because the trailing <code>-print</code> action is <em>required</em> (an explanation can be found in <a href="https://stackoverflow.com/questions/1489277/how-to-use-prune-option-of-find-in-sh">this answer</a>). Such subtleties can introduce bugs.</li> </ul> </li> </ul> </li> <li><p>The first solution in <a href="https://stackoverflow.com/a/762360/45375">Jonathan Leffler's answer</a>, <code>find . 2&gt;/dev/null &gt; files_and_folders</code>, as he himself states, <strong>blindly silences <em>all</em> error messages</strong> (and the workaround is cumbersome and not fully robust, as he also explains). <strong>Pragmatically speaking</strong>, however, it is the <strong>simplest solution</strong>, as you may be content to assume that any and all errors would be permission-related.</p> </li> <li><p><a href="https://stackoverflow.com/a/27503763/45375">mist's answer</a>, <code>sudo find . &gt; files_and_folders</code>, <strong>is concise and pragmatic, but ill-advised for anything other than merely <em>printing</em> filenames</strong>, for security reasons: because you're running as the <em>root</em> user, &quot;you risk having your whole system being messed up by a bug in find or a malicious version, or an incorrect invocation which writes something unexpectedly, which could not happen if you ran this with normal privileges&quot; (from a comment on mist's answer by <a href="https://stackoverflow.com/users/874188/tripleee">tripleee</a>).</p> </li> <li><p>The 2nd solution in <a href="https://stackoverflow.com/a/762377/45375">viraptor's answer</a>, <code>find . 2&gt;&amp;1 | grep -v 'Permission denied' &gt; some_file</code> runs the risk of false positives (due to sending a mix of stdout and stderr through the pipeline), and, potentially, instead of reporting <em>non</em>-permission-denied errors via stderr, captures them alongside the output paths in the output file.</p> </li> </ul>
{ "question_id": 762348, "question_date": "2009-04-17T21:54:07.073Z", "question_score": 902, "tags": "bash|error-handling|find|file-permissions", "answer_id": 40336333, "answer_date": "2016-10-31T03:51:28.573Z", "answer_score": 316 }
Please answer the following Stack Overflow question: Title: xcode-select active developer directory error <p>Saw the following error when running an <code>npm install</code> which required <code>node-gyp</code>... but could be triggered by anything which requires <code>xcode-select</code>.</p> <blockquote> <p>xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance</p> </blockquote> <p>What is the problem?</p>
<p>This problem happens when <code>xcode-select</code> developer directory was pointing to <code>/Library/Developer/CommandLineTools</code> when a full regular Xcode was required (happens when CommandLineTools are installed after Xcode)</p> <p>Solution:</p> <ol> <li>Install Xcode (get it from <a href="https://appstore.com/mac/apple/xcode" rel="noreferrer">https://appstore.com/mac/apple/xcode</a>) if you don't have it yet.</li> <li>Accept the Terms and Conditions.</li> <li>Ensure Xcode app is in the <code>/Applications</code> directory (NOT <code>/Users/{user}/Applications</code>).</li> <li>Point <code>xcode-select</code> to the Xcode app Developer directory using the following command:<br /> <code>sudo xcode-select -s /Applications/Xcode.app/Contents/Developer</code></li> </ol> <p><strong>Note</strong>: Make sure your Xcode app path is correct.</p> <ul> <li>Xcode: <code>/Applications/Xcode.app/Contents/Developer</code></li> <li>Xcode-beta: <code>/Applications/Xcode-beta.app/Contents/Developer</code></li> </ul>
{ "question_id": 17980759, "question_date": "2013-07-31T20:52:07.517Z", "question_score": 902, "tags": "xcode|macos|npm|npm-install|command-line-tool", "answer_id": 17980786, "answer_date": "2013-07-31T20:54:17.683Z", "answer_score": 1736 }
Please answer the following Stack Overflow question: Title: How can I use "*ngIf else"? <p>I'm using Angular and I want to use <code>*ngIf else</code> (available since version 4) in this example:</p> <pre><code>&lt;div *ngIf=&quot;isValid&quot;&gt; content here ... &lt;/div&gt; &lt;div *ngIf=&quot;!isValid&quot;&gt; other content here... &lt;/div&gt; </code></pre> <p>How can I achieve the same behavior with <code>ngIf else</code>?</p>
<p><strong>Angular 4 and 5</strong>:</p> <p>Using <code>else</code>:</p> <pre class="lang-ts prettyprint-override"><code>&lt;div *ngIf=&quot;isValid;else other_content&quot;&gt; content here ... &lt;/div&gt; &lt;ng-template #other_content&gt;other content here...&lt;/ng-template&gt; </code></pre> <p>You can also use <code>then else</code>:</p> <pre class="lang-ts prettyprint-override"><code>&lt;div *ngIf=&quot;isValid;then content else other_content&quot;&gt;here is ignored&lt;/div&gt; &lt;ng-template #content&gt;content here...&lt;/ng-template&gt; &lt;ng-template #other_content&gt;other content here...&lt;/ng-template&gt; </code></pre> <p>Or <code>then</code> alone:</p> <pre class="lang-ts prettyprint-override"><code>&lt;div *ngIf=&quot;isValid;then content&quot;&gt;&lt;/div&gt; &lt;ng-template #content&gt;content here...&lt;/ng-template&gt; </code></pre> <p><strong>Demo:</strong></p> <p><a href="https://plnkr.co/edit/XD5vLvmwTApcaHJ66Is1" rel="noreferrer"><strong>Plunker</strong></a></p> <p><strong>Details:</strong></p> <p><code>&lt;ng-template&gt;</code>: is Angular’s own implementation of the <code>&lt;template&gt;</code> tag which is <a href="https://developer.mozilla.org/en/docs/Web/HTML/Element/template" rel="noreferrer">according to MDN</a>:</p> <blockquote> <p>The HTML <code>&lt;template&gt;</code> element is a mechanism for holding client-side content that is not to be rendered when a page is loaded but may subsequently be instantiated during runtime using JavaScript.</p> </blockquote>
{ "question_id": 43006550, "question_date": "2017-03-24T18:18:26.513Z", "question_score": 901, "tags": "angular|if-statement|angular-template", "answer_id": 43006589, "answer_date": "2017-03-24T18:20:52.810Z", "answer_score": 1345 }
Please answer the following Stack Overflow question: Title: How to Right-align flex item? <p>Is there a more flexbox-ish way to right-align &quot;Contact&quot; than to use <code>position: absolute</code>?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.main { display: flex; } .a, .b, .c { background: #efefef; border: 1px solid #999; } .b { flex: 1; text-align: center; } .c { position: absolute; right: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h2&gt;With title&lt;/h2&gt; &lt;div class="main"&gt; &lt;div class="a"&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/div&gt; &lt;div class="b"&gt;&lt;a href="#"&gt;Some title centered&lt;/a&gt;&lt;/div&gt; &lt;div class="c"&gt;&lt;a href="#"&gt;Contact&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;h2&gt;Without title&lt;/h2&gt; &lt;div class="main"&gt; &lt;div class="a"&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/div&gt; &lt;!--&lt;div class="b"&gt;&lt;a href="#"&gt;Some title centered&lt;/a&gt;&lt;/div&gt;--&gt; &lt;div class="c"&gt;&lt;a href="#"&gt;Contact&lt;/a&gt;&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="http://jsfiddle.net/vqDK9/" rel="noreferrer">http://jsfiddle.net/vqDK9/</a></p>
<p>A more flex approach would be to use an <code>auto</code> left margin (flex items treat <a href="http://www.w3.org/TR/css3-flexbox/#auto-margins" rel="noreferrer">auto margins</a> a bit differently than when used in a block formatting context).</p> <pre><code>.c { margin-left: auto; } </code></pre> <p><strong>Updated fiddle:</strong></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.main { display: flex; } .a, .b, .c { background: #efefef; border: 1px solid #999; } .b { flex: 1; text-align: center; } .c {margin-left: auto;}</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;h2&gt;With title&lt;/h2&gt; &lt;div class="main"&gt; &lt;div class="a"&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/div&gt; &lt;div class="b"&gt;&lt;a href="#"&gt;Some title centered&lt;/a&gt;&lt;/div&gt; &lt;div class="c"&gt;&lt;a href="#"&gt;Contact&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;h2&gt;Without title&lt;/h2&gt; &lt;div class="main"&gt; &lt;div class="a"&gt;&lt;a href="#"&gt;Home&lt;/a&gt;&lt;/div&gt; &lt;!--&lt;div class="b"&gt;&lt;a href="#"&gt;Some title centered&lt;/a&gt;&lt;/div&gt;--&gt; &lt;div class="c"&gt;&lt;a href="#"&gt;Contact&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;h1&gt;Problem&lt;/h1&gt; &lt;p&gt;Is there a more flexbox-ish way to right align "Contact" than to use position absolute?&lt;/p&gt;</code></pre> </div> </div> </p>
{ "question_id": 22429003, "question_date": "2014-03-15T19:56:31.827Z", "question_score": 901, "tags": "html|css|flexbox", "answer_id": 22429853, "answer_date": "2014-03-15T21:17:05.690Z", "answer_score": 1396 }
Please answer the following Stack Overflow question: Title: Xcode error "Could not find Developer Disk Image" <p>When attempting to run a build on a connected iOS device in Xcode I get the error:</p> <blockquote> <p>Could not find Developer Disk Image</p> </blockquote> <p><a href="https://i.stack.imgur.com/AWRcs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/AWRcs.png" alt="Screenshot of error message"></a></p> <p>I saw that there was a public beta for Xcode, so I installed it.</p> <p>One of the new features is that you don't need to have a Developer Program Account Dingus to upload your app directly to your iPhone.</p> <p>However, on my iPhone 4s, I also did a public beta update to iOS 8.4, problem being, that there's no Developer Disk Image available for it.</p> <p>Where do I to find it or how can it be fixed?</p>
<p>I am facing the same issue on <strong>Xcode 7.3 or Older version</strong> of your Xcode and my device version is iOS 10 or newer version of your OS.</p> <p>This error is shown when your Xcode is old and the related device you are using is updated to latest version.</p> <p>We can solve this issue by following the below steps:</p> <blockquote> <p>Method 1:-</p> </blockquote> <ul> <li><blockquote> <p>Right click on <strong>Xcode 7.3 or version of your Xcode</strong>, now select "<strong>Show Package Contents</strong>", "<strong>Contents</strong>", "<strong>Developer</strong>", "<strong>Platforms</strong>","<strong>iPhoneOS.Platform</strong>", "<strong>Device Support</strong>".</p> </blockquote></li> <li><blockquote> <p>Now check there is latest version of developer disk image(folder) like 12.1 or newest version(folder) in your case. Copy the latest version and Paste in the same Folder Device Support.</p> </blockquote></li> </ul> <h2><a href="https://i.stack.imgur.com/7hCur.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7hCur.png" alt="enter image description here"></a></h2> <ul> <li><blockquote> <p>In my case I have 12.1 is the latest folder. Now it will generate the copy of that version like 12.1 copy or newest version(folder)copy in your case.</p> </blockquote></li> <li><blockquote> <p>Now Change the name of copy folder to your latest version of iPhone like. In mine case, I have 12.1(Folder)copy and rename it into 12.4. As you can see in the above screenshot. You can change it according to your latest version of phone. I need it for 12.4 so i just rename the folder to 12.4.</p> </blockquote></li> <li><p>Now your Xcode has a new developer disk image. Close the finder now, and quit your Xcode. Open your Xcode and the error will be gone. Now you can connect your latest device to old Xcode versions.</p> <pre><code> **OR** </code></pre></li> </ul> <blockquote> <p>Method 2:-</p> </blockquote> <p>First of all, download the latest Xcode Version. No Need to install the latest Xcode.</p> <p>We can solve this issue by following the below steps:</p> <blockquote> <ul> <li>Right click on <strong>Xcode 8</strong> or Newer version of your <strong>Xcode</strong>, select "<strong>Show Package Contents</strong>", "<strong>Contents</strong>", "<strong>Developer</strong>", "<strong>Platforms</strong>", "<strong>iPhoneOS.Platform</strong>", "<strong>Device Support</strong>"</li> <li>Copy the 10.0 folder (or above for later version).</li> <li>Back in <strong>Finder</strong> select <strong>Applications</strong> again</li> <li>Right click on <strong>Xcode 7.3 or version of your Xcode</strong>, now select "Show Package Contents", "Contents", "Developer", "Platforms", "iPhoneOS.Platform", "Device Support"</li> <li>Paste the 10.0 folder (or above for later version).</li> </ul> </blockquote> <p>Now your Xcode has a new developer disk image. Close the finder now, and quit your Xcode. Open your Xcode and the error will be gone. Now you can connect your latest device to old Xcode versions.</p> <p>OR </p> <blockquote> <p>If you can't download the latest Xcode, you can get the latest Developer Disk Image for your Xcode from this link:-</p> <p><a href="https://github.com/Yatko/iOS-device-support-files" rel="noreferrer">https://github.com/Yatko/iOS-device-support-files</a></p> <p>Thanks to <strong>Yatko</strong>. So that people can download the latest DMGs.</p> </blockquote>
{ "question_id": 30736932, "question_date": "2015-06-09T15:48:57.277Z", "question_score": 901, "tags": "ios|iphone|xcode", "answer_id": 39784892, "answer_date": "2016-09-30T06:17:37.277Z", "answer_score": 120 }
Please answer the following Stack Overflow question: Title: How do I expand the output display to see more columns of a Pandas DataFrame? <p>Is there a way to widen the display of output in either interactive or script-execution mode?</p> <p>Specifically, I am using the <code>describe()</code> function on a Pandas <code>DataFrame</code>. When the <code>DataFrame</code> is five columns (labels) wide, I get the descriptive statistics that I want. However, if the <code>DataFrame</code> has any more columns, the statistics are suppressed and something like this is returned:</p> <pre class="lang-none prettyprint-override"><code>&gt;&gt; Index: 8 entries, count to max &gt;&gt; Data columns: &gt;&gt; x1 8 non-null values &gt;&gt; x2 8 non-null values &gt;&gt; x3 8 non-null values &gt;&gt; x4 8 non-null values &gt;&gt; x5 8 non-null values &gt;&gt; x6 8 non-null values &gt;&gt; x7 8 non-null values </code></pre> <p>The &quot;8&quot; value is given whether there are 6 or 7 columns. What does the &quot;8&quot; refer to?</p> <p>I have already tried dragging the <a href="https://en.wikipedia.org/wiki/IDLE" rel="noreferrer">IDLE</a> window larger, as well as increasing the &quot;Configure IDLE&quot; width options, to no avail.</p>
<p><strong>Update: Pandas 0.23.4 onwards</strong></p> <p>This is not necessary. Pandas autodetects the size of your terminal window if you set <code>pd.options.display.width = 0</code>. (For older versions see at bottom.)</p> <p><code>pandas.set_printoptions(...)</code> is deprecated. Instead, use <code>pandas.set_option(optname, val)</code>, or equivalently <code>pd.options.&lt;opt.hierarchical.name&gt; = val</code>. Like:</p> <pre><code>import pandas as pd pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) </code></pre> <p>Here is the <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.set_option.html" rel="noreferrer">help for <code>set_option</code></a>:</p> <pre> set_option(pat,value) - Sets the value of the specified option Available options: display.[chop_threshold, colheader_justify, column_space, date_dayfirst, date_yearfirst, encoding, expand_frame_repr, float_format, height, line_width, max_columns, max_colwidth, max_info_columns, max_info_rows, max_rows, max_seq_items, mpl_style, multi_sparse, notebook_repr_html, pprint_nest_depth, precision, width] mode.[sim_interactive, use_inf_as_null] Parameters ---------- pat - str/regexp which should match a single option. Note: partial matches are supported for convenience, but unless you use the full option name (e.g., *x.y.z.option_name*), your code may break in future versions if new options with similar names are introduced. value - new value of option. Returns ------- None Raises ------ KeyError if no such option exists display.chop_threshold: [default: None] [currently: None] : float or None if set to a float value, all float values smaller then the given threshold will be displayed as exactly 0 by repr and friends. display.colheader_justify: [default: right] [currently: right] : 'left'/'right' Controls the justification of column headers. used by DataFrameFormatter. display.column_space: [default: 12] [currently: 12]No description available. display.date_dayfirst: [default: False] [currently: False] : boolean When True, prints and parses dates with the day first, eg 20/01/2005 display.date_yearfirst: [default: False] [currently: False] : boolean When True, prints and parses dates with the year first, e.g., 2005/01/20 display.encoding: [default: UTF-8] [currently: UTF-8] : str/unicode Defaults to the detected encoding of the console. Specifies the encoding to be used for strings returned by to_string, these are generally strings meant to be displayed on the console. display.expand_frame_repr: [default: True] [currently: True] : boolean Whether to print out the full DataFrame repr for wide DataFrames across multiple lines, `max_columns` is still respected, but the output will wrap-around across multiple "pages" if it's width exceeds `display.width`. display.float_format: [default: None] [currently: None] : callable The callable should accept a floating point number and return a string with the desired format of the number. This is used in some places like SeriesFormatter. See core.format.EngFormatter for an example. display.height: [default: 60] [currently: 1000] : int Deprecated. (Deprecated, use `display.height` instead.) display.line_width: [default: 80] [currently: 1000] : int Deprecated. (Deprecated, use `display.width` instead.) display.max_columns: [default: 20] [currently: 500] : int max_rows and max_columns are used in __repr__() methods to decide if to_string() or info() is used to render an object to a string. In case python/IPython is running in a terminal this can be set to 0 and Pandas will correctly auto-detect the width the terminal and swap to a smaller format in case all columns would not fit vertically. The IPython notebook, IPython qtconsole, or IDLE do not run in a terminal and hence it is not possible to do correct auto-detection. 'None' value means unlimited. display.max_colwidth: [default: 50] [currently: 50] : int The maximum width in characters of a column in the repr of a Pandas data structure. When the column overflows, a "..." placeholder is embedded in the output. display.max_info_columns: [default: 100] [currently: 100] : int max_info_columns is used in DataFrame.info method to decide if per column information will be printed. display.max_info_rows: [default: 1690785] [currently: 1690785] : int or None max_info_rows is the maximum number of rows for which a frame will perform a null check on its columns when repr'ing To a console. The default is 1,000,000 rows. So, if a DataFrame has more 1,000,000 rows there will be no null check performed on the columns and thus the representation will take much less time to display in an interactive session. A value of None means always perform a null check when repr'ing. display.max_rows: [default: 60] [currently: 500] : int This sets the maximum number of rows Pandas should output when printing out various output. For example, this value determines whether the repr() for a dataframe prints out fully or just a summary repr. 'None' value means unlimited. display.max_seq_items: [default: None] [currently: None] : int or None when pretty-printing a long sequence, no more then `max_seq_items` will be printed. If items are ommitted, they will be denoted by the addition of "..." to the resulting string. If set to None, the number of items to be printed is unlimited. display.mpl_style: [default: None] [currently: None] : bool Setting this to 'default' will modify the rcParams used by matplotlib to give plots a more pleasing visual style by default. Setting this to None/False restores the values to their initial value. display.multi_sparse: [default: True] [currently: True] : boolean "sparsify" MultiIndex display (don't display repeated elements in outer levels within groups) display.notebook_repr_html: [default: True] [currently: True] : boolean When True, IPython notebook will use html representation for Pandas objects (if it is available). display.pprint_nest_depth: [default: 3] [currently: 3] : int Controls the number of nested levels to process when pretty-printing display.precision: [default: 7] [currently: 7] : int Floating point output precision (number of significant digits). This is only a suggestion display.width: [default: 80] [currently: 1000] : int Width of the display in characters. In case python/IPython is running in a terminal this can be set to None and Pandas will correctly auto-detect the width. Note that the IPython notebook, IPython qtconsole, or IDLE do not run in a terminal and hence it is not possible to correctly detect the width. mode.sim_interactive: [default: False] [currently: False] : boolean Whether to simulate interactive mode for purposes of testing mode.use_inf_as_null: [default: False] [currently: False] : boolean True means treat None, NaN, INF, -INF as null (old way), False means None and NaN are null, but INF, -INF are not null (new way). Call def: pd.set_option(self, *args, **kwds) </pre> <hr /> <p>Older version information. Much of this has been deprecated.</p> <p>As @bmu <a href="https://stackoverflow.com/a/11708664/623735">mentioned</a>, Pandas auto detects (by default) the size of the display area, a summary view will be used when an object repr does not fit on the display. You mentioned resizing the IDLE window, to no effect. If you do <code>print df.describe().to_string()</code> does it fit on the IDLE window?</p> <p>The terminal size is determined by <code>pandas.util.terminal.get_terminal_size()</code> (deprecated and removed), this returns a tuple containing the <code>(width, height)</code> of the display. Does the output match the size of your IDLE window? There might be an issue (there was one before when running a terminal in Emacs).</p> <p>Note that it is possible to bypass the autodetect, <code>pandas.set_printoptions(max_rows=200, max_columns=10)</code> will never switch to summary view if number of rows, columns does not exceed the given limits.</p> <hr /> <p>The 'max_colwidth' option helps in seeing untruncated form of each column.</p> <p><a href="https://i.stack.imgur.com/J412l.png" rel="noreferrer"><img src="https://i.stack.imgur.com/J412l.png" alt="TruncatedColumnDisplay" /></a></p>
{ "question_id": 11707586, "question_date": "2012-07-29T07:44:51.610Z", "question_score": 900, "tags": "python|pandas|printing|column-width", "answer_id": 11711637, "answer_date": "2012-07-29T18:02:02.687Z", "answer_score": 1300 }
Please answer the following Stack Overflow question: Title: How can I list all foreign keys referencing a given table in SQL Server? <p>I need to remove a highly referenced table in a SQL Server database. How can I get a list of all the foreign key constraints I will need to remove in order to drop the table?</p> <p>(SQL answers preferable over clicking about in the GUI of the management studio.)</p>
<p>Not sure why no one suggested but I use <code>sp_fkeys</code> to query foreign keys for a given table:</p> <pre><code>EXEC sp_fkeys 'TableName' </code></pre> <p>You can also specify the schema:</p> <pre><code>EXEC sp_fkeys @pktable_name = 'TableName', @pktable_owner = 'dbo' </code></pre> <p>Without specifying the schema, the <a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-fkeys-transact-sql" rel="noreferrer">docs</a> state the following:</p> <blockquote> <p>If pktable_owner is not specified, the default table visibility rules of the underlying DBMS apply.</p> <p>In SQL Server, if the current user owns a table with the specified name, that table's columns are returned. If pktable_owner is not specified and the current user does not own a table with the specified pktable_name, the procedure looks for a table with the specified pktable_name owned by the database owner. If one exists, that table's columns are returned.</p> </blockquote>
{ "question_id": 483193, "question_date": "2009-01-27T12:17:59.193Z", "question_score": 900, "tags": "sql|sql-server|tsql", "answer_id": 12956348, "answer_date": "2012-10-18T13:53:51.140Z", "answer_score": 1330 }
Please answer the following Stack Overflow question: Title: How to determine equality for two JavaScript objects? <p>A strict equality operator will tell you if two object <strong>types</strong> are equal. However, is there a way to tell if two objects are equal, <strong>much like the hash code</strong> value in Java?</p> <p>Stack Overflow question <em><a href="https://stackoverflow.com/questions/194846">Is there any kind of hashCode function in JavaScript?</a></em> is similar to this question, but requires a more academic answer. The scenario above demonstrates why it would be necessary to have one, and I'm wondering if there is any <strong>equivalent solution</strong>.</p>
<p><strong>The short answer</strong></p> <p>The simple answer is: No, there is no generic means to determine that an object is equal to another in the sense you mean. The exception is when you are strictly thinking of an object being typeless.</p> <p><strong>The long answer</strong></p> <p>The concept is that of an Equals method that compares two different instances of an object to indicate whether they are equal at a value level. However, it is up to the specific type to define how an <code>Equals</code> method should be implemented. An iterative comparison of attributes that have primitive values may not be enough: an object may contain attributes which are not relevant to equality. For example,</p> <pre><code> function MyClass(a, b) { var c; this.getCLazy = function() { if (c === undefined) c = a * b // imagine * is really expensive return c; } } </code></pre> <p>In this above case, <code>c</code> is not really important to determine whether any two instances of MyClass are equal, only <code>a</code> and <code>b</code> are important. In some cases <code>c</code> might vary between instances and yet not be significant during comparison.</p> <p>Note this issue applies when members may themselves also be instances of a type and these each would all be required to have a means of determining equality.</p> <p>Further complicating things is that in JavaScript the distinction between data and method is blurred.</p> <p>An object may reference a method that is to be called as an event handler, and this would likely not be considered part of its 'value state'. Whereas another object may well be assigned a function that performs an important calculation and thereby makes this instance different from others simply because it references a different function.</p> <p>What about an object that has one of its existing prototype methods overridden by another function? Could it still be considered equal to another instance that it otherwise identical? That question can only be answered in each specific case for each type.</p> <p>As stated earlier, the exception would be a strictly typeless object. In which case the only sensible choice is an iterative and recursive comparison of each member. Even then one has to ask what is the 'value' of a function?</p>
{ "question_id": 201183, "question_date": "2008-10-14T13:41:07.357Z", "question_score": 900, "tags": "javascript|object|equals|hashcode", "answer_id": 201471, "answer_date": "2008-10-14T14:48:47.440Z", "answer_score": 220 }
Please answer the following Stack Overflow question: Title: Read a file line by line assigning the value to a variable <p>I have the following .txt file:</p> <pre class="lang-none prettyprint-override"><code>Marco Paolo Antonio </code></pre> <p>I want to read it line-by-line, and for each line I want to assign a .txt line value to a variable. Supposing my variable is <code>$name</code>, the flow is:</p> <ul> <li>Read first line from file</li> <li>Assign <code>$name</code> = "Marco"</li> <li>Do some tasks with <code>$name</code></li> <li>Read second line from file</li> <li>Assign <code>$name</code> = "Paolo"</li> </ul>
<p>The following reads a file passed as an argument line by line:</p> <pre><code>while IFS= read -r line; do echo "Text read from file: $line" done &lt; my_filename.txt </code></pre> <p>This is the <a href="http://mywiki.wooledge.org/BashFAQ/001" rel="noreferrer">standard form</a> for reading lines from a file in a loop. Explanation:</p> <ul> <li><code>IFS=</code> (or <code>IFS=''</code>) prevents leading/trailing whitespace from being trimmed.</li> <li><code>-r</code> prevents backslash escapes from being interpreted.</li> </ul> <p>Or you can put it in a bash file helper script, example contents:</p> <pre><code>#!/bin/bash while IFS= read -r line; do echo "Text read from file: $line" done &lt; "$1" </code></pre> <p>If the above is saved to a script with filename <code>readfile</code>, it can be run as follows:</p> <pre><code>chmod +x readfile ./readfile filename.txt </code></pre> <p>If the file isn’t a <a href="https://stackoverflow.com/a/729795/1968">standard POSIX text file</a> (= not terminated by a newline character), the loop can be modified to handle trailing partial lines:</p> <pre><code>while IFS= read -r line || [[ -n "$line" ]]; do echo "Text read from file: $line" done &lt; "$1" </code></pre> <p>Here, <code>|| [[ -n $line ]]</code> prevents the last line from being ignored if it doesn't end with a <code>\n</code> (since <code>read</code> returns a non-zero exit code when it encounters EOF).</p> <p>If the commands inside the loop also read from standard input, the file descriptor used by <code>read</code> can be chanced to something else (avoid the <a href="https://en.wikipedia.org/wiki/File_descriptor" rel="noreferrer">standard file descriptors</a>), e.g.:</p> <pre><code>while IFS= read -r -u3 line; do echo "Text read from file: $line" done 3&lt; "$1" </code></pre> <p>(Non-Bash shells might not know <code>read -u3</code>; use <code>read &lt;&amp;3</code> instead.)</p>
{ "question_id": 10929453, "question_date": "2012-06-07T09:49:09.860Z", "question_score": 899, "tags": "bash", "answer_id": 10929511, "answer_date": "2012-06-07T09:53:38.333Z", "answer_score": 1615 }
Please answer the following Stack Overflow question: Title: Reset identity seed after deleting records in SQL Server <p>I have inserted records into a SQL Server database table. The table had a primary key defined and the auto increment identity seed is set to “Yes”. This is done primarily because in SQL Azure, each table has to have a primary key and identity defined. </p> <p>But since I have to delete some records from the table, the identity seed for those tables will be disturbed and the index column (which is auto-generated with an increment of 1) will get disturbed.</p> <p><strong>How can I reset the identity column after I deleted the records so that the column has sequence in ascending numerical order?</strong></p> <p>The identity column is not used as a foreign key anywhere in database.</p>
<p>The <a href="http://technet.microsoft.com/en-us/library/ms176057.aspx" rel="noreferrer"><code>DBCC CHECKIDENT</code></a> management command is used to reset identity counter. The command syntax is:</p> <pre><code>DBCC CHECKIDENT (table_name [, { NORESEED | { RESEED [, new_reseed_value ]}}]) [ WITH NO_INFOMSGS ] </code></pre> <p>Example:</p> <pre><code>DBCC CHECKIDENT ('[TestTable]', RESEED, 0); GO </code></pre> <p>It was not supported in previous versions of the Azure SQL Database but is supported now.</p> <hr /> <p>Thanks to <a href="https://stackoverflow.com/questions/21824478/reset-identity-seed-after-deleting-records-in-sql-server/21824729?noredirect=1#comment97903325_21824729">Solomon Rutzky</a> the <a href="https://docs.microsoft.com/en-us/sql/t-sql/database-console-commands/dbcc-checkident-transact-sql" rel="noreferrer">docs</a> for the command are now fixed.</p>
{ "question_id": 21824478, "question_date": "2014-02-17T08:51:48.637Z", "question_score": 899, "tags": "sql|sql-server|database|sql-server-2008|azure-sql-database", "answer_id": 21824729, "answer_date": "2014-02-17T09:04:23.027Z", "answer_score": 1414 }
Please answer the following Stack Overflow question: Title: How to properly ignore exceptions <p>When you just want to do a try-except without handling the exception, how do you do it in Python?</p> <p>Is the following the right way to do it?</p> <pre><code>try: shutil.rmtree(path) except: pass </code></pre>
<pre><code>try: doSomething() except Exception: pass </code></pre> <p>or</p> <pre><code>try: doSomething() except: pass </code></pre> <p>The difference is that the second one will also catch <code>KeyboardInterrupt</code>, <code>SystemExit</code> and stuff like that, which are derived directly from <code>BaseException</code>, not <code>Exception</code>.</p> <p>See documentation for details:</p> <ul> <li><a href="http://docs.python.org/reference/compound_stmts.html#try" rel="noreferrer"><code>try</code> statement</a></li> <li><a href="http://docs.python.org/library/exceptions" rel="noreferrer">exceptions</a></li> </ul> <p>However, it is generally bad practice to catch every error - see <a href="https://stackoverflow.com/questions/21553327/why-is-except-pass-a-bad-programming-practice">Why is &quot;except: pass&quot; a bad programming practice?</a></p>
{ "question_id": 730764, "question_date": "2009-04-08T16:23:00.640Z", "question_score": 899, "tags": "python|exception|try-except", "answer_id": 730778, "answer_date": "2009-04-08T16:25:10.150Z", "answer_score": 1170 }
Please answer the following Stack Overflow question: Title: Scanner is skipping nextLine() after using next() or nextFoo()? <p>I am using the <code>Scanner</code> methods <code>nextInt()</code> and <code>nextLine()</code> for reading input. </p> <p>It looks like this:</p> <pre><code>System.out.println("Enter numerical value"); int option; option = input.nextInt(); // Read numerical value from input System.out.println("Enter 1st string"); String string1 = input.nextLine(); // Read 1st string (this is skipped) System.out.println("Enter 2nd string"); String string2 = input.nextLine(); // Read 2nd string (this appears right after reading numerical value) </code></pre> <p>The problem is that after entering the numerical value, the first <code>input.nextLine()</code> is skipped and the second <code>input.nextLine()</code> is executed, so that my output looks like this:</p> <pre><code>Enter numerical value 3 // This is my input Enter 1st string // The program is supposed to stop here and wait for my input, but is skipped Enter 2nd string // ...and this line is executed and waits for my input </code></pre> <p>I tested my application and it looks like the problem lies in using <code>input.nextInt()</code>. If I delete it, then both <code>string1 = input.nextLine()</code> and <code>string2 = input.nextLine()</code> are executed as I want them to be.</p>
<p>That's because the <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29" rel="noreferrer"><code>Scanner.nextInt</code></a> method does not read the <em>newline</em> character in your input created by hitting "Enter," and so the call to <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextLine%28%29" rel="noreferrer"><code>Scanner.nextLine</code></a> returns after reading that <em>newline</em>.</p> <p>You will encounter the similar behaviour when you use <code>Scanner.nextLine</code> after <a href="http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#next%28%29" rel="noreferrer"><code>Scanner.next()</code></a> or any <code>Scanner.nextFoo</code> method (except <code>nextLine</code> itself).</p> <p><strong>Workaround:</strong></p> <ul> <li><p>Either put a <code>Scanner.nextLine</code> call after each <code>Scanner.nextInt</code> or <code>Scanner.nextFoo</code> to consume rest of that line including <em>newline</em> </p> <pre><code>int option = input.nextInt(); input.nextLine(); // Consume newline left-over String str1 = input.nextLine(); </code></pre></li> <li><p>Or, even better, read the input through <code>Scanner.nextLine</code> and convert your input to the proper format you need. For example, you may convert to an integer using <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt(java.lang.String)" rel="noreferrer"><code>Integer.parseInt(String)</code></a> method.</p> <pre><code>int option = 0; try { option = Integer.parseInt(input.nextLine()); } catch (NumberFormatException e) { e.printStackTrace(); } String str1 = input.nextLine(); </code></pre></li> </ul>
{ "question_id": 13102045, "question_date": "2012-10-27T16:37:01.840Z", "question_score": 899, "tags": "java|io|java.util.scanner", "answer_id": 13102066, "answer_date": "2012-10-27T16:39:20.083Z", "answer_score": 1098 }
Please answer the following Stack Overflow question: Title: How to Join to first row <p>I'll use a concrete, but hypothetical, example.</p> <p>Each <strong>Order</strong> normally has only one <strong>line item</strong>:</p> <p><strong>Orders:</strong></p> <pre class="lang-none prettyprint-override"><code>OrderGUID OrderNumber ========= ============ {FFB2...} STL-7442-1 {3EC6...} MPT-9931-8A </code></pre> <p><strong>LineItems:</strong></p> <pre class="lang-none prettyprint-override"><code>LineItemGUID Order ID Quantity Description ============ ======== ======== ================================= {098FBE3...} 1 7 prefabulated amulite {1609B09...} 2 32 spurving bearing </code></pre> <p>But occasionally there will be an order with two line items:</p> <pre class="lang-none prettyprint-override"><code>LineItemID Order ID Quantity Description ========== ======== ======== ================================= {A58A1...} 6,784,329 5 pentametric fan {0E9BC...} 6,784,329 5 differential girdlespring </code></pre> <p>Normally when showing the orders to the user:</p> <pre><code>SELECT Orders.OrderNumber, LineItems.Quantity, LineItems.Description FROM Orders INNER JOIN LineItems ON Orders.OrderID = LineItems.OrderID </code></pre> <p>I want to show the single item on the order. But with this occasional order containing two (or more) items, the orders would <em>appear</em> be <strong>duplicated</strong>:</p> <pre class="lang-none prettyprint-override"><code>OrderNumber Quantity Description =========== ======== ==================== STL-7442-1 7 prefabulated amulite MPT-9931-8A 32 spurving bearing KSG-0619-81 5 panametric fan KSG-0619-81 5 differential girdlespring </code></pre> <p>What I really want is to have SQL Server <em>just pick one</em>, as it will be <em>good enough</em>:</p> <pre class="lang-none prettyprint-override"><code>OrderNumber Quantity Description =========== ======== ==================== STL-7442-1 7 prefabulated amulite MPT-9931-8A 32 differential girdlespring KSG-0619-81 5 panametric fan </code></pre> <p>If I get adventurous, I might show the user, an ellipsis to indicate that there's more than one:</p> <pre class="lang-none prettyprint-override"><code>OrderNumber Quantity Description =========== ======== ==================== STL-7442-1 7 prefabulated amulite MPT-9931-8A 32 differential girdlespring KSG-0619-81 5 panametric fan, ... </code></pre> <p>So the question is how to either</p> <ul> <li>eliminate "duplicate" rows</li> <li>only join to one of the rows, to avoid duplication</li> </ul> <h2>First attempt</h2> <p>My first naive attempt was to only join to the "<strong>TOP 1</strong>" line items:</p> <pre class="lang-sql prettyprint-override"><code>SELECT Orders.OrderNumber, LineItems.Quantity, LineItems.Description FROM Orders INNER JOIN ( SELECT TOP 1 LineItems.Quantity, LineItems.Description FROM LineItems WHERE LineItems.OrderID = Orders.OrderID) LineItems2 ON 1=1 </code></pre> <p>But that gives the error:</p> <blockquote> <p>The column or prefix 'Orders' does not<br> match with a table name or alias name<br> used in the query. </p> </blockquote> <p>Presumably because the inner select doesn't see the outer table.</p>
<pre><code>SELECT Orders.OrderNumber, LineItems.Quantity, LineItems.Description FROM Orders JOIN LineItems ON LineItems.LineItemGUID = ( SELECT TOP 1 LineItemGUID FROM LineItems WHERE OrderID = Orders.OrderID ) </code></pre> <p>In SQL Server 2005 and above, you could just replace <code>INNER JOIN</code> with <code>CROSS APPLY</code>:</p> <pre><code>SELECT Orders.OrderNumber, LineItems2.Quantity, LineItems2.Description FROM Orders CROSS APPLY ( SELECT TOP 1 LineItems.Quantity, LineItems.Description FROM LineItems WHERE LineItems.OrderID = Orders.OrderID ) LineItems2 </code></pre> <p>Please note that <code>TOP 1</code> without <code>ORDER BY</code> is not deterministic: this query you will get you one line item per order, but it is not defined which one will it be.</p> <p>Multiple invocations of the query can give you different line items for the same order, even if the underlying did not change.</p> <p>If you want deterministic order, you should add an <code>ORDER BY</code> clause to the innermost query.</p> <p><a href="http://sqlfiddle.com/#!18/44d008/6" rel="noreferrer">Example sqlfiddle</a></p>
{ "question_id": 2043259, "question_date": "2010-01-11T16:44:37.123Z", "question_score": 899, "tags": "sql|sql-server|tsql|sql-server-2000", "answer_id": 2043290, "answer_date": "2010-01-11T16:48:26.380Z", "answer_score": 1421 }
Please answer the following Stack Overflow question: Title: What is a clean "pythonic" way to implement multiple constructors? <p>I can't find a definitive answer for this. As far as I know, you can't have multiple <code>__init__</code> functions in a Python class. So how do I solve this problem?</p> <p>Suppose I have a class called <code>Cheese</code> with the <code>number_of_holes</code> property. How can I have two ways of creating cheese objects...</p> <ol> <li>One that takes a number of holes like this: <code>parmesan = Cheese(num_holes = 15)</code>.</li> <li>And one that takes no arguments and just randomizes the <code>number_of_holes</code> property: <code>gouda = Cheese()</code>.</li> </ol> <p>I can think of only one way to do this, but this seems clunky:</p> <pre><code>class Cheese(): def __init__(self, num_holes = 0): if (num_holes == 0): # Randomize number_of_holes else: number_of_holes = num_holes </code></pre> <p>What do you say? Is there another way?</p>
<p>Actually <code>None</code> is much better for "magic" values:</p> <pre><code>class Cheese(): def __init__(self, num_holes = None): if num_holes is None: ... </code></pre> <p>Now if you want complete freedom of adding more parameters:</p> <pre><code>class Cheese(): def __init__(self, *args, **kwargs): #args -- tuple of anonymous arguments #kwargs -- dictionary of named arguments self.num_holes = kwargs.get('num_holes',random_holes()) </code></pre> <p>To better explain the concept of <code>*args</code> and <code>**kwargs</code> (you can actually change these names):</p> <pre><code>def f(*args, **kwargs): print 'args: ', args, ' kwargs: ', kwargs &gt;&gt;&gt; f('a') args: ('a',) kwargs: {} &gt;&gt;&gt; f(ar='a') args: () kwargs: {'ar': 'a'} &gt;&gt;&gt; f(1,2,param=3) args: (1, 2) kwargs: {'param': 3} </code></pre> <p><a href="http://docs.python.org/reference/expressions.html#calls" rel="noreferrer">http://docs.python.org/reference/expressions.html#calls</a></p>
{ "question_id": 682504, "question_date": "2009-03-25T17:00:21.807Z", "question_score": 899, "tags": "python|class|constructor", "answer_id": 682513, "answer_date": "2009-03-25T17:03:38.430Z", "answer_score": 942 }
Please answer the following Stack Overflow question: Title: What is the best project structure for a Python application? <p>Imagine that you want to develop a non-trivial end-user desktop (not web) application in Python. What is the best way to structure the project's folder hierarchy?</p> <p>Desirable features are ease of maintenance, IDE-friendliness, suitability for source control branching/merging, and easy generation of install packages.</p> <p>In particular:</p> <ol> <li>Where do you put the source?</li> <li>Where do you put application startup scripts?</li> <li>Where do you put the IDE project cruft?</li> <li>Where do you put the unit/acceptance tests?</li> <li>Where do you put non-Python data such as config files?</li> <li>Where do you put non-Python sources such as C++ for pyd/so binary extension modules?</li> </ol>
<p>Doesn't too much matter. Whatever makes you happy will work. There aren't a lot of silly rules because Python projects can be simple.</p> <ul> <li><code>/scripts</code> or <code>/bin</code> for that kind of command-line interface stuff</li> <li><code>/tests</code> for your tests</li> <li><code>/lib</code> for your C-language libraries</li> <li><code>/doc</code> for most documentation</li> <li><code>/apidoc</code> for the Epydoc-generated API docs.</li> </ul> <p>And the top-level directory can contain README's, Config's and whatnot.</p> <p>The hard choice is whether or not to use a <code>/src</code> tree. Python doesn't have a distinction between <code>/src</code>, <code>/lib</code>, and <code>/bin</code> like Java or C has.</p> <p>Since a top-level <code>/src</code> directory is seen by some as meaningless, your top-level directory can be the top-level architecture of your application.</p> <ul> <li><code>/foo</code></li> <li><code>/bar</code></li> <li><code>/baz</code></li> </ul> <p>I recommend putting all of this under the "name-of-my-product" directory. So, if you're writing an application named <code>quux</code>, the directory that contains all this stuff is named <code>/quux</code>.</p> <p>Another project's <code>PYTHONPATH</code>, then, can include <code>/path/to/quux/foo</code> to reuse the <code>QUUX.foo</code> module. </p> <p>In my case, since I use Komodo Edit, my IDE cuft is a single .KPF file. I actually put that in the top-level <code>/quux</code> directory, and omit adding it to SVN.</p>
{ "question_id": 193161, "question_date": "2008-10-10T21:50:34.220Z", "question_score": 898, "tags": "python|directory-structure|organization|project-structure", "answer_id": 193181, "answer_date": "2008-10-10T22:03:40.637Z", "answer_score": 479 }
Please answer the following Stack Overflow question: Title: How do I conditionally add attributes to React components? <p>Is there a way to only add attributes to a React component if a certain condition is met?</p> <p>I'm supposed to add required and readOnly attributes to form elements based on an Ajax call after render, but I can't see how to solve this since <code>readOnly=&quot;false&quot;</code> is not the same as omitting the attribute completely.</p> <p>The example below should explain what I want, but it doesn't work.</p> <blockquote> <p>(Parse Error: Unexpected identifier)</p> </blockquote> <pre class="lang-js prettyprint-override"><code>function MyInput({isRequired}) { return &lt;input classname=&quot;foo&quot; {isRequired ? &quot;required&quot; : &quot;&quot;} /&gt; } </code></pre>
<p>Apparently, for certain attributes, React is intelligent enough to omit the attribute if the value you pass to it is not truthy. For example:</p> <pre><code>const InputComponent = function() { const required = true; const disabled = false; return ( &lt;input type=&quot;text&quot; disabled={disabled} required={required} /&gt; ); } </code></pre> <p>will result in:</p> <pre><code>&lt;input type=&quot;text&quot; required&gt; </code></pre> <p><strong>Update:</strong> if anyone is curious as to how/why this happens, you can find details in ReactDOM's source code, specifically at lines <a href="https://github.com/facebook/react/blob/8b88ac2592c5f555f315f9440cbb665dd1e7457a/packages/react-dom/src/shared/DOMProperty.js#L30" rel="noreferrer">30</a> and <a href="https://github.com/facebook/react/blob/8b88ac2592c5f555f315f9440cbb665dd1e7457a/packages/react-dom/src/shared/DOMProperty.js#L167" rel="noreferrer">167</a> of the <a href="https://github.com/facebook/react/blob/8b88ac2592c5f555f315f9440cbb665dd1e7457a/packages/react-dom/src/shared/DOMProperty.js" rel="noreferrer">DOMProperty.js</a> file.</p>
{ "question_id": 31163693, "question_date": "2015-07-01T14:07:27.197Z", "question_score": 898, "tags": "javascript|reactjs", "answer_id": 31164090, "answer_date": "2015-07-01T14:23:58.990Z", "answer_score": 799 }
Please answer the following Stack Overflow question: Title: Why is 2 * (i * i) faster than 2 * i * i in Java? <p>The following Java program takes on average between 0.50 secs and 0.55 secs to run:</p> <pre class="lang-java prettyprint-override"><code>public static void main(String[] args) { long startTime = System.nanoTime(); int n = 0; for (int i = 0; i &lt; 1000000000; i++) { n += 2 * (i * i); } System.out.println( (double) (System.nanoTime() - startTime) / 1000000000 + &quot; s&quot;); System.out.println(&quot;n = &quot; + n); } </code></pre> <p>If I replace <code>2 * (i * i)</code> with <code>2 * i * i</code>, it takes between 0.60 and 0.65 secs to run. How come?</p> <p>I ran each version of the program 15 times, alternating between the two. Here are the results:</p> <pre class="lang-text prettyprint-override"><code> 2*(i*i) │ 2*i*i ──────────┼────────── 0.5183738 │ 0.6246434 0.5298337 │ 0.6049722 0.5308647 │ 0.6603363 0.5133458 │ 0.6243328 0.5003011 │ 0.6541802 0.5366181 │ 0.6312638 0.515149 │ 0.6241105 0.5237389 │ 0.627815 0.5249942 │ 0.6114252 0.5641624 │ 0.6781033 0.538412 │ 0.6393969 0.5466744 │ 0.6608845 0.531159 │ 0.6201077 0.5048032 │ 0.6511559 0.5232789 │ 0.6544526 </code></pre> <p>The fastest run of <code>2 * i * i</code> took longer than the slowest run of <code>2 * (i * i)</code>. If they had the same efficiency, the probability of this happening would be less than <code>1/2^15 * 100% = 0.00305%</code>.</p>
<p>There is a slight difference in the ordering of the bytecode.</p> <p><code>2 * (i * i)</code>:</p> <pre><code> iconst_2 iload0 iload0 imul imul iadd </code></pre> <p>vs <code>2 * i * i</code>:</p> <pre><code> iconst_2 iload0 imul iload0 imul iadd </code></pre> <p>At first sight this should not make a difference; if anything the second version is more optimal since it uses one slot less.</p> <p>So we need to dig deeper into the lower level (JIT)<sup>1</sup>.</p> <p>Remember that JIT tends to unroll small loops very aggressively. Indeed we observe a 16x unrolling for the <code>2 * (i * i)</code> case:</p> <pre><code>030 B2: # B2 B3 &lt;- B1 B2 Loop: B2-B2 inner main of N18 Freq: 1e+006 030 addl R11, RBP # int 033 movl RBP, R13 # spill 036 addl RBP, #14 # int 039 imull RBP, RBP # int 03c movl R9, R13 # spill 03f addl R9, #13 # int 043 imull R9, R9 # int 047 sall RBP, #1 049 sall R9, #1 04c movl R8, R13 # spill 04f addl R8, #15 # int 053 movl R10, R8 # spill 056 movdl XMM1, R8 # spill 05b imull R10, R8 # int 05f movl R8, R13 # spill 062 addl R8, #12 # int 066 imull R8, R8 # int 06a sall R10, #1 06d movl [rsp + #32], R10 # spill 072 sall R8, #1 075 movl RBX, R13 # spill 078 addl RBX, #11 # int 07b imull RBX, RBX # int 07e movl RCX, R13 # spill 081 addl RCX, #10 # int 084 imull RCX, RCX # int 087 sall RBX, #1 089 sall RCX, #1 08b movl RDX, R13 # spill 08e addl RDX, #8 # int 091 imull RDX, RDX # int 094 movl RDI, R13 # spill 097 addl RDI, #7 # int 09a imull RDI, RDI # int 09d sall RDX, #1 09f sall RDI, #1 0a1 movl RAX, R13 # spill 0a4 addl RAX, #6 # int 0a7 imull RAX, RAX # int 0aa movl RSI, R13 # spill 0ad addl RSI, #4 # int 0b0 imull RSI, RSI # int 0b3 sall RAX, #1 0b5 sall RSI, #1 0b7 movl R10, R13 # spill 0ba addl R10, #2 # int 0be imull R10, R10 # int 0c2 movl R14, R13 # spill 0c5 incl R14 # int 0c8 imull R14, R14 # int 0cc sall R10, #1 0cf sall R14, #1 0d2 addl R14, R11 # int 0d5 addl R14, R10 # int 0d8 movl R10, R13 # spill 0db addl R10, #3 # int 0df imull R10, R10 # int 0e3 movl R11, R13 # spill 0e6 addl R11, #5 # int 0ea imull R11, R11 # int 0ee sall R10, #1 0f1 addl R10, R14 # int 0f4 addl R10, RSI # int 0f7 sall R11, #1 0fa addl R11, R10 # int 0fd addl R11, RAX # int 100 addl R11, RDI # int 103 addl R11, RDX # int 106 movl R10, R13 # spill 109 addl R10, #9 # int 10d imull R10, R10 # int 111 sall R10, #1 114 addl R10, R11 # int 117 addl R10, RCX # int 11a addl R10, RBX # int 11d addl R10, R8 # int 120 addl R9, R10 # int 123 addl RBP, R9 # int 126 addl RBP, [RSP + #32 (32-bit)] # int 12a addl R13, #16 # int 12e movl R11, R13 # spill 131 imull R11, R13 # int 135 sall R11, #1 138 cmpl R13, #999999985 13f jl B2 # loop end P=1.000000 C=6554623.000000 </code></pre> <p>We see that there is 1 register that is &quot;spilled&quot; onto the stack.</p> <p>And for the <code>2 * i * i</code> version:</p> <pre><code>05a B3: # B2 B4 &lt;- B1 B2 Loop: B3-B2 inner main of N18 Freq: 1e+006 05a addl RBX, R11 # int 05d movl [rsp + #32], RBX # spill 061 movl R11, R8 # spill 064 addl R11, #15 # int 068 movl [rsp + #36], R11 # spill 06d movl R11, R8 # spill 070 addl R11, #14 # int 074 movl R10, R9 # spill 077 addl R10, #16 # int 07b movdl XMM2, R10 # spill 080 movl RCX, R9 # spill 083 addl RCX, #14 # int 086 movdl XMM1, RCX # spill 08a movl R10, R9 # spill 08d addl R10, #12 # int 091 movdl XMM4, R10 # spill 096 movl RCX, R9 # spill 099 addl RCX, #10 # int 09c movdl XMM6, RCX # spill 0a0 movl RBX, R9 # spill 0a3 addl RBX, #8 # int 0a6 movl RCX, R9 # spill 0a9 addl RCX, #6 # int 0ac movl RDX, R9 # spill 0af addl RDX, #4 # int 0b2 addl R9, #2 # int 0b6 movl R10, R14 # spill 0b9 addl R10, #22 # int 0bd movdl XMM3, R10 # spill 0c2 movl RDI, R14 # spill 0c5 addl RDI, #20 # int 0c8 movl RAX, R14 # spill 0cb addl RAX, #32 # int 0ce movl RSI, R14 # spill 0d1 addl RSI, #18 # int 0d4 movl R13, R14 # spill 0d7 addl R13, #24 # int 0db movl R10, R14 # spill 0de addl R10, #26 # int 0e2 movl [rsp + #40], R10 # spill 0e7 movl RBP, R14 # spill 0ea addl RBP, #28 # int 0ed imull RBP, R11 # int 0f1 addl R14, #30 # int 0f5 imull R14, [RSP + #36 (32-bit)] # int 0fb movl R10, R8 # spill 0fe addl R10, #11 # int 102 movdl R11, XMM3 # spill 107 imull R11, R10 # int 10b movl [rsp + #44], R11 # spill 110 movl R10, R8 # spill 113 addl R10, #10 # int 117 imull RDI, R10 # int 11b movl R11, R8 # spill 11e addl R11, #8 # int 122 movdl R10, XMM2 # spill 127 imull R10, R11 # int 12b movl [rsp + #48], R10 # spill 130 movl R10, R8 # spill 133 addl R10, #7 # int 137 movdl R11, XMM1 # spill 13c imull R11, R10 # int 140 movl [rsp + #52], R11 # spill 145 movl R11, R8 # spill 148 addl R11, #6 # int 14c movdl R10, XMM4 # spill 151 imull R10, R11 # int 155 movl [rsp + #56], R10 # spill 15a movl R10, R8 # spill 15d addl R10, #5 # int 161 movdl R11, XMM6 # spill 166 imull R11, R10 # int 16a movl [rsp + #60], R11 # spill 16f movl R11, R8 # spill 172 addl R11, #4 # int 176 imull RBX, R11 # int 17a movl R11, R8 # spill 17d addl R11, #3 # int 181 imull RCX, R11 # int 185 movl R10, R8 # spill 188 addl R10, #2 # int 18c imull RDX, R10 # int 190 movl R11, R8 # spill 193 incl R11 # int 196 imull R9, R11 # int 19a addl R9, [RSP + #32 (32-bit)] # int 19f addl R9, RDX # int 1a2 addl R9, RCX # int 1a5 addl R9, RBX # int 1a8 addl R9, [RSP + #60 (32-bit)] # int 1ad addl R9, [RSP + #56 (32-bit)] # int 1b2 addl R9, [RSP + #52 (32-bit)] # int 1b7 addl R9, [RSP + #48 (32-bit)] # int 1bc movl R10, R8 # spill 1bf addl R10, #9 # int 1c3 imull R10, RSI # int 1c7 addl R10, R9 # int 1ca addl R10, RDI # int 1cd addl R10, [RSP + #44 (32-bit)] # int 1d2 movl R11, R8 # spill 1d5 addl R11, #12 # int 1d9 imull R13, R11 # int 1dd addl R13, R10 # int 1e0 movl R10, R8 # spill 1e3 addl R10, #13 # int 1e7 imull R10, [RSP + #40 (32-bit)] # int 1ed addl R10, R13 # int 1f0 addl RBP, R10 # int 1f3 addl R14, RBP # int 1f6 movl R10, R8 # spill 1f9 addl R10, #16 # int 1fd cmpl R10, #999999985 204 jl B2 # loop end P=1.000000 C=7419903.000000 </code></pre> <p>Here we observe much more &quot;spilling&quot; and more accesses to the stack <code>[RSP + ...]</code>, due to more intermediate results that need to be preserved.</p> <p>Thus the answer to the question is simple: <code>2 * (i * i)</code> is faster than <code>2 * i * i</code> because the JIT generates more optimal assembly code for the first case.</p> <hr /> <p>But of course it is obvious that neither the first nor the second version is any good; the loop could really benefit from vectorization, since any x86-64 CPU has at least SSE2 support.</p> <p>So it's an issue of the optimizer; as is often the case, it unrolls too aggressively and shoots itself in the foot, all the while missing out on various other opportunities.</p> <p>In fact, modern x86-64 CPUs break down the instructions further into micro-ops (µops) and with features like register renaming, µop caches and loop buffers, loop optimization takes a lot more finesse than a simple unrolling for optimal performance. <a href="https://www.agner.org/optimize/microarchitecture.pdf" rel="noreferrer">According to Agner Fog's optimization guide</a>:</p> <blockquote> <p>The gain in performance due to the µop cache can be quite considerable if the average instruction length is more than 4 bytes. The following methods of optimizing the use of the µop cache may be considered:</p> <ul> <li>Make sure that critical loops are small enough to fit into the µop cache.</li> <li>Align the most critical loop entries and function entries by 32.</li> <li>Avoid unnecessary loop unrolling.</li> <li>Avoid instructions that have extra load time<br /> . . .</li> </ul> </blockquote> <p>Regarding those load times - <a href="https://stackoverflow.com/questions/4087280/approximate-cost-to-access-various-caches-and-main-memory">even the fastest L1D hit costs 4 cycles</a>, an extra register and µop, so yes, even a few accesses to memory will hurt performance in tight loops.</p> <p>But back to the vectorization opportunity - to see how fast it can be, <a href="https://gcc.godbolt.org/z/DdEDny" rel="noreferrer">we can compile a similar C application with GCC</a>, which outright vectorizes it (AVX2 is shown, SSE2 is similar)<sup>2</sup>:</p> <pre><code> vmovdqa ymm0, YMMWORD PTR .LC0[rip] vmovdqa ymm3, YMMWORD PTR .LC1[rip] xor eax, eax vpxor xmm2, xmm2, xmm2 .L2: vpmulld ymm1, ymm0, ymm0 inc eax vpaddd ymm0, ymm0, ymm3 vpslld ymm1, ymm1, 1 vpaddd ymm2, ymm2, ymm1 cmp eax, 125000000 ; 8 calculations per iteration jne .L2 vmovdqa xmm0, xmm2 vextracti128 xmm2, ymm2, 1 vpaddd xmm2, xmm0, xmm2 vpsrldq xmm0, xmm2, 8 vpaddd xmm0, xmm2, xmm0 vpsrldq xmm1, xmm0, 4 vpaddd xmm0, xmm0, xmm1 vmovd eax, xmm0 vzeroupper </code></pre> <p>With run times:</p> <ul> <li>SSE: 0.24 s, or 2 times as fast.</li> <li>AVX: 0.15 s, or 3 times as fast.</li> <li>AVX2: 0.08 s, or 5 times as fast.</li> </ul> <hr /> <p><sup>1</sup> <sub>To get JIT generated assembly output, <a href="https://github.com/ojdkbuild/ojdkbuild/releases" rel="noreferrer">get a debug JVM</a> and run with <code>-XX:+PrintOptoAssembly</code></sub></p> <p><sup>2</sup> <sub>The C version is compiled with the <code>-fwrapv</code> flag, which enables GCC to treat signed integer overflow as a two's-complement wrap-around.</sub></p>
{ "question_id": 53452713, "question_date": "2018-11-23T20:40:10.073Z", "question_score": 898, "tags": "java|performance|benchmarking|bytecode|jit", "answer_id": 53453588, "answer_date": "2018-11-23T22:40:27.097Z", "answer_score": 1237 }
Please answer the following Stack Overflow question: Title: Is there any way to git checkout previous branch? <p>I sort of want the equivalent of <code>cd -</code> for git. If I am in branch <code>master</code> and I checkout <code>foo</code>, I would love to be able to type something like <code>git checkout -</code> to go back to <code>master</code>, and be able to type it again to return to <code>foo</code>.</p> <p>Does anything like this exist? Would it be hard to implement?</p>
<p>From the <a href="https://github.com/git/git/blob/master/Documentation/RelNotes/1.6.2.txt" rel="noreferrer">release notes for 1.6.2</a></p> <blockquote> <p><code>@{-1}</code> is a way to refer to the last branch you were on. This is<br> accepted not only where an object name is expected, but anywhere a branch name is expected and acts as if you typed the branch name.<br> E.g. <code>git branch --track mybranch @{-1}</code>, <code>git merge @{-1}</code>, and<br> <code>git rev-parse --symbolic-full-name @{-1}</code> would work as expected.</p> </blockquote> <p>and</p> <blockquote> <p><code>git checkout -</code> is a shorthand for <code>git checkout @{-1}</code>.</p> </blockquote>
{ "question_id": 7206801, "question_date": "2011-08-26T15:09:11.523Z", "question_score": 898, "tags": "git|git-checkout", "answer_id": 7207542, "answer_date": "2011-08-26T16:05:01.967Z", "answer_score": 1529 }
Please answer the following Stack Overflow question: Title: Changing the color of an hr element <p>I want to change the color of my <code>hr</code> tag using CSS. The code I've tried below doesn't seem to work:</p> <pre class="lang-css prettyprint-override"><code>hr { color: #123455; } </code></pre>
<p>I think you should use <code>border-color</code> instead of <code>color</code>, if your intention is to change the color of the line produced by <code>&lt;hr&gt;</code> tag.</p> <p>Although, it has been pointed in comments that, if you change the size of your line, border will still be as wide as you specified in styles, and line will be filled with the default color (which is not a desired effect most of the time). So it seems like in this case you would also need to specify <code>background-color</code> (as @Ibu suggested in his answer).</p> <p><strong>HTML 5 Boilerplate</strong> project in its default stylesheet <a href="https://github.com/paulirish/html5-boilerplate/blob/ef3c095bafa9a6fa9c771f368d4b30c8ce4deded/css/style.css#L75" rel="noreferrer">specifies</a> the following rule:</p> <pre><code>hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; } </code></pre> <p><strong>An article</strong> titled <a href="http://www.sitepoint.com/12-little-known-css-facts/" rel="noreferrer">“12 Little-Known CSS Facts”</a>, published recently by SitePoint, mentions that <code>&lt;hr&gt;</code> can set its <code>border-color</code> to its parent's <code>color</code> if you specify <code>hr { border-color: inherit }</code>.</p>
{ "question_id": 6382023, "question_date": "2011-06-17T06:15:50.660Z", "question_score": 897, "tags": "html|css", "answer_id": 6382036, "answer_date": "2011-06-17T06:17:17.413Z", "answer_score": 1257 }
Please answer the following Stack Overflow question: Title: How do I get the path of the assembly the code is in? <p>Is there a way to get the path for the assembly in which the current code resides? I do not want the path of the calling assembly, just the one containing the code. </p> <p>Basically my unit test needs to read some xml test files which are located relative to the dll. I want the path to always resolve correctly regardless of whether the testing dll is run from TestDriven.NET, the MbUnit GUI or something else.</p> <p><strong>Edit</strong>: People seem to be misunderstanding what I'm asking.</p> <p>My test library is located in say </p> <blockquote> <p>C:\projects\myapplication\daotests\bin\Debug\daotests.dll</p> </blockquote> <p>and I would like to get this path:</p> <blockquote> <p>C:\projects\myapplication\daotests\bin\Debug\</p> </blockquote> <p>The three suggestions so far fail me when I run from the MbUnit Gui:</p> <ul> <li><p><code>Environment.CurrentDirectory</code> gives <em>c:\Program Files\MbUnit</em></p></li> <li><p><code>System.Reflection.Assembly.GetAssembly(typeof(DaoTests)).Location</code> gives <em>C:\Documents and Settings\george\Local Settings\Temp\ ....\DaoTests.dll</em></p></li> <li><p><code>System.Reflection.Assembly.GetExecutingAssembly().Location</code> gives the same as the previous.</p></li> </ul>
<p><strong>Note</strong>: Assembly.CodeBase is deprecated in .NET Core/.NET 5+: <a href="https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.codebase?view=net-5.0" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assembly.codebase?view=net-5.0</a></p> <p><strong>Original answer:</strong></p> <p>I've defined the following property as we use this often in unit testing.</p> <pre><code>public static string AssemblyDirectory { get { string codeBase = Assembly.GetExecutingAssembly().CodeBase; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); return Path.GetDirectoryName(path); } } </code></pre> <p>The <code>Assembly.Location</code> property sometimes gives you some funny results when using NUnit (where assemblies run from a temporary folder), so I prefer to use <code>CodeBase</code> which gives you the path in URI format, then <code>UriBuild.UnescapeDataString</code> removes the <code>File://</code> at the beginning, and <code>GetDirectoryName</code> changes it to the normal windows format.</p>
{ "question_id": 52797, "question_date": "2008-09-09T20:12:28.340Z", "question_score": 897, "tags": "c#|.net|reflection|mbunit", "answer_id": 283917, "answer_date": "2008-11-12T13:24:56.133Z", "answer_score": 1148 }
Please answer the following Stack Overflow question: Title: What is the difference between single-quoted and double-quoted strings in PHP? <p>I'm a little confused why I see some code in PHP with string placed in single quotes and sometimes in double quotes.</p> <p>I just know in .NET, or the C language, if it is in a single quote, that means it is a character, not a string.</p>
<p><a href="https://php.net/manual/en/language.types.string.php" rel="noreferrer"><strong>PHP strings</strong></a> can be specified not just in <em>two</em> ways, but in <strong>four</strong> ways.</p> <ol> <li><a href="https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single" rel="noreferrer"><strong>Single quoted strings</strong></a> will display things almost completely "as is." Variables and most escape sequences will not be interpreted. The exception is that to display a literal single quote, you can escape it with a back slash <code>\'</code>, and to display a back slash, you can escape it with another backslash <code>\\</code> (<strong>So yes, even single quoted strings are parsed</strong>).</li> <li><a href="https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double" rel="noreferrer"><strong>Double quote strings</strong></a> will display a host of escaped characters (including some regexes), and variables in the strings will be evaluated. An important point here is that <strong>you can use curly braces to isolate the name of the variable you want evaluated</strong>. For example let's say you have the variable <code>$type</code> and you want to <code>echo "The $types are"</code>. That will look for the variable <code>$types</code>. To get around this use <code>echo "The {$type}s are"</code> You can put the left brace before or after the dollar sign. Take a look at <a href="https://www.php.net/manual/en/language.types.string.php#language.types.string.parsing" rel="noreferrer">string parsing</a> to see how to use array variables and such.</li> <li><a href="https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc" rel="noreferrer"><strong>Heredoc</strong></a> string syntax works like double quoted strings. It starts with <code>&lt;&lt;&lt;</code>. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. You don't need to escape quotes in this syntax. </li> <li><a href="https://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc" rel="noreferrer"><strong>Nowdoc</strong></a> (since PHP 5.3.0) string syntax works essentially like single quoted strings. The difference is that not even single quotes or backslashes have to be escaped. A nowdoc is identified with the same <code>&lt;&lt;&lt;</code> sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <code>&lt;&lt;&lt;'EOT'</code>. <strong>No parsing is done in nowdoc.</strong></li> </ol> <p><strong>Notes:</strong> Single quotes inside of single quotes and double quotes inside of double quotes must be escaped:</p> <pre><code>$string = 'He said "What\'s up?"'; $string = "He said \"What's up?\""; </code></pre> <p><strong>Speed:</strong><br> I would not put too much weight on single quotes being faster than double quotes. They probably are faster in certain situations. Here's an article <a href="https://web.archive.org/web/20170703004051/https://www.phplens.com/lens/php-book/optimizing-debugging-php.php" rel="noreferrer">explaining one manner in which single and double quotes are essentially equally fast since PHP 4.3</a> (<code>Useless Optimizations</code> toward the bottom, section <code>C</code>). Also, this <a href="https://www.phpbench.com/" rel="noreferrer"><strong>benchmarks page</strong></a> has a single vs double quote comparison. Most of the comparisons are the same. There is one comparison where double quotes are slower than single quotes.</p>
{ "question_id": 3446216, "question_date": "2010-08-10T05:12:56.133Z", "question_score": 897, "tags": "php|string|syntax", "answer_id": 3446286, "answer_date": "2010-08-10T05:28:33.987Z", "answer_score": 1199 }
Please answer the following Stack Overflow question: Title: How do I copy an object in Java? <p>Consider the code below:</p> <pre><code>DummyBean dum = new DummyBean(); dum.setDummy("foo"); System.out.println(dum.getDummy()); // prints 'foo' DummyBean dumtwo = dum; System.out.println(dumtwo.getDummy()); // prints 'foo' dum.setDummy("bar"); System.out.println(dumtwo.getDummy()); // prints 'bar' but it should print 'foo' </code></pre> <p>So, I want to copy the <code>dum</code> to <code>dumtwo</code> and change <code>dum</code> without affecting the <code>dumtwo</code>. But the code above is not doing that. When I change something in <code>dum</code>, the same change is happening in <code>dumtwo</code> also.</p> <p>I guess, when I say <code>dumtwo = dum</code>, Java copies the <strong>reference only</strong>. So, is there any way to create a fresh copy of <code>dum</code> and assign it to <code>dumtwo</code>?</p>
<p>Create a copy constructor:</p> <pre><code>class DummyBean { private String dummy; public DummyBean(DummyBean another) { this.dummy = another.dummy; // you can access } } </code></pre> <p>Every object has also a clone method which can be used to copy the object, but don't use it. It's way too easy to create a class and do improper clone method. If you are going to do that, read at least what Joshua Bloch has to say about it in <em><a href="http://books.google.com/books?id=ka2VUBqHiWkC&amp;pg=PA55&amp;lpg=PA55&amp;dq=effective+java+clone&amp;source=bl&amp;ots=yXGhLnv4O4&amp;sig=zvEip5tp5KGgwqO1sCWgtGyJ1Ns&amp;hl=en&amp;ei=CYANSqygK8jktgfM-JGcCA&amp;sa=X&amp;oi=book_result&amp;ct=result&amp;resnum=3#PPA54,M1" rel="noreferrer">Effective Java</a></em>.</p>
{ "question_id": 869033, "question_date": "2009-05-15T14:30:26.943Z", "question_score": 896, "tags": "java|object|copy|clone", "answer_id": 869078, "answer_date": "2009-05-15T14:35:42.483Z", "answer_score": 687 }
Please answer the following Stack Overflow question: Title: Multiline editing in Visual Studio Code <p>Is it possible to enable multiline editing like in <a href="http://en.wikipedia.org/wiki/Sublime_Text" rel="noreferrer">Sublime Text</a>?</p> <p>For example, press <kbd>Ctrl</kbd> to place additional cursor carets and being able to write/delete on multiple places in the document at one time.</p>
<p>On Windows, you hold <kbd>Ctrl</kbd>+<kbd>Alt</kbd> while pressing the up <kbd>↑</kbd> or down <kbd>↓</kbd> arrow keys to add cursors.</p> <p>Mac: <kbd>⌥ Opt</kbd>+<kbd>⌘ Cmd</kbd>+<kbd>↑</kbd>/<kbd>↓</kbd></p> <p>Linux: <kbd>Shift</kbd>+<kbd>Alt</kbd>+<kbd>↑</kbd>/<kbd>↓</kbd></p> <blockquote> <p>Note that third-party software may interfere with these shortcuts, preventing them from working as intended (particularly Intel's HD Graphics software on Windows; see comments for more details).</p> <p>If you experience this issue, you can either disable the Intel/other software hotkeys, or modify the VS Code shortcuts (described below).</p> </blockquote> <p>Press <kbd>Esc</kbd> to reset to a single cursor.</p> <p><img src="https://i.stack.imgur.com/yWIwr.gif" alt="Multiline cursors in Visual Studio Code" /></p> <p>Or, <a href="https://stackoverflow.com/a/30047339">as Isidor Nikolic points out</a>, you can hold <kbd>Alt</kbd> and left click to place cursors arbitrarily.</p> <p><img src="https://i.stack.imgur.com/MayEK.gif" alt="Arbitrarily placed multiline cursors in Visual Studio Code" /></p> <p>You can view and edit keyboard shortcuts via:</p> <blockquote> <p>File → Preferences → Keyboard Shortcuts</p> </blockquote> <p>Documentation:</p> <p><a href="https://code.visualstudio.com/docs/customization/keybindings" rel="noreferrer">https://code.visualstudio.com/docs/customization/keybindings</a></p> <p>Official VS Code Keyboard shortcut cheat sheets:</p> <p><a href="https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf" rel="noreferrer">https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf</a><br /> <a href="https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf" rel="noreferrer">https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf</a><br /> <a href="https://code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf" rel="noreferrer">https://code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf</a></p>
{ "question_id": 30037808, "question_date": "2015-05-04T18:55:14.317Z", "question_score": 896, "tags": "visual-studio-code", "answer_id": 30039968, "answer_date": "2015-05-04T21:05:52.380Z", "answer_score": 1578 }
Please answer the following Stack Overflow question: Title: List comprehension vs map <p>Is there a reason to prefer using <code>map()</code> over list comprehension or vice versa? Is either of them generally more efficient or considered generally more pythonic than the other?</p>
<p><code>map</code> may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.</p> <p>An example of the tiny speed advantage of map when using exactly the same function:</p> <pre><code>$ python -m timeit -s'xs=range(10)' 'map(hex, xs)' 100000 loops, best of 3: 4.86 usec per loop $ python -m timeit -s'xs=range(10)' '[hex(x) for x in xs]' 100000 loops, best of 3: 5.58 usec per loop </code></pre> <p>An example of how performance comparison gets completely reversed when map needs a lambda:</p> <pre><code>$ python -m timeit -s'xs=range(10)' 'map(lambda x: x+2, xs)' 100000 loops, best of 3: 4.24 usec per loop $ python -m timeit -s'xs=range(10)' '[x+2 for x in xs]' 100000 loops, best of 3: 2.32 usec per loop </code></pre>
{ "question_id": 1247486, "question_date": "2009-08-07T23:43:31.943Z", "question_score": 896, "tags": "python|list-comprehension|map-function", "answer_id": 1247490, "answer_date": "2009-08-07T23:45:23.420Z", "answer_score": 805 }
Please answer the following Stack Overflow question: Title: Metadata file '.dll' could not be found <p>I am working on a WPF, C# 3.0 project, and I get this error:</p> <pre><code>Error 1 Metadata file 'WORK=- \Tools\VersionManagementSystem\BusinessLogicLayer\bin\Debug \BusinessLogicLayer.dll' could not be found C:\-=WORK=- \Tools \VersionManagementSystem\VersionManagementSystem\CSC VersionManagementSystem </code></pre> <p>This is how I reference my usercontrols:</p> <pre><code>xmlns:vms="clr-namespace:VersionManagementSystem" &lt;vms:SignOffProjectListing Margin="5"/&gt; </code></pre> <p>It happens after every failed build. The only way I can get the solution to compile is to comment out all my user controls and re-build the project, and then I uncomment the usercontrols and everything is fine.</p> <p>I have checked build orders and dependencies configurations.</p> <p>As you can see, it seems to have truncated the DLL file's absolute path... I have read that there is a bug with the length. Is this a possible problem?</p> <p>It's very annoying and having to comment, build, and uncomment, the build is becoming extremely tiresome.</p>
<p>I just had the same problem. Visual Studio isn't building the project that's being referenced.</p> <h2>Written Instructions:</h2> <ol> <li>Right click on the solution and click Properties.</li> <li>Click Configuration on the left.</li> <li>Make sure the check box under "Build" for the project it can't find is checked. If it is already checked, uncheck, hit apply and check the boxes again.</li> <li>(Optional) You had to do it for both Release and Debug modes on the solution properties.</li> </ol> <h2>Screen capture Instructions:</h2> <ul> <li>They say a picture is worth a thousand words. Click on the GIF to zoom in, and hopefully it will be easy to follow:</li> </ul> <p><a href="https://i.stack.imgur.com/F3Cs3.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/F3Cs3.gif" alt="Gif Instructions"></a></p>
{ "question_id": 1421862, "question_date": "2009-09-14T14:19:59.547Z", "question_score": 895, "tags": "c#|.net|wpf|visual-studio-2008|c#-3.0", "answer_id": 17723774, "answer_date": "2013-07-18T12:42:37.887Z", "answer_score": 1115 }
Please answer the following Stack Overflow question: Title: How do you count the lines of code in a Visual Studio solution? <p>Is it possible to find the number of lines of code in an entire solution? I've heard of <a href="http://www.mztools.com/index.aspx" rel="noreferrer">MZ-Tools</a>, but is there an open source equivalent?</p>
<p><a href="https://docs.microsoft.com/en-us/visualstudio/code-quality/code-metrics-values" rel="noreferrer">Visual Studio has built-in code metrics</a>, including lines of code:</p> <blockquote> <p>Analyze → Calculate Code Metrics</p> </blockquote>
{ "question_id": 1244729, "question_date": "2009-08-07T13:35:47.287Z", "question_score": 895, "tags": "visual-studio", "answer_id": 5149884, "answer_date": "2011-03-01T02:25:09.483Z", "answer_score": 674 }
Please answer the following Stack Overflow question: Title: Ajax request returns 200 OK, but an error event is fired instead of success <p>I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns <strong>200 OK</strong>, but <strong>jQuery</strong> executes the error event.<br> I tried a lot of things, but I could not figure out the problem. I am adding my code below:</p> <h3>jQuery Code</h3> <pre><code>var row = "1"; var json = "{'TwitterId':'" + row + "'}"; $.ajax({ type: 'POST', url: 'Jqueryoperation.aspx?Operation=DeleteRow', contentType: 'application/json; charset=utf-8', data: json, dataType: 'json', cache: false, success: AjaxSucceeded, error: AjaxFailed }); function AjaxSucceeded(result) { alert("hello"); alert(result.d); } function AjaxFailed(result) { alert("hello1"); alert(result.status + ' ' + result.statusText); } </code></pre> <h3>C# code for <code>JqueryOpeartion.aspx</code></h3> <pre><code>protected void Page_Load(object sender, EventArgs e) { test(); } private void test() { Response.Write("&lt;script language='javascript'&gt;alert('Record Deleted');&lt;/script&gt;"); } </code></pre> <p>I need the <code>("Record deleted")</code> string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?</p>
<p><a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer"><code>jQuery.ajax</code></a> attempts to convert the response body depending on the specified <code>dataType</code> parameter or the <code>Content-Type</code> header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.</p> <hr> <p>Your AJAX code contains:</p> <pre><code>dataType: "json" </code></pre> <p>In this case jQuery:</p> <blockquote> <p>Evaluates the response as JSON and returns a JavaScript object. […] The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. […] an empty response is also rejected; the server should return a response of null or {} instead.</p> </blockquote> <p>Your server-side code returns HTML snippet with <code>200 OK</code> status. jQuery was expecting valid JSON and therefore fires the error callback complaining about <code>parseerror</code>.</p> <p>The solution is to remove the <code>dataType</code> parameter from your jQuery code and make the server-side code return:</p> <pre><code>Content-Type: application/javascript alert("Record Deleted"); </code></pre> <p>But I would rather suggest returning a JSON response and display the message inside the success callback:</p> <pre><code>Content-Type: application/json {"message": "Record deleted"} </code></pre>
{ "question_id": 6186770, "question_date": "2011-05-31T11:17:38.467Z", "question_score": 895, "tags": "javascript|jquery|asp.net|ajax|json", "answer_id": 6186905, "answer_date": "2011-05-31T11:31:53.367Z", "answer_score": 1226 }
Please answer the following Stack Overflow question: Title: Should I add the Visual Studio .suo and .user files to source control? <p>Visual Studio solutions contain two types of hidden user files. One is the solution <code>.suo</code> file which is a binary file. The other is the project <code>.user</code> file which is a text file. Exactly what data do these files contain?</p> <p>I've also been wondering whether I should add these files to source control (Subversion in my case). If I don't add these files and another developer checks out the solution, will Visual Studio automatically create new user files?</p>
<p>These files contain user preference configurations that are in general specific to your machine, so it's better not to put it in SCM. Also, VS will change it almost every time you execute it, so it will always be marked by the SCM as 'changed'. I don't include either, I'm in a project using VS for 2 years and had no problems doing that. The only minor annoyance is that the debug parameters (execution path, deployment target, etc.) are stored in one of those files (don't know which), so if you have a standard for them you won't be able to 'publish' it via SCM for other developers to have the entire development environment 'ready to use'.</p>
{ "question_id": 72298, "question_date": "2008-09-16T13:40:42.437Z", "question_score": 895, "tags": "visual-studio|version-control", "answer_id": 72662, "answer_date": "2008-09-16T14:08:40.497Z", "answer_score": 705 }
Please answer the following Stack Overflow question: Title: Flexbox: center horizontally and vertically <p>How to center div horizontally, and vertically within the container using flexbox. In below example, I want each number below each other (in rows), which are centered horizontally.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.flex-container { padding: 0; margin: 0; list-style: none; display: flex; align-items: center; justify-content: center; } row { width: 100%; } .flex-item { background: tomato; padding: 5px; width: 200px; height: 150px; margin: 10px; line-height: 150px; color: white; font-weight: bold; font-size: 3em; text-align: center; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="flex-container"&gt; &lt;div class="row"&gt; &lt;span class="flex-item"&gt;1&lt;/span&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;span class="flex-item"&gt;2&lt;/span&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;span class="flex-item"&gt;3&lt;/span&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;span class="flex-item"&gt;4&lt;/span&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p><a href="http://codepen.io/anon/pen/zLxBo" rel="noreferrer">http://codepen.io/anon/pen/zLxBo</a></p>
<p>I think you want something like the following.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body { height: 100%; } body { margin: 0; } .flex-container { height: 100%; padding: 0; margin: 0; display: flex; align-items: center; justify-content: center; } .row { width: auto; border: 1px solid blue; } .flex-item { background-color: tomato; padding: 5px; width: 20px; height: 20px; margin: 10px; line-height: 20px; color: white; font-weight: bold; font-size: 2em; text-align: center; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="flex-container"&gt; &lt;div class="row"&gt; &lt;div class="flex-item"&gt;1&lt;/div&gt; &lt;div class="flex-item"&gt;2&lt;/div&gt; &lt;div class="flex-item"&gt;3&lt;/div&gt; &lt;div class="flex-item"&gt;4&lt;/div&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>See demo at: <a href="http://jsfiddle.net/audetwebdesign/tFscL/" rel="noreferrer">http://jsfiddle.net/audetwebdesign/tFscL/</a></p> <p>Your <code>.flex-item</code> elements should be block level (<code>div</code> instead of <code>span</code>) if you want the height and top/bottom padding to work properly.</p> <p>Also, on <code>.row</code>, set the width to <code>auto</code> instead of <code>100%</code>.</p> <p>Your <code>.flex-container</code> properties are fine.</p> <p>If you want the <code>.row</code> to be centered vertically in the view port, assign 100% height to <code>html</code> and <code>body</code>, and also zero out the <code>body</code> margins.</p> <p>Note that <code>.flex-container</code> needs a height to see the vertical alignment effect, otherwise, the container computes the minimum height needed to enclose the content, which is less than the view port height in this example.</p> <p><strong>Footnote:</strong><br /> The <code>flex-flow</code>, <code>flex-direction</code>, <code>flex-wrap</code> properties could have made this design easier to implement. I think that the <code>.row</code> container is not needed unless you want to add some styling around the elements (background image, borders and so on).</p> <p>A useful resource is: <a href="http://demo.agektmr.com/flexbox/" rel="noreferrer">http://demo.agektmr.com/flexbox/</a></p>
{ "question_id": 19026884, "question_date": "2013-09-26T11:22:41.580Z", "question_score": 894, "tags": "html|css|flexbox", "answer_id": 19027949, "answer_date": "2013-09-26T12:13:04.213Z", "answer_score": 969 }
Please answer the following Stack Overflow question: Title: Get changes from master into branch in Git <p>In my repository I have a branch called <code>aq</code> which I'm working on.</p> <p>I then committed new work and bugs in <code>master</code>. </p> <p>What is the best way to get those commits into the <code>aq</code> branch? Create another new branch out of <code>master</code> and merge it with <code>aq</code>?</p>
<p>Check out the <code>aq</code> branch, and rebase from <code>master</code>.</p> <pre><code>git checkout aq git rebase master </code></pre>
{ "question_id": 5340724, "question_date": "2011-03-17T14:51:32.313Z", "question_score": 894, "tags": "git|version-control|git-merge", "answer_id": 5340773, "answer_date": "2011-03-17T14:54:41.537Z", "answer_score": 1017 }
Please answer the following Stack Overflow question: Title: Difference between malloc and calloc? <p>What is the difference between doing:</p> <pre><code>ptr = malloc (MAXELEMS * sizeof(char *)); </code></pre> <p>or:</p> <pre><code>ptr = calloc (MAXELEMS, sizeof(char*)); </code></pre> <p>When is it a good idea to use calloc over malloc or vice versa?</p>
<p><code>calloc()</code> gives you a zero-initialized buffer, while <code>malloc()</code> leaves the memory uninitialized.</p> <p>For large allocations, most <code>calloc</code> implementations under mainstream OSes will get known-zeroed pages from the OS (e.g. via POSIX <code>mmap(MAP_ANONYMOUS)</code> or Windows <code>VirtualAlloc</code>) so it doesn't need to write them in user-space. This is how normal <code>malloc</code> gets more pages from the OS as well; <code>calloc</code> just takes advantage of the OS's guarantee.</p> <p>This means <code>calloc</code> memory can still be &quot;clean&quot; and lazily-allocated, and copy-on-write mapped to a system-wide shared physical page of zeros. (Assuming a system with virtual memory.) The effects are visible with <a href="https://stackoverflow.com/questions/57125253/why-is-iterating-though-stdvector-faster-than-iterating-though-stdarray/57130924#57130924">performance experiments on Linux</a>, for example.</p> <p>Some compilers even can optimize malloc + memset(0) into calloc for you, but it's best to just use calloc in the source if you want zeroed memory. (Or if you were trying to pre-fault it to avoid page faults later, that optimization will defeat your attempt.)</p> <p>If you aren't going to ever read memory before writing it, use <code>malloc</code> so it can (potentially) give you dirty memory from its internal free list instead of getting new pages from the OS. (Or instead of zeroing a block of memory on the free list for a small allocation).</p> <hr /> <p>Embedded implementations of <code>calloc</code> may leave it up to <code>calloc</code> itself to zero memory if there's no OS, or it's not a fancy multi-user OS that zeros pages to stop information leaks between processes.</p> <p>On embedded Linux, malloc could <a href="http://man7.org/linux/man-pages/man2/mmap.2.html" rel="noreferrer"><code>mmap(MAP_UNINITIALIZED|MAP_ANONYMOUS)</code></a>, which is only enabled for some embedded kernels because it's insecure on a multi-user system.</p>
{ "question_id": 1538420, "question_date": "2009-10-08T15:04:33.983Z", "question_score": 894, "tags": "c|malloc|calloc", "answer_id": 1538427, "answer_date": "2009-10-08T15:05:25.260Z", "answer_score": 961 }
Please answer the following Stack Overflow question: Title: What's the difference between <b> and <strong>, <i> and <em>? <p>What's the difference between <code>&lt;b&gt;</code> and <code>&lt;strong&gt;</code>, <code>&lt;i&gt;</code> and <code>&lt;em&gt;</code> in HTML/XHTML? When should you use each?</p>
<p>They have the <strong>same effect on normal web browser rendering engines</strong>, but there is a <strong>fundamental difference</strong> between them.</p> <p>As the author writes in <a href="https://web.archive.org/web/20091124170143/http://lists.evolt.org/archive/Week-of-Mon-20010521/032901.html" rel="noreferrer">a discussion list post</a>:</p> <p>Think of three different situations:</p> <ul> <li>web browsers</li> <li>blind people</li> <li>mobile phones</li> </ul> <p>"Bold" is a style - when you say <em>"bold a word"</em>, people basically know that it means to add more, let's say "ink", around the letters until they stand out more amongst the rest of the letters.</p> <p>That, unfortunately, means nothing to a blind person. On mobile phones and other PDAs, text is already bold because screen resolution is very small. You can't bold a bold without screwing something up.</p> <p><strong><code>&lt;b&gt;</code> is a style</strong> - we know what "bold" is supposed to look like.</p> <p><strong><code>&lt;strong&gt;</code></strong> however <strong>is an indication of how something should be understood</strong>. "Strong" could (and often does) mean "bold" in a browser, but it could also mean a lower tone for a speaking program like Jaws (for blind people) or be represented by an underline (since you can't bold a bold) on a Palm Pilot.</p> <p>HTML was never meant to be about styles. Do <a href="http://www.google.com/search?q=%22Tim+Berners+Lee%22+%22Semantic+Web%22&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:de:official&amp;client=firefox-a" rel="noreferrer">some searches</a> for <a href="http://en.wikipedia.org/wiki/Tim_Berners-Lee" rel="noreferrer"><em>"Tim Berners-Lee"</em></a> and <em>"the semantic web."</em> <code>&lt;strong&gt;</code> is semantic&mdash;it describes the text it surrounds (e.g., <em>"this text should be stronger than the rest of the text you've displayed"</em>) as opposed to describing <em>how</em> the text it surrounds <em>should be displayed</em> (e.g., <em>"this text should be bold"</em>).</p>
{ "question_id": 271743, "question_date": "2008-11-07T10:56:08.463Z", "question_score": 894, "tags": "html|xhtml", "answer_id": 271776, "answer_date": "2008-11-07T11:07:32.323Z", "answer_score": 1160 }
Please answer the following Stack Overflow question: Title: Difference between npx and npm? <p>I have just started learning React, and Facebook helps in simplifying the initial setup by providing the <a href="https://github.com/facebook/create-react-app" rel="noreferrer">following ready-made project</a>. </p> <p>If I have to install the skeleton project I have to type <code>npx create-react-app my-app</code> in command-line.</p> <p>I was wondering why does the Facebook in Github have <code>npx create-react-app my-app</code> rather than <code>npm create-react-app my-app</code>?</p>
<h2><a href="https://blog.npmjs.org/post/162869356040/introducing-npx-an-npm-package-runner" rel="noreferrer">Introducing npx: an npm package runner</a></h2> <h3><code>NPM</code> - <em>Manages</em> packages <em>but</em> doesn't make life easy <em>executing</em> any.<br><code>NPX</code> - A tool for <em>executing</em> Node packages.</h3> <blockquote> <p><code>NPX</code> comes bundled with <code>NPM</code> version <code>5.2+</code> <br></p> </blockquote> <p><code>NPM</code> by itself does not simply run any package. It doesn't run any package as a matter of fact. If you want to run a package using NPM, you must specify that package in your <code>package.json</code> file.</p> <p>When executables are installed via NPM packages, NPM links to them:</p> <ol> <li><em>local</em> installs have &quot;links&quot; created at <code>./node_modules/.bin/</code> directory.</li> <li><em>global</em> installs have &quot;links&quot; created from the global <code>bin/</code> directory (e.g. <code>/usr/local/bin</code>) on Linux or at <code>%AppData%/npm</code> on Windows.</li> </ol> <p><a href="https://docs.npmjs.com/files/folders#executables" rel="noreferrer"><strong>Documentation you should read</strong></a></p> <hr /> <h1>NPM:</h1> <p>One might install a package locally on a certain project:</p> <pre><code>npm install some-package </code></pre> <p>Now let's say you want NodeJS to execute that package from the command line:</p> <pre><code>$ some-package </code></pre> <p>The above will <strong>fail</strong>. Only <strong>globally installed</strong> packages can be executed by typing their name <em>only</em>.</p> <p>To fix this, and have it run, you must type the local path:</p> <pre><code>$ ./node_modules/.bin/some-package </code></pre> <p>You can technically run a locally installed package by editing your <code>packages.json</code> file and adding that package in the <code>scripts</code> section:</p> <pre><code>{ &quot;name&quot;: &quot;whatever&quot;, &quot;version&quot;: &quot;1.0.0&quot;, &quot;scripts&quot;: { &quot;some-package&quot;: &quot;some-package&quot; } } </code></pre> <p>Then run the script using <a href="https://docs.npmjs.com/cli/run-script" rel="noreferrer"><code>npm run-script</code></a> (or <code>npm run</code>):</p> <pre><code>npm run some-package </code></pre> <hr /> <h1>NPX:</h1> <p><code>npx</code> will check whether <code>&lt;command&gt;</code> exists in <code>$PATH</code>, or in the local project binaries, and execute it. So, for the above example, if you wish to execute the locally-installed package <code>some-package</code> all you need to do is type:</p> <pre><code>npx some-package </code></pre> <p>Another <strong>major</strong> advantage of <code>npx</code> is the ability to execute a package which wasn't previously installed:</p> <pre><code>$ npx create-react-app my-app </code></pre> <p>The above example will generate a <code>react</code> app boilerplate <em>within</em> the path the command had run in, and ensures that you always use the latest version of a generator or build tool without having to upgrade each time you’re about to use it.</p> <hr /> <h3>Use-Case Example:</h3> <p><code>npx</code> command may be helpful in the <code>script</code> section of a <code>package.json</code> file, when it is unwanted to define a dependency which might not be commonly used or any other reason:</p> <pre class="lang-js prettyprint-override"><code>&quot;scripts&quot;: { &quot;start&quot;: &quot;npx [email protected]&quot;, &quot;serve&quot;: &quot;npx http-server&quot; } </code></pre> <p>Call with: <code>npm run serve</code></p> <hr /> <h3>Related questions:</h3> <ol> <li><a href="https://stackoverflow.com/q/9679932/104380">How to use package installed locally in node_modules?</a></li> <li><a href="https://stackoverflow.com/q/18033754/104380">NPM: how to source ./node_modules/.bin folder?</a></li> <li><a href="https://stackoverflow.com/q/32964900/104380">How do you run a js file using npm scripts?</a></li> </ol>
{ "question_id": 50605219, "question_date": "2018-05-30T12:51:54.103Z", "question_score": 894, "tags": "javascript|reactjs|npm|npx", "answer_id": 52018825, "answer_date": "2018-08-25T15:43:15.070Z", "answer_score": 1063 }
Please answer the following Stack Overflow question: Title: What does it mean to "program to an interface"? <p>I have seen this mentioned a few times and I am not clear on what it means. When and why would you do this? </p> <p>I know what interfaces do, but the fact I am not clear on this makes me think I am missing out on using them correctly. </p> <p>Is it just so if you were to do:</p> <pre><code>IInterface classRef = new ObjectWhatever() </code></pre> <p>You could use any class that implements <code>IInterface</code>? When would you need to do that? The only thing I can think of is if you have a method and you are unsure of what object will be passed except for it implementing <code>IInterface</code>. I cannot think how often you would need to do that. </p> <p>Also, how could you write a method that takes in an object that implements an interface? Is that possible?</p>
<p>There are some wonderful answers on here to this questions that get into all sorts of great detail about interfaces and loosely coupling code, inversion of control and so on. There are some fairly heady discussions, so I'd like to take the opportunity to break things down a bit for understanding why an interface is useful.</p> <p>When I first started getting exposed to interfaces, I too was confused about their relevance. I didn't understand why you needed them. If we're using a language like Java or C#, we already have inheritance and I viewed interfaces as a <em>weaker</em> form of inheritance and thought, "why bother?" In a sense I was right, you can think of interfaces as sort of a weak form of inheritance, but beyond that I finally understood their use as a language construct by thinking of them as a means of classifying common traits or behaviors that were exhibited by potentially many non-related classes of objects.</p> <p>For example -- say you have a SIM game and have the following classes:</p> <pre class="lang-java prettyprint-override"><code>class HouseFly inherits Insect { void FlyAroundYourHead(){} void LandOnThings(){} } class Telemarketer inherits Person { void CallDuringDinner(){} void ContinueTalkingWhenYouSayNo(){} } </code></pre> <p>Clearly, these two objects have nothing in common in terms of direct inheritance. But, you could say they are both annoying. </p> <p>Let's say our game needs to have some sort of random <em>thing</em> that annoys the game player when they eat dinner. This could be a <code>HouseFly</code> or a <code>Telemarketer</code> or both -- but how do you allow for both with a single function? And how do you ask each different type of object to "do their annoying thing" in the same way?</p> <p>The key to realize is that both a <code>Telemarketer</code> and <code>HouseFly</code> share a common loosely interpreted behavior even though they are nothing alike in terms of modeling them. So, let's make an interface that both can implement:</p> <pre class="lang-java prettyprint-override"><code>interface IPest { void BeAnnoying(); } class HouseFly inherits Insect implements IPest { void FlyAroundYourHead(){} void LandOnThings(){} void BeAnnoying() { FlyAroundYourHead(); LandOnThings(); } } class Telemarketer inherits Person implements IPest { void CallDuringDinner(){} void ContinueTalkingWhenYouSayNo(){} void BeAnnoying() { CallDuringDinner(); ContinueTalkingWhenYouSayNo(); } } </code></pre> <p>We now have two classes that can each be annoying in their own way. And they do not need to derive from the same base class and share common inherent characteristics -- they simply need to satisfy the contract of <code>IPest</code> -- that contract is simple. You just have to <code>BeAnnoying</code>. In this regard, we can model the following:</p> <pre class="lang-java prettyprint-override"><code>class DiningRoom { DiningRoom(Person[] diningPeople, IPest[] pests) { ... } void ServeDinner() { when diningPeople are eating, foreach pest in pests pest.BeAnnoying(); } } </code></pre> <p>Here we have a dining room that accepts a number of diners and a number of pests -- note the use of the interface. This means that in our little world, a member of the <code>pests</code> array could actually be a <code>Telemarketer</code> object or a <code>HouseFly</code> object.</p> <p>The <code>ServeDinner</code> method is called when dinner is served and our people in the dining room are supposed to eat. In our little game, that's when our pests do their work -- each pest is instructed to be annoying by way of the <code>IPest</code> interface. In this way, we can easily have both <code>Telemarketers</code> and <code>HouseFlys</code> be annoying in each of their own ways -- we care only that we have something in the <code>DiningRoom</code> object that is a pest, we don't really care what it is and they could have nothing in common with other. </p> <p>This very contrived pseudo-code example (that dragged on a lot longer than I anticipated) is simply meant to illustrate the kind of thing that finally turned the light on for me in terms of when we might use an interface. I apologize in advance for the silliness of the example, but hope that it helps in your understanding. And, to be sure, the other posted answers you've received here really cover the gamut of the use of interfaces today in design patterns and development methodologies. </p>
{ "question_id": 383947, "question_date": "2008-12-21T00:48:59.113Z", "question_score": 894, "tags": "language-agnostic|oop|interface", "answer_id": 384067, "answer_date": "2008-12-21T03:43:06.533Z", "answer_score": 1789 }
Please answer the following Stack Overflow question: Title: Why use apparently meaningless do-while and if-else statements in macros? <p>In many C/C++ macros I'm seeing the code of the macro wrapped in what seems like a meaningless <code>do while</code> loop. Here are examples.</p> <pre><code>#define FOO(X) do { f(X); g(X); } while (0) #define FOO(X) if (1) { f(X); g(X); } else </code></pre> <p>I can't see what the <code>do while</code> is doing. Why not just write this without it?</p> <pre><code>#define FOO(X) f(X); g(X) </code></pre>
<p>The <code>do ... while</code> and <code>if ... else</code> are there to make it so that a semicolon after your macro always means the same thing. Let's say you had something like your second macro.</p> <pre><code>#define BAR(X) f(x); g(x) </code></pre> <p>Now if you were to use <code>BAR(X);</code> in an <code>if ... else</code> statement, where the bodies of the if statement were not wrapped in curly brackets, you'd get a bad surprise.</p> <pre><code>if (corge) BAR(corge); else gralt(); </code></pre> <p>The above code would expand into</p> <pre><code>if (corge) f(corge); g(corge); else gralt(); </code></pre> <p>which is syntactically incorrect, as the else is no longer associated with the if. It doesn't help to wrap things in curly braces within the macro, because a semicolon after the braces is syntactically incorrect.</p> <pre><code>if (corge) {f(corge); g(corge);}; else gralt(); </code></pre> <p>There are two ways of fixing the problem. The first is to use a comma to sequence statements within the macro without robbing it of its ability to act like an expression.</p> <pre><code>#define BAR(X) f(X), g(X) </code></pre> <p>The above version of bar <code>BAR</code> expands the above code into what follows, which is syntactically correct.</p> <pre><code>if (corge) f(corge), g(corge); else gralt(); </code></pre> <p>This doesn't work if instead of <code>f(X)</code> you have a more complicated body of code that needs to go in its own block, say for example to declare local variables. In the most general case the solution is to use something like <code>do ... while</code> to cause the macro to be a single statement that takes a semicolon without confusion.</p> <pre><code>#define BAR(X) do { \ int i = f(X); \ if (i &gt; 4) g(i); \ } while (0) </code></pre> <p>You don't have to use <code>do ... while</code>, you could cook up something with <code>if ... else</code> as well, although when <code>if ... else</code> expands inside of an <code>if ... else</code> it leads to a "<a href="http://en.wikipedia.org/wiki/Dangling_else" rel="noreferrer">dangling else</a>", which could make an existing dangling else problem even harder to find, as in the following code.</p> <pre><code>if (corge) if (1) { f(corge); g(corge); } else; else gralt(); </code></pre> <p>The point is to use up the semicolon in contexts where a dangling semicolon is erroneous. Of course, it could (and probably should) be argued at this point that it would be better to declare <code>BAR</code> as an actual function, not a macro.</p> <p>In summary, the <code>do ... while</code> is there to work around the shortcomings of the C preprocessor. When those C style guides tell you to lay off the C preprocessor, this is the kind of thing they're worried about.</p>
{ "question_id": 154136, "question_date": "2008-09-30T17:36:24.213Z", "question_score": 894, "tags": "c++|c|c-preprocessor|c++-faq", "answer_id": 154138, "answer_date": "2008-09-30T17:36:35.693Z", "answer_score": 937 }
Please answer the following Stack Overflow question: Title: Is there a way to get the git root directory in one command? <p>Mercurial has a way of printing the root directory (that contains .hg) via</p> <pre><code>hg root </code></pre> <p>Is there something equivalent in git to get the directory that contains the .git directory?</p>
<p>Yes:</p> <pre><code>git rev-parse --show-toplevel </code></pre> <p>If you want to replicate the Mercurial command more directly, you can create an <a href="https://git-scm.com/book/en/v2/Git-Basics-Git-Aliases" rel="noreferrer">alias</a>:</p> <pre><code>git config --global alias.root 'rev-parse --show-toplevel' </code></pre> <p>and now <code>git root</code> will function just as <code>hg root</code>.</p> <hr /> <p><strong>Note</strong>: In a submodule this will display the root directory of the <em>submodule</em> and <strong>not</strong> the parent repository. If you are using Git &gt;=2.13 or above, there is a way that <a href="https://stackoverflow.com/a/958125/884640">submodules can show the superproject's root directory.</a> If your git is older than that, <a href="https://git-scm.com/docs/git-rev-parse#Documentation/git-rev-parse.txt---show-superproject-working-tree" rel="noreferrer">see this other answer.</a></p>
{ "question_id": 957928, "question_date": "2009-06-05T20:15:26.570Z", "question_score": 893, "tags": "git|version-control", "answer_id": 957978, "answer_date": "2009-06-05T20:29:12.690Z", "answer_score": 1493 }
Please answer the following Stack Overflow question: Title: Relation between CommonJS, AMD and RequireJS? <p>I'm still very confused about <strong>CommonJS, AMD</strong> and <strong>RequireJS</strong>, even after reading a lot.</p> <p>I know that <strong>CommonJS</strong> (formerly <strong>ServerJS</strong>) is a group for defining some <strong>JavaScript</strong> specifications (i.e. modules) when the language is used outside the browser. <strong>CommonJS</strong> modules specification has some implementation like <strong>Node.js</strong> or <strong>RingoJS</strong>, right?</p> <blockquote> <p>What's the relation between <strong>CommonJS</strong>, <strong>Asynchronous Module Definition</strong> (AMD) and <strong>RequireJS</strong>?</p> <p>Is <strong>RequireJS</strong> an implementation of the <strong>CommonJS</strong> module definition? If yes, what's <strong>AMD</strong> then?</p> </blockquote>
<p><strong>RequireJS</strong> implements the <strong>AMD</strong> API <a href="http://www.requirejs.org/docs/whyamd.html" rel="noreferrer">(source)</a>.</p> <p><strong>CommonJS</strong> is a way of defining modules with the help of an <code>exports</code> object, that defines the module contents. Simply put, a CommonJS implementation might work like this:</p> <pre><code>// someModule.js exports.doSomething = function() { return &quot;foo&quot;; }; //otherModule.js var someModule = require('someModule'); // in the vein of node exports.doSomethingElse = function() { return someModule.doSomething() + &quot;bar&quot;; }; </code></pre> <p>Basically, CommonJS specifies that you need to have a <code>require()</code> function to fetch dependencies, an <code>exports</code> variable to export module contents and a module identifier (which describes the location of the module in question in relation to this module) that is used to require the dependencies (<a href="http://wiki.commonjs.org/wiki/Modules/1.1.1" rel="noreferrer">source</a>). CommonJS has various implementations, including <strong>Node.js</strong>, which you mentioned.</p> <p>CommonJS was not particularly designed with browsers in mind, so it doesn't fit in the browser environment very well (*I really have no source for this--it just says so everywhere, including <a href="http://requirejs.org/docs/commonjs.html" rel="noreferrer">the RequireJS site.*</a>) Apparently, this has something to do with asynchronous loading, etc.</p> <p>On the other hand, RequireJS implements AMD, which is designed to suit the browser environment (<a href="https://github.com/amdjs/amdjs-api/wiki/AMD" rel="noreferrer">source</a>). Apparently, AMD started as a spinoff of the CommonJS Transport format and evolved into its own module definition API. Hence the similarities between the two. The new feature in AMD is the <code>define()</code> function that allows the module to declare its dependencies before being loaded. For example, the definition could be:</p> <pre><code>define('module/id/string', ['module', 'dependency', 'array'], function(module, factory function) { return ModuleContents; }); </code></pre> <p>So, CommonJS and AMD are <strong>JavaScript</strong> module definition APIs that have different implementations, but both come from the same origins.</p> <ul> <li><strong>AMD</strong> is more suited for the browser, because it supports asynchronous loading of module dependencies.</li> <li><strong>RequireJS</strong> is an implementation of <strong>AMD</strong>, while at the same time trying to keep the spirit of <strong>CommonJS</strong> (mainly in the module identifiers).</li> </ul> <p>To confuse you even more, RequireJS, while being an AMD implementation, offers a CommonJS wrapper so CommonJS modules can almost directly be imported for use with RequireJS.</p> <pre><code>define(function(require, exports, module) { var someModule = require('someModule'); // in the vein of node exports.doSomethingElse = function() { return someModule.doSomething() + &quot;bar&quot;; }; }); </code></pre>
{ "question_id": 16521471, "question_date": "2013-05-13T11:56:23.900Z", "question_score": 893, "tags": "javascript|module|requirejs|amd|commonjs", "answer_id": 16522990, "answer_date": "2013-05-13T13:14:08.313Z", "answer_score": 807 }
Please answer the following Stack Overflow question: Title: Writing a list to a file with Python, with newlines <p>How do I write a list to a file? <code>writelines()</code> doesn't insert newline characters, so I need to do:</p> <pre><code>f.writelines([f&quot;{line}\n&quot; for line in lines]) </code></pre>
<p>Use a loop:</p> <pre><code>with open('your_file.txt', 'w') as f: for line in lines: f.write(f&quot;{line}\n&quot;) </code></pre> <p>For Python &lt;3.6:</p> <pre><code>with open('your_file.txt', 'w') as f: for line in lines: f.write(&quot;%s\n&quot; % line) </code></pre> <p>For Python 2, one may also use:</p> <pre><code>with open('your_file.txt', 'w') as f: for line in lines: print &gt;&gt; f, line </code></pre> <p>If you're keen on a single function call, at least remove the square brackets <code>[]</code>, so that the strings to be printed get made one at a time (a genexp rather than a listcomp) -- no reason to take up all the memory required to materialize the whole list of strings.</p>
{ "question_id": 899103, "question_date": "2009-05-22T17:52:18.297Z", "question_score": 892, "tags": "python|file|list|file-io|newline", "answer_id": 899176, "answer_date": "2009-05-22T18:04:21.523Z", "answer_score": 1206 }
Please answer the following Stack Overflow question: Title: How do you get the logical xor of two variables in Python? <p>How do you get the <a href="http://en.wikipedia.org/wiki/Exclusive_or" rel="noreferrer">logical xor</a> of two variables in Python?</p> <p>For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):</p> <pre><code>str1 = raw_input("Enter string one:") str2 = raw_input("Enter string two:") if logical_xor(str1, str2): print "ok" else: print "bad" </code></pre> <p>The <code>^</code> operator seems to be bitwise, and not defined on all objects:</p> <pre><code>&gt;&gt;&gt; 1 ^ 1 0 &gt;&gt;&gt; 2 ^ 1 3 &gt;&gt;&gt; "abc" ^ "" Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: unsupported operand type(s) for ^: 'str' and 'str' </code></pre>
<p>If you're already normalizing the inputs to booleans, then != is xor.</p> <pre><code>bool(a) != bool(b) </code></pre>
{ "question_id": 432842, "question_date": "2009-01-11T12:34:43.917Z", "question_score": 892, "tags": "python|logical-operators", "answer_id": 433161, "answer_date": "2009-01-11T16:30:46.047Z", "answer_score": 1544 }
Please answer the following Stack Overflow question: Title: Merge development branch with master <p>I have two branches namely <code>master</code> and <code>development</code> in a GitHub Repository. I am doing all my development in development branch as shown.</p> <pre><code>git branch development git add * git commit -m "My initial commit message" git push -u origin development </code></pre> <p>Now I want to merge all the changes on the <code>development</code> branch into the <code>master</code>. My current approach is:</p> <pre><code>git checkout master git merge development git push -u origin master </code></pre> <p>Please let me know if the procedure I am following is correct.</p>
<p>I generally like to merge <code>master</code> into the <code>development</code> first so that if there are any conflicts, I can resolve in the <code>development</code> branch itself and my <code>master</code> remains clean.</p> <pre><code>(on branch development)$ git merge master (resolve any merge conflicts if there are any) git checkout master git merge development (there won't be any conflicts now) </code></pre> <p>There isn't much of a difference in the two approaches, but I have noticed sometimes that I don't want to merge the branch into <code>master</code> yet, after merging them, or that there is still more work to be done before these can be merged, so I tend to leave <code>master</code> untouched until final stuff.</p> <p>EDIT: From comments</p> <p>If you want to keep track of who did the merge and when, you can use <code>--no-ff</code> flag while merging to do so. This is generally useful only when merging <code>development</code> into the <code>master</code> (last step), because you might need to merge <code>master</code> into <code>development</code> (first step) multiple times in your workflow, and creating a commit node for these might not be very useful.</p> <pre><code>git merge --no-ff development </code></pre>
{ "question_id": 14168677, "question_date": "2013-01-05T04:45:48.277Z", "question_score": 892, "tags": "git|git-merge", "answer_id": 14168817, "answer_date": "2013-01-05T05:08:43.593Z", "answer_score": 1349 }
Please answer the following Stack Overflow question: Title: Finding duplicate values in MySQL <p>I have a table with a varchar column, and I would like to find all the records that have duplicate values in this column. What is the best query I can use to find the duplicates?</p>
<p>Do a <code>SELECT</code> with a <code>GROUP BY</code> clause. Let's say <em>name</em> is the column you want to find duplicates in:</p> <pre><code>SELECT name, COUNT(*) c FROM table GROUP BY name HAVING c &gt; 1; </code></pre> <p>This will return a result with the <em>name</em> value in the first column, and a count of how many times that value appears in the second.</p>
{ "question_id": 688549, "question_date": "2009-03-27T04:22:12.460Z", "question_score": 892, "tags": "mysql", "answer_id": 688551, "answer_date": "2009-03-27T04:24:08.990Z", "answer_score": 1727 }
Please answer the following Stack Overflow question: Title: How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#? <p>How do I convert struct <code>System.Byte</code> <code>byte[]</code> to a <code>System.IO.Stream</code> object in <strong>C#</strong>?</p>
<p>The easiest way to convert a byte array to a stream is using the <a href="http://msdn.microsoft.com/en-us/library/system.io.memorystream.aspx"><code>MemoryStream</code></a> class:</p> <pre><code>Stream stream = new MemoryStream(byteArray); </code></pre>
{ "question_id": 4736155, "question_date": "2011-01-19T14:08:58.357Z", "question_score": 892, "tags": "c#|.net|arrays|stream", "answer_id": 4769610, "answer_date": "2011-01-22T18:12:11.600Z", "answer_score": 1527 }
Please answer the following Stack Overflow question: Title: Sql Server 'Saving changes is not permitted' error ► Prevent saving changes that require table re-creation <p>When I create a table in SQL Server and save it, if I try to edit the table design, like change a column type from int to real, I get this error:</p> <blockquote> <p>Saving changes is not permitted. The change you have made requires the following table to be dropped and re-created. You have either made changes to a table that can't be recreated or enabled the option prevent saving changes that require the table to be re-created.</p> </blockquote> <p>Why do I have to re-create the table? I just want to change a data type from <code>smallint</code> to <code>real</code>.</p> <p>The table is empty, and I didn't use it until now.</p>
<p>From <a href="http://msdn.microsoft.com/en-us/library/bb895146.aspx" rel="noreferrer">Save (Not Permitted) Dialog Box on MSDN</a> :</p> <blockquote> <p>The <strong>Save</strong> (Not Permitted) dialog box warns you that saving changes is not permitted because the changes you have made require the listed tables to be dropped and re-created.</p> <p>The following actions might require a table to be re-created:</p> <ul> <li>Adding a new column to the middle of the table</li> <li>Dropping a column</li> <li>Changing column nullability</li> <li>Changing the order of the columns</li> <li>Changing the data type of a column <strong>&lt;&lt;&lt;&lt;</strong></li> </ul> <p>To change this option, on the <strong>Tools</strong> menu, click <strong>Options</strong>, expand <strong>Designers</strong>, and then click <strong>Table and Database Designers</strong>. Select or clear the <strong>Prevent saving changes that require the table to be re-created</strong> check box.</p> </blockquote> <p>See Also Colt Kwong Blog Entry:<br /> <a href="http://weblogs.asp.net/coltk/archive/2009/12/26/saving-changes-is-not-permitted-in-sql-2008-management-studio.aspx" rel="noreferrer">Saving changes is not permitted in SQL 2008 Management Studio</a></p>
{ "question_id": 6810425, "question_date": "2011-07-24T23:22:17.283Z", "question_score": 892, "tags": "sql-server-2008|save|ssms|menuitem", "answer_id": 6810442, "answer_date": "2011-07-24T23:26:43.400Z", "answer_score": 1665 }
Please answer the following Stack Overflow question: Title: How to check iOS version? <p>I want to check if the <code>iOS</code> version of the device is greater than <code>3.1.3</code> I tried things like:</p> <pre><code>[[UIDevice currentDevice].systemVersion floatValue] </code></pre> <p>but it does not work, I just want a:</p> <pre><code>if (version &gt; 3.1.3) { } </code></pre> <p>How can I achieve this?</p>
<h3>The quick answer …</h3> <p><br/> As of Swift 2.0, you can use <code>#available</code> in an <code>if</code> or <code>guard</code> to protect code that should only be run on certain systems.</p> <p><code>if #available(iOS 9, *) {}</code> <br/> <br/> <br/> In Objective-C, you need to check the system version and perform a comparison.</p> <p><code>[[NSProcessInfo processInfo] operatingSystemVersion]</code> in iOS 8 and above.</p> <p>As of Xcode 9:</p> <p><code>if (@available(iOS 9, *)) {}</code></p> <p><br/></p> <h2>The full answer …</h2> <p>In Objective-C, and Swift in rare cases, it's better to avoid relying on the operating system version as an indication of device or OS capabilities. There is usually a more reliable method of checking whether a particular feature or class is available.</p> <p><strong>Checking for the presence of APIs:</strong></p> <p>For example, you can check if <code>UIPopoverController</code> is available on the current device using <code>NSClassFromString</code>:</p> <pre><code>if (NSClassFromString(@"UIPopoverController")) { // Do something } </code></pre> <p>For weakly linked classes, it is safe to message the class, directly. Notably, this works for frameworks that aren't explicitly linked as "Required". For missing classes, the expression evaluates to nil, failing the condition:</p> <pre><code>if ([LAContext class]) { // Do something } </code></pre> <p>Some classes, like <code>CLLocationManager</code> and <code>UIDevice</code>, provide methods to check device capabilities:</p> <pre><code>if ([CLLocationManager headingAvailable]) { // Do something } </code></pre> <p><strong>Checking for the presence of symbols:</strong></p> <p>Very occasionally, you must check for the presence of a constant. This came up in iOS 8 with the introduction of <code>UIApplicationOpenSettingsURLString</code>, used to load Settings app via <code>-openURL:</code>. The value didn't exist prior to iOS 8. Passing nil to this API will crash, so you must take care to verify the existence of the constant first:</p> <pre><code>if (&amp;UIApplicationOpenSettingsURLString != NULL) { [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]; } </code></pre> <p><strong>Comparing against the operating system version:</strong></p> <p>Let's assume you're faced with the relatively rare need to check the operating system version. For projects targeting iOS 8 and above, <code>NSProcessInfo</code> includes a method for performing version comparisons with less chance of error:</p> <pre><code>- (BOOL)isOperatingSystemAtLeastVersion:(NSOperatingSystemVersion)version </code></pre> <p>Projects targeting older systems can use <code>systemVersion</code> on <code>UIDevice</code>. Apple uses it in their <a href="http://developer.apple.com/iphone/library/samplecode/GLSprite/Listings/Classes_EAGLView_m.html" rel="noreferrer">GLSprite</a> sample code.</p> <pre><code>// A system version of 3.1 or greater is required to use CADisplayLink. The NSTimer // class is used as fallback when it isn't available. NSString *reqSysVer = @"3.1"; NSString *currSysVer = [[UIDevice currentDevice] systemVersion]; if ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending) { displayLinkSupported = TRUE; } </code></pre> <p>If for whatever reason you decide that <code>systemVersion</code> is what you want, make sure to treat it as an string or you risk truncating the patch revision number (eg. 3.1.2 -> 3.1).</p>
{ "question_id": 3339722, "question_date": "2010-07-26T23:30:11.657Z", "question_score": 892, "tags": "ios|objective-c", "answer_id": 3339787, "answer_date": "2010-07-26T23:44:27.583Z", "answer_score": 1044 }
Please answer the following Stack Overflow question: Title: MySQL: Large VARCHAR vs. TEXT? <p>I've got a messages table in MySQL which records messages between users. Apart from the typical ids and message types (all integer types) I need to save the actual message text as either VARCHAR or TEXT. I'm setting a front-end limit of 3000 characters which means the messages would never be inserted into the db as longer than this.</p> <p>Is there a rationale for going with either VARCHAR(3000) or TEXT? There's something about just writing VARCHAR(3000) that feels somewhat counter-intuitive. I've been through other similar posts on Stack Overflow but would be good to get views specific to this type of common message storing.</p>
<ul> <li><p><code>TEXT</code> and <code>BLOB</code> <em>may</em> by stored off the table with the table just having a pointer to the location of the actual storage. Where it is stored depends on lots of things like data size, columns size, row_format, and MySQL version.</p></li> <li><p><code>VARCHAR</code> is stored inline with the table. <code>VARCHAR</code> is faster when the size is reasonable, the tradeoff of which would be faster depends upon your data and your hardware, you'd want to benchmark a real-world scenario with your data.</p></li> </ul>
{ "question_id": 2023481, "question_date": "2010-01-07T20:40:33.473Z", "question_score": 891, "tags": "mysql|text|messages|varchar", "answer_id": 2023513, "answer_date": "2010-01-07T20:45:00.017Z", "answer_score": 837 }
Please answer the following Stack Overflow question: Title: Efficiency of Java "Double Brace Initialization"? <p>In <a href="https://stackoverflow.com/questions/15496/hidden-features-of-java">Hidden Features of Java</a> the top answer mentions <a href="http://www.c2.com/cgi/wiki?DoubleBraceInitialization" rel="noreferrer">Double Brace Initialization</a>, with a <em>very</em> enticing syntax:</p> <pre><code>Set&lt;String&gt; flavors = new HashSet&lt;String&gt;() {{ add("vanilla"); add("strawberry"); add("chocolate"); add("butter pecan"); }}; </code></pre> <p>This idiom creates an anonymous inner class with just an instance initializer in it, which "can use any [...] methods in the containing scope". </p> <p>Main question: Is this as <strong>inefficient</strong> as it sounds? Should its use be limited to one-off initializations? (And of course showing off!)</p> <p>Second question: The new HashSet must be the "this" used in the instance initializer ... can anyone shed light on the mechanism? </p> <p>Third question: Is this idiom too <strong>obscure</strong> to use in production code?</p> <p><strong>Summary:</strong> Very, very nice answers, thanks everyone. On question (3), people felt the syntax should be clear (though I'd recommend an occasional comment, especially if your code will pass on to developers who may not be familiar with it). </p> <p>On question (1), the generated code should run quickly. The extra .class files do cause jar file clutter, and slow program startup slightly (thanks to @coobird for measuring that). @Thilo pointed out that garbage collection can be affected, and the memory cost for the extra loaded classes may be a factor in some cases. </p> <p>Question (2) turned out to be most interesting to me. If I understand the answers, what's happening in DBI is that the anonymous inner class extends the class of the object being constructed by the new operator, and hence has a "this" value referencing the instance being constructed. Very neat.</p> <p>Overall, DBI strikes me as something of an intellectual curiousity. Coobird and others point out you can achieve the same effect with Arrays.asList, varargs methods, Google Collections, and the proposed Java 7 Collection literals. Newer JVM languages like Scala, JRuby, and Groovy also offer concise notations for list construction, and interoperate well with Java. Given that DBI clutters up the classpath, slows down class loading a bit, and makes the code a tad more obscure, I'd probably shy away from it. However, I plan to spring this on a friend who's just gotten his SCJP and loves good natured jousts about Java semantics! ;-) Thanks everyone!</p> <p>7/2017: Baeldung <a href="http://www.baeldung.com/java-double-brace-initialization" rel="noreferrer">has a good summary</a> of double brace initialization and considers it an anti-pattern.</p> <p>12/2017: @Basil Bourque notes that in the new Java 9 you can say:</p> <pre><code>Set&lt;String&gt; flavors = Set.of("vanilla", "strawberry", "chocolate", "butter pecan"); </code></pre> <p>That's for sure the way to go. If you're stuck with an earlier version, take a look at <a href="https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/ImmutableSet.html" rel="noreferrer">Google Collections' ImmutableSet</a>.</p>
<p>Here's the problem when I get too carried away with anonymous inner classes:</p> <pre><code>2009/05/27 16:35 1,602 DemoApp2$1.class 2009/05/27 16:35 1,976 DemoApp2$10.class 2009/05/27 16:35 1,919 DemoApp2$11.class 2009/05/27 16:35 2,404 DemoApp2$12.class 2009/05/27 16:35 1,197 DemoApp2$13.class /* snip */ 2009/05/27 16:35 1,953 DemoApp2$30.class 2009/05/27 16:35 1,910 DemoApp2$31.class 2009/05/27 16:35 2,007 DemoApp2$32.class 2009/05/27 16:35 926 DemoApp2$33$1$1.class 2009/05/27 16:35 4,104 DemoApp2$33$1.class 2009/05/27 16:35 2,849 DemoApp2$33.class 2009/05/27 16:35 926 DemoApp2$34$1$1.class 2009/05/27 16:35 4,234 DemoApp2$34$1.class 2009/05/27 16:35 2,849 DemoApp2$34.class /* snip */ 2009/05/27 16:35 614 DemoApp2$40.class 2009/05/27 16:35 2,344 DemoApp2$5.class 2009/05/27 16:35 1,551 DemoApp2$6.class 2009/05/27 16:35 1,604 DemoApp2$7.class 2009/05/27 16:35 1,809 DemoApp2$8.class 2009/05/27 16:35 2,022 DemoApp2$9.class </code></pre> <p>These are all classes which were generated when I was making a simple application, and used copious amounts of anonymous inner classes -- each class will be compiled into a separate <code>class</code> file.</p> <p>The "double brace initialization", as already mentioned, is an anonymous inner class with an instance initialization block, which means that a new class is created for each "initialization", all for the purpose of usually making a single object.</p> <p>Considering that the Java Virtual Machine will need to read all those classes when using them, that can lead to some time in the <a href="http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#88597" rel="noreferrer">bytecode verfication</a> process and such. Not to mention the increase in the needed disk space in order to store all those <code>class</code> files.</p> <p>It seems as if there is a bit of overhead when utilizing double-brace initialization, so it's probably not such a good idea to go too overboard with it. But as Eddie has noted in the comments, it's not possible to be absolutely sure of the impact.</p> <hr> <p>Just for reference, double brace initialization is the following:</p> <pre><code>List&lt;String&gt; list = new ArrayList&lt;String&gt;() {{ add("Hello"); add("World!"); }}; </code></pre> <p>It looks like a "hidden" feature of Java, but it is just a rewrite of:</p> <pre><code>List&lt;String&gt; list = new ArrayList&lt;String&gt;() { // Instance initialization block { add("Hello"); add("World!"); } }; </code></pre> <p>So it's basically a <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/initial.html" rel="noreferrer">instance initialization block</a> that is part of an <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html" rel="noreferrer">anonymous inner class</a>.</p> <hr> <p>Joshua Bloch's <a href="http://mail.openjdk.java.net/pipermail/coin-dev/2009-March/001193.html" rel="noreferrer">Collection Literals proposal</a> for <a href="http://openjdk.java.net/projects/coin/" rel="noreferrer">Project Coin</a> was along the lines of:</p> <pre><code>List&lt;Integer&gt; intList = [1, 2, 3, 4]; Set&lt;String&gt; strSet = {"Apple", "Banana", "Cactus"}; Map&lt;String, Integer&gt; truthMap = { "answer" : 42 }; </code></pre> <p>Sadly, it <a href="http://mail.openjdk.java.net/pipermail/lambda-dev/2014-March/011938.html" rel="noreferrer">didn't make its way</a> into neither Java 7 nor 8 and was shelved indefinitely.</p> <hr> <p><strong>Experiment</strong></p> <p>Here's the simple experiment I've tested -- make 1000 <code>ArrayList</code>s with the elements <code>"Hello"</code> and <code>"World!"</code> added to them via the <code>add</code> method, using the two methods:</p> <p><em>Method 1: Double Brace Initialization</em></p> <pre><code>List&lt;String&gt; l = new ArrayList&lt;String&gt;() {{ add("Hello"); add("World!"); }}; </code></pre> <p><em>Method 2: Instantiate an <code>ArrayList</code> and <code>add</code></em></p> <pre><code>List&lt;String&gt; l = new ArrayList&lt;String&gt;(); l.add("Hello"); l.add("World!"); </code></pre> <p>I created a simple program to write out a Java source file to perform 1000 initializations using the two methods:</p> <p><em>Test 1:</em></p> <pre><code>class Test1 { public static void main(String[] s) { long st = System.currentTimeMillis(); List&lt;String&gt; l0 = new ArrayList&lt;String&gt;() {{ add("Hello"); add("World!"); }}; List&lt;String&gt; l1 = new ArrayList&lt;String&gt;() {{ add("Hello"); add("World!"); }}; /* snip */ List&lt;String&gt; l999 = new ArrayList&lt;String&gt;() {{ add("Hello"); add("World!"); }}; System.out.println(System.currentTimeMillis() - st); } } </code></pre> <p><em>Test 2:</em></p> <pre><code>class Test2 { public static void main(String[] s) { long st = System.currentTimeMillis(); List&lt;String&gt; l0 = new ArrayList&lt;String&gt;(); l0.add("Hello"); l0.add("World!"); List&lt;String&gt; l1 = new ArrayList&lt;String&gt;(); l1.add("Hello"); l1.add("World!"); /* snip */ List&lt;String&gt; l999 = new ArrayList&lt;String&gt;(); l999.add("Hello"); l999.add("World!"); System.out.println(System.currentTimeMillis() - st); } } </code></pre> <p>Please note, that the elapsed time to initialize the 1000 <code>ArrayList</code>s and the 1000 anonymous inner classes extending <code>ArrayList</code> is checked using the <code>System.currentTimeMillis</code>, so the timer does not have a very high resolution. On my Windows system, the resolution is around 15-16 milliseconds.</p> <p>The results for 10 runs of the two tests were the following:</p> <pre><code>Test1 Times (ms) Test2 Times (ms) ---------------- ---------------- 187 0 203 0 203 0 188 0 188 0 187 0 203 0 188 0 188 0 203 0 </code></pre> <p>As can be seen, the double brace initialization has a noticeable execution time of around 190 ms.</p> <p>Meanwhile, the <code>ArrayList</code> initialization execution time came out to be 0 ms. Of course, the timer resolution should be taken into account, but it is likely to be under 15 ms.</p> <p>So, there seems to be a noticeable difference in the execution time of the two methods. It does appear that there is indeed some overhead in the two initialization methods.</p> <p>And yes, there were 1000 <code>.class</code> files generated by compiling the <code>Test1</code> double brace initialization test program.</p>
{ "question_id": 924285, "question_date": "2009-05-29T03:40:13.207Z", "question_score": 891, "tags": "java|performance|collections|initialization", "answer_id": 924326, "answer_date": "2009-05-29T03:59:26.743Z", "answer_score": 647 }
Please answer the following Stack Overflow question: Title: File to byte[] in Java <p>How do I convert a <code>java.io.File</code> to a <code>byte[]</code>?</p>
<p>It depends on what best means for you. Productivity wise, don't reinvent the wheel and use Apache Commons. Which is here <a href="https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html#readFileToByteArray(java.io.File)" rel="noreferrer"><code>FileUtils.readFileToByteArray(File input)</code></a>.</p>
{ "question_id": 858980, "question_date": "2009-05-13T16:30:33.773Z", "question_score": 890, "tags": "java|file-io", "answer_id": 859076, "answer_date": "2009-05-13T16:48:21.483Z", "answer_score": 570 }
Please answer the following Stack Overflow question: Title: How do I do a not equal in Django queryset filtering? <p>In Django model QuerySets, I see that there is a <code>__gt</code> and <code>__lt</code> for comparative values, but is there a <code>__ne</code> or <code>!=</code> (<strong>not equals</strong>)? I want to filter out using a not equals. For example, for</p> <pre><code>Model: bool a; int x; </code></pre> <p>I want to do</p> <pre><code>results = Model.objects.exclude(a=True, x!=5) </code></pre> <p>The <code>!=</code> is not correct syntax. I also tried <code>__ne</code>.</p> <p>I ended up using:</p> <pre><code>results = Model.objects.exclude(a=True, x__lt=5).exclude(a=True, x__gt=5) </code></pre>
<p>You can use <a href="https://docs.djangoproject.com/en/stable/topics/db/queries/#complex-lookups-with-q" rel="noreferrer">Q objects</a> for this. They can be negated with the <code>~</code> operator and combined much like normal Python expressions:</p> <pre><code>from myapp.models import Entry from django.db.models import Q Entry.objects.filter(~Q(id=3)) </code></pre> <p>will return all entries except the one(s) with <code>3</code> as their ID:</p> <pre><code>[&lt;Entry: Entry object&gt;, &lt;Entry: Entry object&gt;, &lt;Entry: Entry object&gt;, ...] </code></pre>
{ "question_id": 687295, "question_date": "2009-03-26T19:47:45.923Z", "question_score": 890, "tags": "python|django|django-models|django-queryset", "answer_id": 1154977, "answer_date": "2009-07-20T17:58:38.883Z", "answer_score": 986 }
Please answer the following Stack Overflow question: Title: What is the difference between YAML and JSON? <p>What are the differences between YAML and JSON, specifically considering the following things?</p> <ul> <li>Performance (encode/decode time)</li> <li>Memory consumption</li> <li>Expression clarity</li> <li>Library availability, ease of use (I prefer C)</li> </ul> <p>I was planning to use one of these two in our embedded system to store configure files.</p> <h3>Related:</h3> <p><a href="https://stackoverflow.com/questions/1876735/">Should I use YAML or JSON to store my Perl data?</a></p>
<p>Technically YAML is a superset of JSON. This means that, in theory at least, a YAML parser can understand JSON, but not necessarily the other way around. </p> <p>See the official specs, in the section entitled <a href="http://yaml.org/spec/1.2/spec.html#id2759572" rel="noreferrer">"YAML: Relation to JSON"</a>.</p> <p>In general, there are certain things I like about YAML that are not available in JSON. </p> <ul> <li>As <a href="https://stackoverflow.com/a/1726816/1218980">@jdupont pointed out</a>, YAML is visually easier to look at. In fact the <a href="http://yaml.org/" rel="noreferrer">YAML homepage</a> is itself valid YAML, yet it is easy for a human to read. </li> <li>YAML has the ability to reference other items within a YAML file using "anchors." Thus it can handle relational information as one might find in a MySQL database. </li> <li>YAML is more robust about embedding other serialization formats such as JSON or XML <em>within</em> a YAML file. </li> </ul> <p>In practice neither of these last two points will likely matter for things that you or I do, but in the long term, I think YAML will be a more robust and viable data serialization format. </p> <p>Right now, AJAX and other web technologies tend to use JSON. YAML is currently being used more for offline data processes. For example, it is included by default in the C-based OpenCV computer vision package, whereas JSON is not. </p> <p>You will find C libraries for both JSON and YAML. YAML's libraries tend to be newer, but I have had no trouble with them in the past. See for example <a href="http://code.google.com/p/yaml-cpp/" rel="noreferrer">Yaml-cpp</a>. </p>
{ "question_id": 1726802, "question_date": "2009-11-13T02:42:47.037Z", "question_score": 890, "tags": "json|yaml", "answer_id": 1729545, "answer_date": "2009-11-13T14:28:02.737Z", "answer_score": 776 }
Please answer the following Stack Overflow question: Title: How can I position my div at the bottom of its container? <p>Given the following HTML:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="container"&gt; &lt;!-- Other elements here --&gt; &lt;div id="copyright"&gt; Copyright Foo web designs &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>I would like <code>#copyright</code> to stick to the bottom of <code>#container</code>. Can I achieve this without using absolute positioning?</p>
<h2>The flexbox approach!</h2> <p>In <a href="http://caniuse.com/#feat=flexbox" rel="noreferrer">supported browsers</a>, you can use the following:</p> <p><a href="http://jsfiddle.net/bv1rs8s1/" rel="noreferrer"><strong>Example Here</strong></a></p> <pre class="lang-css prettyprint-override"><code>.parent { display: flex; flex-direction: column; } .child { margin-top: auto; } </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.parent { height: 100px; border: 5px solid #000; display: flex; flex-direction: column; } .child { height: 40px; width: 100%; background: #f00; margin-top: auto; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="parent"&gt; &lt;div class="child"&gt;Align to the bottom&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <hr> <p>The solution above is probably more flexible, however, here is an alternative solution:</p> <p><a href="http://jsfiddle.net/rh4Lc5dr/" rel="noreferrer"><strong>Example Here</strong></a></p> <pre class="lang-css prettyprint-override"><code>.parent { display: flex; } .child { align-self: flex-end; } </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.parent { height: 100px; border: 5px solid #000; display: flex; } .child { height: 40px; width: 100%; background: #f00; align-self: flex-end; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="parent"&gt; &lt;div class="child"&gt;Align to the bottom&lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <hr> <p>As a side note, you may want to add vendor prefixes for additional support.</p>
{ "question_id": 526035, "question_date": "2009-02-08T17:08:57.470Z", "question_score": 889, "tags": "html|css", "answer_id": 27812717, "answer_date": "2015-01-07T05:04:24.103Z", "answer_score": 277 }
Please answer the following Stack Overflow question: Title: Entity Framework 5 Updating a Record <p>I have been exploring different methods of editing/updating a record within Entity Framework 5 in an ASP.NET MVC3 environment, but so far none of them tick all of the boxes I need. I'll explain why.</p> <p>I have found three methods to which I'll mention the pros and cons:</p> <p><strong>Method 1 - Load original record, update each property</strong></p> <pre><code>var original = db.Users.Find(updatedUser.UserId); if (original != null) { original.BusinessEntityId = updatedUser.BusinessEntityId; original.Email = updatedUser.Email; original.EmployeeId = updatedUser.EmployeeId; original.Forename = updatedUser.Forename; original.Surname = updatedUser.Surname; original.Telephone = updatedUser.Telephone; original.Title = updatedUser.Title; original.Fax = updatedUser.Fax; original.ASPNetUserId = updatedUser.ASPNetUserId; db.SaveChanges(); } </code></pre> <p><em>Pros</em></p> <ul> <li>Can specify which properties change</li> <li>Views don't need to contain every property</li> </ul> <p><em>Cons</em></p> <ul> <li>2 x queries on database to load original then update it</li> </ul> <p><strong>Method 2 - Load original record, set changed values</strong></p> <pre><code>var original = db.Users.Find(updatedUser.UserId); if (original != null) { db.Entry(original).CurrentValues.SetValues(updatedUser); db.SaveChanges(); } </code></pre> <p><em>Pros</em></p> <ul> <li>Only modified properties are sent to database</li> </ul> <p><em>Cons</em></p> <ul> <li>Views need to contain every property</li> <li>2 x queries on database to load original then update it</li> </ul> <p><strong>Method 3 - Attach updated record and set state to EntityState.Modified</strong></p> <pre><code>db.Users.Attach(updatedUser); db.Entry(updatedUser).State = EntityState.Modified; db.SaveChanges(); </code></pre> <p><em>Pros</em></p> <ul> <li>1 x query on database to update</li> </ul> <p><em>Cons</em></p> <ul> <li>Can't specify which properties change</li> <li>Views must contain every property</li> </ul> <p><strong>Question</strong></p> <p>My question to you guys; is there a clean way that I can achieve this set of goals?</p> <ul> <li>Can specify which properties change</li> <li>Views don't need to contain every property (such as password!)</li> <li>1 x query on database to update</li> </ul> <p>I understand this is quite a minor thing to point out but I may be missing a simple solution to this. If not method one will prevail ;-)</p>
<p>You are looking for:</p> <pre><code>db.Users.Attach(updatedUser); var entry = db.Entry(updatedUser); entry.Property(e =&gt; e.Email).IsModified = true; // other changed properties db.SaveChanges(); </code></pre>
{ "question_id": 15336248, "question_date": "2013-03-11T10:27:12.657Z", "question_score": 889, "tags": "c#|asp.net-mvc-3|entity-framework-5", "answer_id": 15339512, "answer_date": "2013-03-11T13:12:34.607Z", "answer_score": 685 }
Please answer the following Stack Overflow question: Title: Get key by value in dictionary <p>I made a function which will look up ages in a <code>Dictionary</code> and show the matching name:</p> <pre><code>dictionary = {'george' : 16, 'amber' : 19} search_age = raw_input("Provide age") for age in dictionary.values(): if age == search_age: name = dictionary[age] print name </code></pre> <p>I know how to compare and find the age I just don't know how to show the name of the person. Additionally, I am getting a <code>KeyError</code> because of line 5. I know it's not correct but I can't figure out how to make it search backwards.</p>
<p>There is none. <code>dict</code> is not intended to be used this way.</p> <pre><code>dictionary = {'george': 16, 'amber': 19} search_age = input("Provide age") for name, age in dictionary.items(): # for name, age in dictionary.iteritems(): (for Python 2.x) if age == search_age: print(name) </code></pre>
{ "question_id": 8023306, "question_date": "2011-11-05T21:09:18.203Z", "question_score": 888, "tags": "python|dictionary", "answer_id": 8023337, "answer_date": "2011-11-05T21:13:09.117Z", "answer_score": 678 }
Please answer the following Stack Overflow question: Title: Deleting DataFrame row in Pandas based on column value <p>I have the following DataFrame:</p> <pre><code> daysago line_race rating rw wrating line_date 2007-03-31 62 11 56 1.000000 56.000000 2007-03-10 83 11 67 1.000000 67.000000 2007-02-10 111 9 66 1.000000 66.000000 2007-01-13 139 10 83 0.880678 73.096278 2006-12-23 160 10 88 0.793033 69.786942 2006-11-09 204 9 52 0.636655 33.106077 2006-10-22 222 8 66 0.581946 38.408408 2006-09-29 245 9 70 0.518825 36.317752 2006-09-16 258 11 68 0.486226 33.063381 2006-08-30 275 8 72 0.446667 32.160051 2006-02-11 475 5 65 0.164591 10.698423 2006-01-13 504 0 70 0.142409 9.968634 2006-01-02 515 0 64 0.134800 8.627219 2005-12-06 542 0 70 0.117803 8.246238 2005-11-29 549 0 70 0.113758 7.963072 2005-11-22 556 0 -1 0.109852 -0.109852 2005-11-01 577 0 -1 0.098919 -0.098919 2005-10-20 589 0 -1 0.093168 -0.093168 2005-09-27 612 0 -1 0.083063 -0.083063 2005-09-07 632 0 -1 0.075171 -0.075171 2005-06-12 719 0 69 0.048690 3.359623 2005-05-29 733 0 -1 0.045404 -0.045404 2005-05-02 760 0 -1 0.039679 -0.039679 2005-04-02 790 0 -1 0.034160 -0.034160 2005-03-13 810 0 -1 0.030915 -0.030915 2004-11-09 934 0 -1 0.016647 -0.016647 </code></pre> <p>I need to remove the rows where <code>line_race</code> is equal to <code>0</code>. What's the most efficient way to do this?</p>
<p>If I'm understanding correctly, it should be as simple as:</p> <pre><code>df = df[df.line_race != 0] </code></pre>
{ "question_id": 18172851, "question_date": "2013-08-11T14:14:57.950Z", "question_score": 888, "tags": "python|pandas", "answer_id": 18173074, "answer_date": "2013-08-11T14:38:31.897Z", "answer_score": 1417 }
Please answer the following Stack Overflow question: Title: What's the difference between faking, mocking, and stubbing? <p>I know how I use these terms, but I'm wondering if there are accepted definitions for <strong>faking</strong>, <strong>mocking</strong>, and <strong>stubbing</strong> for unit tests? How do you define these for your tests? Describe situations where you might use each.</p> <p>Here is how I use them:</p> <p><strong>Fake</strong>: a class that implements an interface but contains fixed data and no logic. Simply returns "good" or "bad" data depending on the implementation.</p> <p><strong>Mock</strong>: a class that implements an interface and allows the ability to dynamically set the values to return/exceptions to throw from particular methods and provides the ability to check if particular methods have been called/not called.</p> <p><strong>Stub</strong>: Like a mock class, except that it doesn't provide the ability to verify that methods have been called/not called.</p> <p>Mocks and stubs can be hand generated or generated by a mocking framework. Fake classes are generated by hand. I use mocks primarily to verify interactions between my class and dependent classes. I use stubs once I have verified the interactions and am testing alternate paths through my code. I use fake classes primarily to abstract out data dependencies or when mocks/stubs are too tedious to set up each time.</p>
<p>You can get some information :</p> <h2>From <a href="http://www.martinfowler.com/articles/mocksArentStubs.html" rel="noreferrer">Martin Fowler about Mock and Stub</a></h2> <p><strong>Fake</strong> objects actually have working implementations, but usually take some shortcut which makes them not suitable for production</p> <p><strong>Stubs</strong> provide canned answers to calls made during the test, usually not responding at all to anything outside what's programmed in for the test. Stubs may also record information about calls, such as an email gateway stub that remembers the messages it 'sent', or maybe only how many messages it 'sent'.</p> <p><strong>Mocks</strong> are what we are talking about here: objects pre-programmed with expectations which form a specification of the calls they are expected to receive.</p> <h2>From <a href="http://xunitpatterns.com" rel="noreferrer">xunitpattern</a>:</h2> <p><strong>Fake</strong>: We acquire or build a very lightweight implementation of the same functionality as provided by a component that the SUT depends on and instruct the SUT to use it instead of the real.</p> <p><strong>Stub</strong> : This implementation is configured to respond to calls from the SUT with the values (or exceptions) that will exercise the Untested Code (see Production Bugs on page X) within the SUT. A key indication for using a Test Stub is having Untested Code caused by the inability to control the indirect inputs of the SUT</p> <p><strong>Mock Object</strong> that implements the same interface as an object on which the SUT (System Under Test) depends. We can use a Mock Object as an observation point when we need to do Behavior Verification to avoid having an Untested Requirement (see Production Bugs on page X) caused by an inability to observe side-effects of invoking methods on the SUT.</p> <h2>Personally</h2> <p>I try to simplify by using : Mock and Stub. I use Mock when it's an object that returns a value that is set to the tested class. I use Stub to mimic an Interface or Abstract class to be tested. In fact, it doesn't really matter what you call it, they are all classes that aren't used in production, and are used as utility classes for testing.</p>
{ "question_id": 346372, "question_date": "2008-12-06T15:17:46.203Z", "question_score": 888, "tags": "unit-testing|mocking|language-agnostic|terminology|definition", "answer_id": 346440, "answer_date": "2008-12-06T16:17:52.617Z", "answer_score": 653 }
Please answer the following Stack Overflow question: Title: Why are these constructs using pre and post-increment undefined behavior? <pre><code>#include &lt;stdio.h&gt; int main(void) { int i = 0; i = i++ + ++i; printf("%d\n", i); // 3 i = 1; i = (i++); printf("%d\n", i); // 2 Should be 1, no ? volatile int u = 0; u = u++ + ++u; printf("%d\n", u); // 1 u = 1; u = (u++); printf("%d\n", u); // 2 Should also be one, no ? register int v = 0; v = v++ + ++v; printf("%d\n", v); // 3 (Should be the same as u ?) int w = 0; printf("%d %d\n", ++w, w); // shouldn't this print 1 1 int x[2] = { 5, 8 }, y = 0; x[y] = y ++; printf("%d %d\n", x[0], x[1]); // shouldn't this print 0 8? or 5 0? } </code></pre>
<p>C has the concept of undefined behavior, i.e. some language constructs are syntactically valid but you can't predict the behavior when the code is run.</p> <p>As far as I know, the standard doesn't explicitly say <em>why</em> the concept of undefined behavior exists. In my mind, it's simply because the language designers wanted there to be some leeway in the semantics, instead of i.e. requiring that all implementations handle integer overflow in the exact same way, which would very likely impose serious performance costs, they just left the behavior undefined so that if you write code that causes integer overflow, anything can happen.</p> <p>So, with that in mind, why are these "issues"? The language clearly says that certain things lead to <a href="http://en.wikipedia.org/wiki/Undefined_behavior" rel="noreferrer">undefined behavior</a>. There is no problem, there is no "should" involved. If the undefined behavior changes when one of the involved variables is declared <code>volatile</code>, that doesn't prove or change anything. It is <em>undefined</em>; you cannot reason about the behavior.</p> <p>Your most interesting-looking example, the one with</p> <pre><code>u = (u++); </code></pre> <p>is a text-book example of undefined behavior (see Wikipedia's entry on <a href="http://en.wikipedia.org/wiki/Sequence_point" rel="noreferrer">sequence points</a>).</p>
{ "question_id": 949433, "question_date": "2009-06-04T09:17:52.267Z", "question_score": 888, "tags": "c|increment|undefined-behavior|operator-precedence|sequence-points", "answer_id": 949443, "answer_date": "2009-06-04T09:20:59.763Z", "answer_score": 615 }
Please answer the following Stack Overflow question: Title: Database, Table and Column Naming Conventions? <p>Whenever I design a database, I always wonder if there is a best way of naming an item in my database. Quite often I ask myself the following questions:</p> <ol> <li>Should table names be plural?</li> <li>Should column names be singular?</li> <li>Should I prefix tables or columns?</li> <li>Should I use any case in naming items?</li> </ol> <p>Are there any recommended guidelines out there for naming items in a database?</p>
<p>I recommend checking out Microsoft's SQL Server sample databases: <a href="https://github.com/Microsoft/sql-server-samples/releases/tag/adventureworks" rel="noreferrer">https://github.com/Microsoft/sql-server-samples/releases/tag/adventureworks</a></p> <p>The AdventureWorks sample uses a very clear and consistent naming convention that uses schema names for the organization of database objects.</p> <ol> <li>Singular names for tables</li> <li>Singular names for columns</li> <li>Schema name for tables prefix (E.g.: SchemeName.TableName)</li> <li>Pascal casing (a.k.a. upper camel case)</li> </ol>
{ "question_id": 7662, "question_date": "2008-08-11T10:27:22.780Z", "question_score": 887, "tags": "database|database-design|language-agnostic|naming-conventions", "answer_id": 7724, "answer_date": "2008-08-11T12:39:37.817Z", "answer_score": 376 }
Please answer the following Stack Overflow question: Title: How do I wrap text in a pre tag? <p><code>pre</code> tags are super-useful for code blocks in HTML and for debugging output while writing scripts, but how do I make the text word-wrap instead of printing out one long line?</p>
<p>The answer, from <a href="https://longren.io/wrapping-text-inside-pre-tags/" rel="noreferrer">this page</a> in CSS:</p> <pre><code>pre { white-space: pre-wrap; /* Since CSS 2.1 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* Internet Explorer 5.5+ */ } </code></pre>
{ "question_id": 248011, "question_date": "2008-10-29T19:03:23.353Z", "question_score": 887, "tags": "html|css", "answer_id": 248013, "answer_date": "2008-10-29T19:04:14.383Z", "answer_score": 1228 }
Please answer the following Stack Overflow question: Title: What's the difference between SoftReference and WeakReference in Java? <p>What's the difference between <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ref/WeakReference.html" rel="noreferrer"><code>java.lang.ref.WeakReference</code></a> and <a href="https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ref/SoftReference.html" rel="noreferrer"><code>java.lang.ref.SoftReference</code></a> ?</p>
<p>From <a href="https://web.archive.org/web/20061130103858/http://weblogs.java.net/blog/enicholas/archive/2006/05/understanding_w.html" rel="noreferrer">Understanding Weak References</a>, by Ethan Nicholas:</p> <blockquote> <p><strong>Weak references</strong></p> <p>A <em>weak reference</em>, simply put, is a reference that isn't strong enough to force an object to remain in memory. Weak references allow you to leverage the garbage collector's ability to determine reachability for you, so you don't have to do it yourself. You create a weak reference like this:</p> <pre><code>WeakReference weakWidget = new WeakReference(widget); </code></pre> <p>and then elsewhere in the code you can use <code>weakWidget.get()</code> to get the actual <code>Widget</code> object. Of course the weak reference isn't strong enough to prevent garbage collection, so you may find (if there are no strong references to the widget) that <code>weakWidget.get()</code> suddenly starts returning <code>null</code>.</p> <p>...</p> <p><strong>Soft references</strong></p> <p>A <em>soft reference</em> is exactly like a weak reference, except that it is less eager to throw away the object to which it refers. An object which is only weakly reachable (the strongest references to it are <code>WeakReferences</code>) will be discarded at the next garbage collection cycle, but an object which is softly reachable will generally stick around for a while.</p> <p><code>SoftReferences</code> aren't <em>required</em> to behave any differently than <code>WeakReferences</code>, but in practice softly reachable objects are generally retained as long as memory is in plentiful supply. This makes them an excellent foundation for a cache, such as the image cache described above, since you can let the garbage collector worry about both how reachable the objects are (a strongly reachable object will <em>never</em> be removed from the cache) and how badly it needs the memory they are consuming.</p> </blockquote> <p>And Peter Kessler added in a comment:</p> <blockquote> <p>The Sun JRE does treat SoftReferences differently from WeakReferences. We attempt to hold on to object referenced by a SoftReference if there isn't pressure on the available memory. One detail: the policy for the "-client" and "-server" JRE's are different: the -client JRE tries to keep your footprint small by preferring to clear SoftReferences rather than expand the heap, whereas the -server JRE tries to keep your performance high by preferring to expand the heap (if possible) rather than clear SoftReferences. One size does not fit all.</p> </blockquote>
{ "question_id": 299659, "question_date": "2008-11-18T18:26:37.637Z", "question_score": 887, "tags": "java|reference|weak-references|soft-references", "answer_id": 299702, "answer_date": "2008-11-18T18:37:29.690Z", "answer_score": 1001 }
Please answer the following Stack Overflow question: Title: get and set in TypeScript <p>I'm trying to create get and set method for a property:</p> <pre><code>private _name: string; Name() { get: { return this._name; } set: { this._name = ???; } } </code></pre> <p>What's the keyword to set a value?</p>
<p>TypeScript uses getter/setter syntax that is like ECMAScript4/ActionScript3.</p> <pre><code>class foo { private _bar: boolean = false; get bar(): boolean { return this._bar; } set bar(value: boolean) { this._bar = value; } } </code></pre> <p>That will produce this JavaScript, using the ECMAScript 5 <code>Object.defineProperty()</code> feature.</p> <pre><code>var foo = (function () { function foo() { this._bar = false; } Object.defineProperty(foo.prototype, &quot;bar&quot;, { get: function () { return this._bar; }, set: function (value) { this._bar = value; }, enumerable: true, configurable: true }); return foo; })(); </code></pre> <p>So to use it,</p> <pre><code>var myFoo = new foo(); if(myFoo.bar) { // calls the getter myFoo.bar = false; // calls the setter and passes false } </code></pre> <p>However, in order to use it at all, you must make sure the TypeScript compiler targets ECMAScript5. If you are running the command line compiler, use <code>--target</code> flag like this;</p> <pre><code>tsc --target ES5 </code></pre> <p>If you are using Visual Studio, you must edit your project file to add the flag to the configuration for the TypeScriptCompile build tool. You can see that <a href="https://stackoverflow.com/a/17261732/1733315">here</a>:</p> <p>As @DanFromGermany suggests below, if your are simply reading and writing a local property like <code>foo.bar = true</code>, then having a setter and getter pair is overkill. You can always add them later if you need to do something, like logging, whenever the property is read or written.</p> <p>Getters can be used to implement readonly properties. Here is an example that also shows how getters interact with readonly and optional types.</p> <pre><code>// // type with optional readonly property. // baz?:string is the same as baz:string|undefined // type Foo = { readonly bar: string; readonly baz?: string; } const foo:Foo = {bar: &quot;bar&quot;} console.log(foo.bar) // prints 'bar' console.log(foo.baz) // prints undefined // // interface with optional readonly property // interface iFoo { readonly bar: string; readonly baz?: string; } const ifoo:iFoo = {bar: &quot;bar&quot;} console.log(ifoo.bar) // prints 'bar' console.log(ifoo.baz) // prints undefined // // class implements bar as a getter, // but leaves off baz. // class iBarClass implements iFoo { get bar() { return &quot;bar&quot; } } const iBarInstance = new iBarClass() console.log(iBarInstance.bar) // prints 'bar' console.log(iBarInstance.baz) // prints 'undefined' // accessing baz gives warning that baz does not exist // on iBarClass but returns undefined // note that you could define baz as a getter // and just return undefined to remove the warning. // // class implements optional readonly property as a getter // class iBazClass extends iBarClass { private readonly _baz?: string constructor(baz?:string) { super() this._baz = baz } get baz() { return this._baz; } } const iBazInstance = new iBazClass(&quot;baz&quot;) console.log(iBazInstance.bar) // prints bar console.log(iBazInstance.baz) // prints baz </code></pre>
{ "question_id": 12827266, "question_date": "2012-10-10T19:52:14.990Z", "question_score": 886, "tags": "typescript", "answer_id": 12850536, "answer_date": "2012-10-12T00:19:25.973Z", "answer_score": 1390 }
Please answer the following Stack Overflow question: Title: How to change the remote a branch is tracking? <p>The <code>central</code> repository had to be set up on a new server, so I created a new remote on my local repo, and pushed to that.</p> <p>But now when I do <code>git pull</code>, it claims I am up to date. It's wrong&mdash;it's telling me about the <em>old</em> remote branch, not the new one, which I know for a fact has new commits to fetch.</p> <p>How do I change my local branch to track a different remote?</p> <p>I can see this in the git config file but I don't want to mess things up.</p> <pre><code>[branch "master"] remote = oldserver merge = refs/heads/master </code></pre>
<h2>Using <strong>git v1.8.0</strong> or later:</h2> <pre class="lang-sh prettyprint-override"><code>git branch branch_name --set-upstream-to your_new_remote/branch_name </code></pre> <h2>Or you can use the <code>-u</code> switch</h2> <pre class="lang-sh prettyprint-override"><code>git branch branch_name -u your_new_remote/branch_name </code></pre> <h3>Using git <strong>v1.7.12</strong> or earlier</h3> <pre class="lang-sh prettyprint-override"><code>git branch --set-upstream branch_name your_new_remote/branch_name </code></pre>
{ "question_id": 4878249, "question_date": "2011-02-02T18:20:33.693Z", "question_score": 886, "tags": "git", "answer_id": 4879224, "answer_date": "2011-02-02T19:59:55.120Z", "answer_score": 1430 }
Please answer the following Stack Overflow question: Title: How to change node.js's console font color? <p>I had to change the console background color to white because of eye problems, but the font is gray colored and it makes the messages unreadable. How can I change it?</p>
<p>Below you can find colors reference of text to command when running node.js application:</p> <pre><code>console.log('\x1b[36m%s\x1b[0m', 'I am cyan'); //cyan console.log('\x1b[33m%s\x1b[0m', stringToMakeYellow); //yellow </code></pre> <p>Note <code>%s</code> is where in the string (the second argument) gets injected. <code>\x1b[0m</code> resets the terminal color so it doesn't continue to be the chosen color anymore after this point.</p> <p><strong>Colors reference</strong></p> <pre><code>Reset = "\x1b[0m" Bright = "\x1b[1m" Dim = "\x1b[2m" Underscore = "\x1b[4m" Blink = "\x1b[5m" Reverse = "\x1b[7m" Hidden = "\x1b[8m" FgBlack = "\x1b[30m" FgRed = "\x1b[31m" FgGreen = "\x1b[32m" FgYellow = "\x1b[33m" FgBlue = "\x1b[34m" FgMagenta = "\x1b[35m" FgCyan = "\x1b[36m" FgWhite = "\x1b[37m" BgBlack = "\x1b[40m" BgRed = "\x1b[41m" BgGreen = "\x1b[42m" BgYellow = "\x1b[43m" BgBlue = "\x1b[44m" BgMagenta = "\x1b[45m" BgCyan = "\x1b[46m" BgWhite = "\x1b[47m" </code></pre> <p>EDIT:</p> <p>For example, <code>\x1b[31m</code> is an <em>escape sequence</em> that will be intercepted by your terminal and instructs it to switch to the red color. In fact, <code>\x1b</code> is the code for the <strong>non-printable control character</strong> <code>escape</code>. Escape sequences dealing only with colors and styles are also known as <strong><a href="https://en.wikipedia.org/wiki/ANSI_escape_code#Colors" rel="noreferrer">ANSI escape code</a></strong> and are standardized, so therefore they (should) work on any platform.</p> <p>Wikipedia has a nice comparison of how different terminals display colors <a href="https://en.wikipedia.org/wiki/ANSI_escape_code#Colors" rel="noreferrer">https://en.wikipedia.org/wiki/ANSI_escape_code#Colors</a></p>
{ "question_id": 9781218, "question_date": "2012-03-20T04:07:02.943Z", "question_score": 886, "tags": "node.js|colors|console", "answer_id": 41407246, "answer_date": "2016-12-31T09:53:38.580Z", "answer_score": 1880 }
Please answer the following Stack Overflow question: Title: What methods of ‘clearfix’ can I use? <p>I have the age-old problem of a <code>div</code> wrapping a two-column layout. My sidebar is floated, so my container <code>div</code> fails to wrap the content and sidebar.</p> <pre class="lang-html prettyprint-override"><code>&lt;div id="container"&gt; &lt;div id="content"&gt;&lt;/div&gt; &lt;div id="sidebar"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>There seem to be numerous methods of fixing the clear bug in Firefox:</p> <ul> <li><code>&lt;br clear="all"/&gt;</code></li> <li><code>overflow:auto</code></li> <li><code>overflow:hidden</code></li> </ul> <p>In my situation, the only one that seems to work correctly is the <code>&lt;br clear="all"/&gt;</code> solution, which is a little bit scruffy. <code>overflow:auto</code> gives me nasty scrollbars, and <code>overflow:hidden</code> must surely have side effects. Also, IE7 apparently shouldn't suffer from this problem due to its incorrect behaviour, but in my situation it's suffering the same as Firefox.</p> <p>Which method currently available to us is the most robust?</p>
<p>Depending upon the design being produced, each of the below clearfix CSS solutions has its own benefits.</p> <p>The clearfix does have useful applications but it has also been used as a hack. Before you use a clearfix perhaps these modern css solutions can be useful:</p> <ul> <li><a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/" rel="noreferrer">css flexbox</a></li> <li><a href="https://css-tricks.com/snippets/css/complete-guide-grid/" rel="noreferrer">css grid</a></li> </ul> <hr> <h1>Modern Clearfix Solutions</h1> <hr> <h2>Container with <code>overflow: auto;</code></h2> <p>The simplest way to clear floated elements is using the style <code>overflow: auto</code> on the containing element. This solution works in every modern browsers.</p> <pre class="lang-html prettyprint-override"><code>&lt;div style="overflow: auto;"&gt; &lt;img style="float: right;" src="path/to/floated-element.png" width="500" height="500" &gt; &lt;p&gt;Your content here…&lt;/p&gt; &lt;/div&gt; </code></pre> <p>One downside, using certain combinations of margin and padding on the external element can cause scrollbars to appear but this can be solved by placing the margin and padding on another parent containing element.</p> <p>Using ‘overflow: hidden’ is also a clearfix solution, but will not have scrollbars, however using <code>hidden</code> will crop any content positioned outside of the containing element.</p> <p><em>Note:</em> The floated element is an <code>img</code> tag in this example, but could be any html element.</p> <hr> <h2>Clearfix Reloaded</h2> <p>Thierry Koblentz on CSSMojo wrote: <a href="http://cssmojo.com/the-very-latest-clearfix-reloaded/" rel="noreferrer">The very latest clearfix reloaded</a>. He noted that by dropping support for oldIE, the solution can be simplified to one css statement. Additionally, using <code>display: block</code> (instead of <code>display: table</code>) allows margins to collapse properly when elements with clearfix are siblings.</p> <pre class="lang-css prettyprint-override"><code>.container::after { content: ""; display: block; clear: both; } </code></pre> <p>This is the most modern version of the clearfix.</p> <hr> <p>⋮</p> <p>⋮</p> <h1>Older Clearfix Solutions</h1> <p>The below solutions are not necessary for modern browsers, but may be useful for targeting older browsers.</p> <p>Note that these solutions rely upon browser bugs and therefore should be used only if none of the above solutions work for you.</p> <p>They are listed roughly in chronological order.</p> <hr> <h2>"Beat That ClearFix", a clearfix for modern browsers</h2> <p>Thierry Koblentz' of <a href="http://www.cssmojo.com/latest_new_clearfix_so_far/" rel="noreferrer">CSS Mojo</a> has pointed out that when targeting modern browsers, we can now drop the <code>zoom</code> and <code>::before</code> property/values and simply use:</p> <pre class="lang-css prettyprint-override"><code>.container::after { content: ""; display: table; clear: both; } </code></pre> <p><em>This solution does not support for IE 6/7 …on purpose!</em></p> <p>Thierry also offers: "<a href="http://www.cssmojo.com/latest_new_clearfix_so_far/#why-is-that" rel="noreferrer">A word of caution</a>: if you start a new project from scratch, go for it, but don’t swap this technique with the one you have now, because even though you do not support oldIE, your existing rules prevent collapsing margins."</p> <hr> <h2>Micro Clearfix</h2> <p>The most recent and globally adopted clearfix solution, the <a href="http://nicolasgallagher.com/micro-clearfix-hack/" rel="noreferrer">Micro Clearfix by Nicolas Gallagher</a>.</p> <p><em>Known support: Firefox 3.5+, Safari 4+, Chrome, Opera 9+, IE 6+</em></p> <pre class="lang-css prettyprint-override"><code>.container::before, .container::after { content: ""; display: table; } .container::after { clear: both; } .container { zoom: 1; } </code></pre> <hr> <h2>Overflow Property</h2> <p>This basic method is preferred for the usual case, when positioned content will not show outside the bounds of the container.</p> <p><a href="http://www.quirksmode.org/css/clearing.html" rel="noreferrer">http://www.quirksmode.org/css/clearing.html</a> - <em>explains how to resolve common issues related to this technique, namely, setting <code>width: 100%</code> on the container.</em></p> <pre class="lang-css prettyprint-override"><code>.container { overflow: hidden; display: inline-block; display: block; } </code></pre> <p>Rather than using the <code>display</code> property to set "hasLayout" for IE, other properties can be used for <a href="http://www.satzansatz.de/cssd/onhavinglayout.html" rel="noreferrer">triggering "hasLayout" for an element</a>.</p> <pre class="lang-css prettyprint-override"><code>.container { overflow: hidden; zoom: 1; display: block; } </code></pre> <p>Another way to clear floats using the <code>overflow</code> property is to use the <a href="http://wellstyled.com/css-underscore-hack.html" rel="noreferrer">underscore hack</a>. IE will apply the values prefixed with the underscore, other browsers will not. The <code>zoom</code> property triggers <a href="http://www.satzansatz.de/cssd/onhavinglayout.html" rel="noreferrer">hasLayout</a> in IE:</p> <pre class="lang-css prettyprint-override"><code>.container { overflow: hidden; _overflow: visible; /* for IE */ _zoom: 1; /* for IE */ } </code></pre> <p>While this works... it is not ideal to use hacks.</p> <hr> <h2>PIE: Easy Clearing Method</h2> <p>This older "Easy Clearing" method has the advantage of allowing positioned elements to hang outside the bounds of the container, at the expense of more tricky CSS.</p> <p>This solution is quite old, but you can learn all about Easy Clearing on Position Is Everything: <a href="http://www.positioniseverything.net/easyclearing.html" rel="noreferrer">http://www.positioniseverything.net/easyclearing.html</a></p> <hr> <h2>Element using "clear" property</h2> <p>The quick and dirty solution (with some drawbacks) for when you’re quickly slapping something together:</p> <pre><code>&lt;br style="clear: both" /&gt; &lt;!-- So dirty! --&gt; </code></pre> <h3>Drawbacks</h3> <ul> <li>It's not responsive and thus may not provide the desired effect if layout styles change based upon media queries. A solution in pure CSS is more ideal.</li> <li>It adds html markup without necessarily adding any semantic value.</li> <li>It requires a inline definition and solution for each instance rather than a class reference to a single solution of a “clearfix” in the css and class references to it in the html.</li> <li>It makes code difficult to work with for others as they may have to write more hacks to work around it.</li> <li>In the future when you need/want to use another clearfix solution, you won't have to go back and remove every <code>&lt;br style="clear: both" /&gt;</code> tag littered around the markup.</li> </ul>
{ "question_id": 211383, "question_date": "2008-10-17T08:15:36.747Z", "question_score": 886, "tags": "css|clearfix", "answer_id": 1633170, "answer_date": "2009-10-27T19:37:01.643Z", "answer_score": 1062 }
Please answer the following Stack Overflow question: Title: Making TextView scrollable on Android <p>I am displaying text in a TextView that appears to be too long to fit into one screen. I need to make my TextView scrollable. How can I do that?</p> <p>Here is the code:</p> <pre><code>final TextView tv = new TextView(this); tv.setBackgroundResource(R.drawable.splash); tv.setTypeface(face); tv.setTextSize(18); tv.setTextColor(R.color.BROWN); tv.setGravity(Gravity.CENTER_VERTICAL| Gravity.CENTER_HORIZONTAL); tv.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent e) { Random r = new Random(); int i = r.nextInt(101); if (e.getAction() == e.ACTION_DOWN) { tv.setText(tips[i]); tv.setBackgroundResource(R.drawable.inner); } return true; } }); setContentView(tv); </code></pre>
<p>You don't need to use a <code>ScrollView</code> actually.</p> <p>Just set the</p> <pre><code>android:scrollbars = "vertical" </code></pre> <p>properties of your <code>TextView</code> in your layout's xml file. </p> <p>Then use:</p> <p><code>yourTextView.setMovementMethod(new ScrollingMovementMethod());</code> </p> <p>in your code.</p> <p>Bingo, it scrolls! </p>
{ "question_id": 1748977, "question_date": "2009-11-17T13:43:03.510Z", "question_score": 885, "tags": "android|scroll|textview|android-scrollview|scrollable", "answer_id": 3256305, "answer_date": "2010-07-15T14:07:04.643Z", "answer_score": 1956 }
Please answer the following Stack Overflow question: Title: Reliable way for a Bash script to get the full path to itself <p>I have a Bash script that needs to know its full path. I'm trying to find a broadly-compatible way of doing that without ending up with relative or funky-looking paths. I only need to support Bash, not sh, csh, etc.</p> <p>What I've found so far:</p> <ol> <li><p>The accepted answer to <em><a href="https://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in">Getting the source directory of a Bash script from within</a></em> addresses getting the path of the script via <code>dirname $0</code>, which is fine, but that may return a <em>relative</em> path (like <code>.</code>), which is a problem if you want to change directories in the script and have the path still point to the script's directory. Still, <code>dirname</code> will be part of the puzzle.</p></li> <li><p>The accepted answer to <em><a href="https://stackoverflow.com/questions/3572030/bash-script-absolute-path-with-osx">Bash script absolute path with OS X</a></em> <em>(OS X specific, but the answer works regardless)</em> gives a function that will test to see if <code>$0</code> looks relative and if so will pre-pend <code>$PWD</code> to it. But the result can still have relative bits in it (although overall it's absolute)&nbsp;&mdash; for instance, if the script is <code>t</code> in the directory <code>/usr/bin</code> and you're in <code>/usr</code> and you type <code>bin/../bin/t</code> to run it (yes, that's convoluted), you end up with <code>/usr/bin/../bin</code> as the script's directory path. Which <strong>works</strong>, but...</p></li> <li><p>The <code>readlink</code> solution <a href="https://web.archive.org/web/20110620064726/http://fritzthomas.com/open-source/linux/384-how-to-get-the-absolute-path-within-the-running-bash-script/" rel="noreferrer">on this page</a>, which looks like this:</p> <pre><code># Absolute path to this script. /home/user/bin/foo.sh SCRIPT=$(readlink -f $0) # Absolute path this script is in. /home/user/bin SCRIPTPATH=`dirname $SCRIPT` </code></pre> <p>But <code>readlink</code> isn't POSIX and apparently the solution relies on GNU's <code>readlink</code> where BSD's won't work for some reason (I don't have access to a BSD-like system to check).</p></li> </ol> <p>So, various ways of doing it, but they all have their caveats.</p> <p>What would be a better way? Where "better" means:</p> <ul> <li>Gives me the absolute path.</li> <li>Takes out funky bits even when invoked in a convoluted way (see comment on #2 above). (E.g., at least moderately canonicalizes the path.)</li> <li>Relies only on Bash-isms or things that are almost certain to be on most popular flavors of *nix systems (GNU/Linux, BSD and BSD-like systems like OS&nbsp;X, etc.).</li> <li>Avoids calling external programs if possible (e.g., prefers Bash built-ins).</li> <li>(<strong>Updated</strong>, thanks for the heads up, <a href="https://stackoverflow.com/users/251414/wich">wich</a>) It doesn't have to resolve symlinks (in fact, I'd kind of prefer it left them alone, but that's not a requirement).</li> </ul>
<p>Here's what I've come up with (edit: plus some tweaks provided by <a href="https://stackoverflow.com/users/1430833/sfstewman">sfstewman</a>, <a href="https://stackoverflow.com/users/397210/levigroker">levigroker</a>, <a href="https://stackoverflow.com/users/1858225/kyle-strand">Kyle Strand</a>, and <a href="https://stackoverflow.com/users/33732/rob-kennedy">Rob Kennedy</a>), that seems to mostly fit my &quot;better&quot; criteria:</p> <pre><code>SCRIPTPATH=&quot;$( cd -- &quot;$(dirname &quot;$0&quot;)&quot; &gt;/dev/null 2&gt;&amp;1 ; pwd -P )&quot; </code></pre> <p>That <code>SCRIPTPATH</code> line seems particularly roundabout, but we need it rather than <code>SCRIPTPATH=`pwd` </code> in order to properly handle spaces and symlinks.</p> <p>The inclusion of output redirection (<code>&gt;/dev/null 2&gt;&amp;1</code>) handles the rare(?) case where <code>cd</code> might produce output that would interfere with the surrounding <code>$( ... )</code> capture. (Such as <a href="https://unix.stackexchange.com/a/20413/32976"><code>cd</code> being overridden to also <code>ls</code> a directory</a> after switching to it.)</p> <p>Note also that esoteric situations, such as executing a script that isn't coming from a file in an accessible file system at all (which is perfectly possible), is not catered to there (or in any of the other answers I've seen).</p> <p>The <code>--</code> after <code>cd</code> and before <code>&quot;$0&quot;</code> are in case the directory starts with a <code>-</code>.</p>
{ "question_id": 4774054, "question_date": "2011-01-23T13:24:16.817Z", "question_score": 885, "tags": "bash|path", "answer_id": 4774063, "answer_date": "2011-01-23T13:25:57.020Z", "answer_score": 763 }
Please answer the following Stack Overflow question: Title: Linking to an external URL in Javadoc? <p>Something like:</p> <pre><code>/** * See {@linktourl http://google.com} */ </code></pre>
<p>This creates a "See Also" heading containing the link, i.e.:</p> <pre><code>/** * @see &lt;a href="http://google.com"&gt;http://google.com&lt;/a&gt; */ </code></pre> <p>will render as:</p> <blockquote> <p><strong>See Also:</strong><br/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="http://google.com" rel="noreferrer">http://google.com</a></p> </blockquote> <p>whereas this:</p> <pre><code>/** * See &lt;a href="http://google.com"&gt;http://google.com&lt;/a&gt; */ </code></pre> <p>will create an in-line link:</p> <blockquote> <p>See <a href="http://google.com" rel="noreferrer">http://google.com</a></p> </blockquote>
{ "question_id": 1082050, "question_date": "2009-07-04T11:44:32.330Z", "question_score": 885, "tags": "java|url|javadoc|hyperlink", "answer_id": 10683345, "answer_date": "2012-05-21T10:13:41.317Z", "answer_score": 1404 }
Please answer the following Stack Overflow question: Title: List of lists changes reflected across sublists unexpectedly <p>I created a list of lists:</p> <pre><code>xs = [[1] * 4] * 3 # xs == [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]] </code></pre> <p>Then, I changed one of the innermost values:</p> <pre><code>xs[0][0] = 5 # xs == [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]] </code></pre> <p>Why did every first element of each sublist change to <code>5</code>?</p>
<p>When you write <code>[x]*3</code> you get, essentially, the list <code>[x, x, x]</code>. That is, a list with 3 references to the same <code>x</code>. When you then modify this single <code>x</code> it is visible via all three references to it:</p> <pre><code>x = [1] * 4 xs = [x] * 3 print(f&quot;id(x): {id(x)}&quot;) # id(x): 140560897920048 print( f&quot;id(xs[0]): {id(xs[0])}\n&quot; f&quot;id(xs[1]): {id(xs[1])}\n&quot; f&quot;id(xs[2]): {id(xs[2])}&quot; ) # id(xs[0]): 140560897920048 # id(xs[1]): 140560897920048 # id(xs[2]): 140560897920048 x[0] = 42 print(f&quot;x: {x}&quot;) # x: [42, 1, 1, 1] print(f&quot;xs: {xs}&quot;) # xs: [[42, 1, 1, 1], [42, 1, 1, 1], [42, 1, 1, 1]] </code></pre> <p>To fix it, you need to make sure that you create a new list at each position. One way to do it is</p> <pre><code>[[1]*4 for _ in range(3)] </code></pre> <p>which will reevaluate <code>[1]*4</code> each time instead of evaluating it once and making 3 references to 1 list.</p> <hr /> <p>You might wonder why <code>*</code> can't make independent objects the way the list comprehension does. That's because the multiplication operator <code>*</code> operates on objects, without seeing expressions. When you use <code>*</code> to multiply <code>[[1] * 4]</code> by 3, <code>*</code> only sees the 1-element list <code>[[1] * 4]</code> evaluates to, not the <code>[[1] * 4</code> expression text. <code>*</code> has no idea how to make copies of that element, no idea how to reevaluate <code>[[1] * 4]</code>, and no idea you even want copies, and in general, there might not even be a way to copy the element.</p> <p>The only option <code>*</code> has is to make new references to the existing sublist instead of trying to make new sublists. Anything else would be inconsistent or require major redesigning of fundamental language design decisions.</p> <p>In contrast, a list comprehension reevaluates the element expression on every iteration. <code>[[1] * 4 for n in range(3)]</code> reevaluates <code>[1] * 4</code> every time for the same reason <code>[x**2 for x in range(3)]</code> reevaluates <code>x**2</code> every time. Every evaluation of <code>[1] * 4</code> generates a new list, so the list comprehension does what you wanted.</p> <p>Incidentally, <code>[1] * 4</code> also doesn't copy the elements of <code>[1]</code>, but that doesn't matter, since integers are immutable. You can't do something like <code>1.value = 2</code> and turn a 1 into a 2.</p>
{ "question_id": 240178, "question_date": "2008-10-27T14:57:22.883Z", "question_score": 885, "tags": "python|list|nested-lists|mutable", "answer_id": 240205, "answer_date": "2008-10-27T15:03:30.080Z", "answer_score": 760 }
Please answer the following Stack Overflow question: Title: If a folder does not exist, create it <p>I use a <code>FileUploader</code> control in my application. I want to save a file to a specified folder. If this folder does not exist, I want to first create it, and then save my file to this folder. If the folder already exists, then just save the file in it.</p> <p>How can I do this?</p>
<p>As others have said, use <a href="https://docs.microsoft.com/en-us/dotnet/api/system.io.directory.createdirectory" rel="noreferrer"><code>System.IO.Directory.CreateDirectory</code></a>.</p> <p>But, you don't need to check if it exists first. From <a href="https://docs.microsoft.com/en-us/dotnet/api/system.io.directory.createdirectory" rel="noreferrer">the documentation</a>:</p> <blockquote> <p>Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. If the directory already exists, this method does not create a new directory, but it returns a DirectoryInfo object for the existing directory.</p> </blockquote>
{ "question_id": 9065598, "question_date": "2012-01-30T14:42:14.843Z", "question_score": 884, "tags": "c#|asp.net|directory", "answer_id": 9065716, "answer_date": "2012-01-30T14:49:41.863Z", "answer_score": 1453 }
Please answer the following Stack Overflow question: Title: How can you check for a #hash in a URL using JavaScript? <p>I have some jQuery/JavaScript code that I want to run only when there is a hash (<code>#</code>) anchor link in a URL. How can you check for this character using JavaScript? I need a simple catch-all test that would detect URLs like these:</p> <ul> <li><code>example.com/page.html#anchor</code></li> <li><code>example.com/page.html#anotheranchor</code></li> </ul> <p>Basically something along the lines of:</p> <pre><code>if (thereIsAHashInTheUrl) { do this; } else { do this; } </code></pre>
<p>Simple use of <a href="https://developer.mozilla.org/en-US/docs/Web/API/Location/hash" rel="noreferrer">location hash</a>:</p> <pre><code>if(window.location.hash) { // Fragment exists } else { // Fragment doesn't exist } </code></pre>
{ "question_id": 298503, "question_date": "2008-11-18T11:35:02.087Z", "question_score": 884, "tags": "javascript|jquery|anchor|fragment-identifier", "answer_id": 298513, "answer_date": "2008-11-18T11:37:00.617Z", "answer_score": 1578 }
Please answer the following Stack Overflow question: Title: How to make a new List in Java <p>We create a <code>Set</code> as:</p> <pre><code>Set myset = new HashSet() </code></pre> <p>How do we create a <code>List</code> in Java?</p>
<pre><code>List myList = new ArrayList(); </code></pre> <p>or with generics (<a href="https://docs.oracle.com/javase/tutorial/java/generics/types.html#diamond" rel="noreferrer">Java 7</a> or later)</p> <pre><code>List&lt;MyType&gt; myList = new ArrayList&lt;&gt;(); </code></pre> <p>or with generics (Old java versions)</p> <pre><code>List&lt;MyType&gt; myList = new ArrayList&lt;MyType&gt;(); </code></pre>
{ "question_id": 858572, "question_date": "2009-05-13T15:12:45.443Z", "question_score": 883, "tags": "java|list|collections", "answer_id": 858590, "answer_date": "2009-05-13T15:15:38.997Z", "answer_score": 1130 }
Please answer the following Stack Overflow question: Title: How can I SELECT rows with MAX(Column value), PARTITION by another column in MYSQL? <p>I have a table of player performance:</p> <pre><code>CREATE TABLE TopTen ( id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT, home INT UNSIGNED NOT NULL, `datetime`DATETIME NOT NULL, player VARCHAR(6) NOT NULL, resource INT NOT NULL ); </code></pre> <p>What query will return the rows for each distinct <code>home</code> holding its maximum value of <code>datetime</code>? In other words, how can I filter by the maximum <code>datetime</code> (grouped by <code>home</code>) and still include other non-grouped, non-aggregate columns (such as <code>player</code>) in the result?</p> <p>For this sample data:</p> <pre><code>INSERT INTO TopTen (id, home, `datetime`, player, resource) VALUES (1, 10, '04/03/2009', 'john', 399), (2, 11, '04/03/2009', 'juliet', 244), (5, 12, '04/03/2009', 'borat', 555), (3, 10, '03/03/2009', 'john', 300), (4, 11, '03/03/2009', 'juliet', 200), (6, 12, '03/03/2009', 'borat', 500), (7, 13, '24/12/2008', 'borat', 600), (8, 13, '01/01/2009', 'borat', 700) ; </code></pre> <p>the result should be:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th>id</th> <th>home</th> <th>datetime</th> <th>player</th> <th>resource</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>10</td> <td>04/03/2009</td> <td>john</td> <td>399</td> </tr> <tr> <td>2</td> <td>11</td> <td>04/03/2009</td> <td>juliet</td> <td>244</td> </tr> <tr> <td>5</td> <td>12</td> <td>04/03/2009</td> <td>borat</td> <td>555</td> </tr> <tr> <td>8</td> <td>13</td> <td>01/01/2009</td> <td>borat</td> <td>700</td> </tr> </tbody> </table> </div> <p>I tried a subquery getting the maximum <code>datetime</code> for each <code>home</code>:</p> <pre><code>-- 1 ..by the MySQL manual: SELECT DISTINCT home, id, datetime AS dt, player, resource FROM TopTen t1 WHERE `datetime` = (SELECT MAX(t2.datetime) FROM TopTen t2 GROUP BY home) GROUP BY `datetime` ORDER BY `datetime` DESC </code></pre> <p>The result-set has 130 rows although database holds 187, indicating the result includes some duplicates of <code>home</code>.</p> <p>Then I tried joining to a subquery that gets the maximum <code>datetime</code> for each row <code>id</code>:</p> <pre><code>-- 2 ..join SELECT s1.id, s1.home, s1.datetime, s1.player, s1.resource FROM TopTen s1 JOIN (SELECT id, MAX(`datetime`) AS dt FROM TopTen GROUP BY id) AS s2 ON s1.id = s2.id ORDER BY `datetime` </code></pre> <p>Nope. Gives all the records.</p> <p>I tried various exotic queries, each with various results, but nothing that got me any closer to solving this problem.</p>
<p>You are so close! All you need to do is select BOTH the home and its max date time, then join back to the <code>topten</code> table on BOTH fields:</p> <pre><code>SELECT tt.* FROM topten tt INNER JOIN (SELECT home, MAX(datetime) AS MaxDateTime FROM topten GROUP BY home) groupedtt ON tt.home = groupedtt.home AND tt.datetime = groupedtt.MaxDateTime </code></pre>
{ "question_id": 612231, "question_date": "2009-03-04T20:14:26.573Z", "question_score": 883, "tags": "mysql|sql|max|distinct|greatest-n-per-group", "answer_id": 612268, "answer_date": "2009-03-04T20:22:47.270Z", "answer_score": 1082 }
Please answer the following Stack Overflow question: Title: How to access POST form fields in Express <p>Here is my simple form:</p> <pre class="lang-html prettyprint-override"><code>&lt;form id="loginformA" action="userlogin" method="post"&gt; &lt;div&gt; &lt;label for="email"&gt;Email: &lt;/label&gt; &lt;input type="text" id="email" name="email"&gt;&lt;/input&gt; &lt;/div&gt; &lt;input type="submit" value="Submit"&gt;&lt;/input&gt; &lt;/form&gt; </code></pre> <p>Here is my <a href="https://en.wikipedia.org/wiki/Express.js">Express.js</a>/Node.js code:</p> <pre><code>app.post('/userlogin', function(sReq, sRes){ var email = sReq.query.email.; } </code></pre> <p>I tried <code>sReq.query.email</code> or <code>sReq.query['email']</code> or <code>sReq.params['email']</code>, etc. None of them work. They all return <code>undefined</code>. </p> <p>When I change to a Get call, it works, so .. any idea?</p>
<p>Things have <a href="https://expressjs.com/en/changelog/4x.html#4.16.0" rel="noreferrer">changed</a> once again starting <strong>Express 4.16.0</strong>, you can now use <code>express.json()</code> and <code>express.urlencoded()</code> just like in <strong>Express 3.0</strong>.</p> <p>This was <a href="https://github.com/senchalabs/connect#middleware" rel="noreferrer">different</a> starting <strong>Express 4.0 to 4.15</strong>:</p> <pre><code>$ npm install --save body-parser </code></pre> <p>and then:</p> <pre><code>var bodyParser = require('body-parser') app.use( bodyParser.json() ); // to support JSON-encoded bodies app.use(bodyParser.urlencoded({ // to support URL-encoded bodies extended: true })); </code></pre> <p>The rest is like in <strong>Express 3.0</strong>:</p> <p>Firstly you need to add some middleware to parse the post data of the body.</p> <p>Add one or both of the following lines of code:</p> <pre><code>app.use(express.json()); // to support JSON-encoded bodies app.use(express.urlencoded()); // to support URL-encoded bodies </code></pre> <p>Then, in your handler, use the <a href="http://expressjs.com/api.html#req.body" rel="noreferrer"><code>req.body</code></a> object:</p> <pre><code>// assuming POST: name=foo&amp;color=red &lt;-- URL encoding // // or POST: {&quot;name&quot;:&quot;foo&quot;,&quot;color&quot;:&quot;red&quot;} &lt;-- JSON encoding app.post('/test-page', function(req, res) { var name = req.body.name, color = req.body.color; // ... }); </code></pre> <hr /> <p>Note that the use of <a href="http://expressjs.com/api.html#bodyParser" rel="noreferrer"><code>express.bodyParser()</code></a> is not recommended.</p> <pre><code>app.use(express.bodyParser()); </code></pre> <p>...is equivalent to:</p> <pre><code>app.use(express.json()); app.use(express.urlencoded()); app.use(express.multipart()); </code></pre> <p>Security concerns exist with <code>express.multipart()</code>, and so it is better to explicitly add support for the specific encoding type(s) you require. If you do need multipart encoding (to support uploading files for example) then you should <a href="https://groups.google.com/forum/#!msg/express-js/iP2VyhkypHo/5AXQiYN3RPcJ" rel="noreferrer">read this</a>.</p>
{ "question_id": 5710358, "question_date": "2011-04-19T00:38:39.310Z", "question_score": 883, "tags": "javascript|node.js|post|express", "answer_id": 12008719, "answer_date": "2012-08-17T15:30:04.163Z", "answer_score": 1366 }
Please answer the following Stack Overflow question: Title: How to call a method after a delay in Android <p>I want to be able to call the following method after a specified delay. In objective c there was something like:</p> <pre><code>[self performSelector:@selector(DoSomething) withObject:nil afterDelay:5]; </code></pre> <p>Is there an equivalent of this method in android with java? For example I need to be able to call a method after 5 seconds.</p> <pre><code>public void DoSomething() { //do something here } </code></pre>
<h3>Kotlin</h3> <pre class="lang-kotlin prettyprint-override"><code>Handler(Looper.getMainLooper()).postDelayed({ //Do something after 100ms }, 100) </code></pre> <br> <h3>Java</h3> <pre class="lang-java prettyprint-override"><code>final Handler handler = new Handler(Looper.getMainLooper()); handler.postDelayed(new Runnable() { @Override public void run() { //Do something after 100ms } }, 100); </code></pre> <br>
{ "question_id": 3072173, "question_date": "2010-06-18T18:24:19.197Z", "question_score": 883, "tags": "java|android|handler|delay", "answer_id": 9166354, "answer_date": "2012-02-06T19:55:23.557Z", "answer_score": 2133 }
Please answer the following Stack Overflow question: Title: Use grep --exclude/--include syntax to not grep through certain files <p>I'm looking for the string <code>foo=</code> in text files in a directory tree. It's on a common Linux machine, I have bash shell:</p> <pre><code>grep -ircl &quot;foo=&quot; * </code></pre> <p>In the directories are also many binary files which match <code>&quot;foo=&quot;</code>. As these results are not relevant and slow down the search, I want grep to skip searching these files (mostly JPEG and PNG images). How would I do that?</p> <p>I know there are the <code>--exclude=PATTERN</code> and <code>--include=PATTERN</code> options, but what is the pattern format? The man page of grep says:</p> <pre><code>--include=PATTERN Recurse in directories only searching file matching PATTERN. --exclude=PATTERN Recurse in directories skip file matching PATTERN. </code></pre> <p>Searching on <em>grep include</em>, <em>grep include exclude</em>, <em>grep exclude</em> and variants did not find anything relevant</p> <p>If there's a better way of grepping only in certain files, I'm all for it; moving the offending files is not an option. I can't search only certain directories (the directory structure is a big mess, with everything everywhere). Also, I can't install anything, so I have to do with common tools (like <em>grep</em> or the suggested <em>find</em>).</p>
<p>Use the shell <a href="https://man7.org/linux/man-pages/man7/glob.7.html" rel="noreferrer">globbing syntax</a>:</p> <pre><code>grep pattern -r --include=\*.cpp --include=\*.h rootdir </code></pre> <p>The syntax for <code>--exclude</code> is identical.</p> <p>Note that the star is escaped with a backslash to prevent it from being expanded by the shell (quoting it, such as <code>--include=&quot;*.cpp&quot;</code>, would work just as well). Otherwise, if you had any files in the current working directory that matched the pattern, the command line would expand to something like <code>grep pattern -r --include=foo.cpp --include=bar.cpp rootdir</code>, which would only search files named <code>foo.cpp</code> and <code>bar.cpp</code>, which is quite likely not what you wanted.</p> <p><strong>Update 2021-03-04</strong></p> <p>I've edited the original answer to remove the use of <a href="https://www.gnu.org/software/bash/manual/bash.html#Brace-Expansion" rel="noreferrer">brace expansion</a>, which is a feature provided by several shells such as Bash and zsh to simplify patterns like this; but note that brace expansion is not POSIX shell-compliant.</p> <p>The original example was:</p> <pre><code>grep pattern -r --include=\*.{cpp,h} rootdir </code></pre> <p>to search through all <code>.cpp</code> and <code>.h</code> files rooted in the directory <code>rootdir</code>.</p>
{ "question_id": 221921, "question_date": "2008-10-21T13:41:01.673Z", "question_score": 883, "tags": "unix|search|shell|command-line|grep", "answer_id": 221929, "answer_date": "2008-10-21T13:44:01.793Z", "answer_score": 895 }
Please answer the following Stack Overflow question: Title: Removing input background colour for Chrome autocomplete? <p>On a form I'm working on, Chrome is auto-filling the email and password fields. This is fine, however, Chrome changes the background colour to a pale yellow colour.</p> <p>The design I'm working on is using light text on a dark background, so this really messes up the look of the form - I have stark yellow boxes and near-invisible white text. Once the field is focused, the fields return to normal.</p> <p>Is it possible to stop Chrome changing the colour of these fields?</p>
<p>You can change input box styles as well as text styles inside <code>input</code> box:</p> <p>Here you can use any color e.g. <code>white</code>, <code>#DDD</code>, <code>rgba(102, 163, 177, 0.45)</code>.</p> <p>But <code>transparent</code> won't work here.</p> <pre class="lang-css prettyprint-override"><code>/* Change the white to any color */ input:-webkit-autofill, input:-webkit-autofill:hover, input:-webkit-autofill:focus, input:-webkit-autofill:active{ -webkit-box-shadow: 0 0 0 30px white inset !important; } </code></pre> <p>Additionally, you can use this to change the text color:</p> <pre class="lang-css prettyprint-override"><code>/*Change text in autofill textbox*/ input:-webkit-autofill{ -webkit-text-fill-color: yellow !important; } </code></pre> <p><strong>Advice:</strong> Don't use an excessive blur radius in the hundreds or thousands. This has no benefit and might put processor load on weaker mobile devices. (Also true for actual, outside shadows). For a normal input box of 20px height, 30px ‘blur radius’ will perfectly cover it.</p>
{ "question_id": 2781549, "question_date": "2010-05-06T13:36:48.070Z", "question_score": 882, "tags": "autocomplete|input|google-chrome", "answer_id": 14205976, "answer_date": "2013-01-07T23:35:53.633Z", "answer_score": 1494 }
Please answer the following Stack Overflow question: Title: Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference <p>Given the following examples, why is <code>outerScopeVar</code> undefined in all cases?</p> <pre><code>var outerScopeVar; var img = document.createElement('img'); img.onload = function() { outerScopeVar = this.width; }; img.src = 'lolcat.png'; alert(outerScopeVar); </code></pre> <pre><code>var outerScopeVar; setTimeout(function() { outerScopeVar = 'Hello Asynchronous World!'; }, 0); alert(outerScopeVar); </code></pre> <pre><code>// Example using some jQuery var outerScopeVar; $.post('loldog', function(response) { outerScopeVar = response; }); alert(outerScopeVar); </code></pre> <pre><code>// Node.js example var outerScopeVar; fs.readFile('./catdog.html', function(err, data) { outerScopeVar = data; }); console.log(outerScopeVar); </code></pre> <pre><code>// with promises var outerScopeVar; myPromise.then(function (response) { outerScopeVar = response; }); console.log(outerScopeVar); </code></pre> <pre><code>// with observables var outerScopeVar; myObservable.subscribe(function (value) { outerScopeVar = value; }); console.log(outerScopeVar); </code></pre> <pre><code>// geolocation API var outerScopeVar; navigator.geolocation.getCurrentPosition(function (pos) { outerScopeVar = pos; }); console.log(outerScopeVar); </code></pre> <p>Why does it output <code>undefined</code> in all of these examples? I don't want workarounds, I want to know <strong>why</strong> this is happening.</p> <hr> <blockquote> <p><strong>Note:</strong> This is a canonical question for <em>JavaScript asynchronicity</em>. Feel free to improve this question and add more simplified examples which the community can identify with.</p> </blockquote>
<p>One word answer: <strong>asynchronicity</strong>.</p> <h2>Forewords</h2> <p>This topic has been iterated at least a couple of thousands of times, here, in Stack Overflow. Hence, first off I'd like to point out some extremely useful resources:</p> <ul> <li><p><a href="https://stackoverflow.com/a/14220323/1331430">@Felix Kling's answer to "How do I return the response from an asynchronous call?"</a>. See his excellent answer explaining synchronous and asynchronous flows, as well as the "Restructure code" section.<br> @Benjamin Gruenbaum has also put a lot of effort explaining asynchronicity in the same thread.</p></li> <li><p><a href="https://stackoverflow.com/a/10058879/1331430">@Matt Esch's answer to "Get data from fs.readFile"</a> also explains asynchronicity extremely well in a simple manner.</p></li> </ul> <hr> <h2>The answer to the question at hand</h2> <p>Let's trace the common behavior first. In all examples, the <code>outerScopeVar</code> is modified inside of a <em>function</em>. That function is clearly not executed immediately, it is being assigned or passed as an argument. That is what we call a <strong><em>callback</em></strong>.</p> <p>Now the question is, when is that callback called?</p> <p>It depends on the case. Let's try to trace some common behavior again:</p> <ul> <li><code>img.onload</code> may be called <em>sometime in the future</em>, when (and if) the image has successfully loaded.</li> <li><code>setTimeout</code> may be called <em>sometime in the future</em>, after the delay has expired and the timeout hasn't been canceled by <code>clearTimeout</code>. Note: even when using <code>0</code> as delay, all browsers have a minimum timeout delay cap (specified to be 4ms in the HTML5 spec).</li> <li>jQuery <code>$.post</code>'s callback may be called <em>sometime in the future</em>, when (and if) the Ajax request has been completed successfully.</li> <li>Node.js's <code>fs.readFile</code> may be called <em>sometime in the future</em>, when the file has been read successfully or thrown an error.</li> </ul> <p>In all cases, we have a callback which may run <em>sometime in the future</em>. This "sometime in the future" is what we refer to as <strong>asynchronous flow</strong>.</p> <p>Asynchronous execution is pushed out of the synchronous flow. That is, the asynchronous code will <strong>never</strong> execute while the synchronous code stack is executing. This is the meaning of JavaScript being single-threaded.</p> <p>More specifically, when the JS engine is idle -- not executing a stack of (a)synchronous code -- it will poll for events that may have triggered asynchronous callbacks (e.g. expired timeout, received network response) and execute them one after another. This is regarded as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop" rel="noreferrer">Event Loop</a>.</p> <p>That is, the asynchronous code highlighted in the hand-drawn red shapes may execute only after all the remaining synchronous code in their respective code blocks have executed:</p> <p><img src="https://i.stack.imgur.com/40IwM.png" alt="async code highlighted"></p> <p>In short, the callback functions are created synchronously but executed asynchronously. You just can't rely on the execution of an asynchronous function until you know it has executed, and how to do that?</p> <p>It is simple, really. The logic that depends on the asynchronous function execution should be started/called from inside this asynchronous function. For example, moving the <code>alert</code>s and <code>console.log</code>s too inside the callback function would output the expected result, because the result is available at that point.</p> <h3>Implementing your own callback logic</h3> <p>Often you need to do more things with the result from an asynchronous function or do different things with the result depending on where the asynchronous function has been called. Let's tackle a bit more complex example:</p> <pre><code>var outerScopeVar; helloCatAsync(); alert(outerScopeVar); function helloCatAsync() { setTimeout(function() { outerScopeVar = 'Nya'; }, Math.random() * 2000); } </code></pre> <p><strong>Note:</strong> I'm using <code>setTimeout</code> with a random delay as a generic asynchronous function, the same example applies to Ajax, <code>readFile</code>, <code>onload</code> and any other asynchronous flow.</p> <p>This example clearly suffers from the same issue as the other examples, it is not waiting until the asynchronous function executes.</p> <p>Let's tackle it implementing a callback system of our own. First off, we get rid of that ugly <code>outerScopeVar</code> which is completely useless in this case. Then we add a parameter which accepts a function argument, our callback. When the asynchronous operation finishes, we call this callback passing the result. The implementation (please read the comments in order):</p> <pre><code>// 1. Call helloCatAsync passing a callback function, // which will be called receiving the result from the async operation helloCatAsync(function(result) { // 5. Received the result from the async function, // now do whatever you want with it: alert(result); }); // 2. The "callback" parameter is a reference to the function which // was passed as argument from the helloCatAsync call function helloCatAsync(callback) { // 3. Start async operation: setTimeout(function() { // 4. Finished async operation, // call the callback passing the result as argument callback('Nya'); }, Math.random() * 2000); } </code></pre> <p>Code snippet of the above example:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// 1. Call helloCatAsync passing a callback function, // which will be called receiving the result from the async operation console.log("1. function called...") helloCatAsync(function(result) { // 5. Received the result from the async function, // now do whatever you want with it: console.log("5. result is: ", result); }); // 2. The "callback" parameter is a reference to the function which // was passed as argument from the helloCatAsync call function helloCatAsync(callback) { console.log("2. callback here is the function passed as argument above...") // 3. Start async operation: setTimeout(function() { console.log("3. start async operation...") console.log("4. finished async operation, calling the callback, passing the result...") // 4. Finished async operation, // call the callback passing the result as argument callback('Nya'); }, Math.random() * 2000); }</code></pre> </div> </div> </p> <p>Most often in real use cases, the DOM API and most libraries already provide the callback functionality (the <code>helloCatAsync</code> implementation in this demonstrative example). You only need to pass the callback function and understand that it will execute out of the synchronous flow, and restructure your code to accommodate for that.</p> <p>You will also notice that due to the asynchronous nature, it is impossible to <code>return</code> a value from an asynchronous flow back to the synchronous flow where the callback was defined, as the asynchronous callbacks are executed long after the synchronous code has already finished executing.</p> <p>Instead of <code>return</code>ing a value from an asynchronous callback, you will have to make use of the callback pattern, or... Promises.</p> <h3>Promises</h3> <p>Although there are ways to keep the <a href="http://callbackhell.com/" rel="noreferrer">callback hell</a> at bay with vanilla JS, promises are growing in popularity and are currently being standardized in ES6 (see <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise" rel="noreferrer">Promise - MDN</a>).</p> <p>Promises (a.k.a. Futures) provide a more linear, and thus pleasant, reading of the asynchronous code, but explaining their entire functionality is out of the scope of this question. Instead, I'll leave these excellent resources for the interested:</p> <ul> <li><a href="http://www.html5rocks.com/en/tutorials/es6/promises/" rel="noreferrer">JavaScript Promises - HTML5 Rocks</a></li> <li><a href="http://domenic.me/2012/10/14/youre-missing-the-point-of-promises/" rel="noreferrer">You're Missing the Point of Promises - domenic.me</a></li> </ul> <hr> <h3>More reading material about JavaScript asynchronicity</h3> <ul> <li><a href="https://github.com/maxogden/art-of-node#callbacks" rel="noreferrer">The Art of Node - Callbacks</a> explains asynchronous code and callbacks very well with vanilla JS examples and Node.js code as well.</li> </ul> <hr> <blockquote> <p><strong>Note:</strong> I've marked this answer as Community Wiki, hence anyone with at least 100 reputations can edit and improve it! Please feel free to improve this answer, or submit a completely new answer if you'd like as well.</p> <p>I want to turn this question into a canonical topic to answer asynchronicity issues which are unrelated to Ajax (there is <a href="https://stackoverflow.com/q/14220321/1331430">How to return the response from an AJAX call?</a> for that), hence this topic needs your help to be as good and helpful as possible!</p> </blockquote>
{ "question_id": 23667086, "question_date": "2014-05-14T23:55:16.930Z", "question_score": 882, "tags": "javascript|asynchronous", "answer_id": 23667087, "answer_date": "2014-05-14T23:55:16.930Z", "answer_score": 697 }
Please answer the following Stack Overflow question: Title: Self-references in object literals / initializers <p>Is there any way to get something like the following to work in JavaScript?</p> <pre><code>var foo = { a: 5, b: 6, c: this.a + this.b // Doesn't work }; </code></pre> <p>In the current form, this code obviously throws a reference error since <code>this</code> doesn't refer to <code>foo</code>. But <em>is</em> there any way to have values in an object literal's properties depend on other properties declared earlier?</p>
<p>Well, the only thing that I can tell you about are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get" rel="noreferrer">getter</a>:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var foo = { a: 5, b: 6, get c() { return this.a + this.b; } } console.log(foo.c) // 11</code></pre> </div> </div> </p> <p>This is a syntactic extension introduced by the ECMAScript 5th Edition Specification, the syntax is supported by most modern browsers (including IE9).</p>
{ "question_id": 4616202, "question_date": "2011-01-06T14:53:53.263Z", "question_score": 882, "tags": "javascript|object-literal", "answer_id": 4616262, "answer_date": "2011-01-06T14:58:54.997Z", "answer_score": 966 }
Please answer the following Stack Overflow question: Title: android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData() <p>The app is crashing when I'm trying to open a file. It works below Android Nougat, but on Android Nougat it crashes. It only crashes when I try to open a file from the SD card, not from the system partition. Some permission problem?</p> <p>Sample code:</p> <pre><code>File file = new File("/storage/emulated/0/test.txt"); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "text/*"); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); // Crashes on this line </code></pre> <p>Log: </p> <blockquote> <p>android.os.FileUriExposedException: file:///storage/emulated/0/test.txt exposed beyond app through Intent.getData()</p> </blockquote> <p><strong>Edit:</strong></p> <p>When targeting Android Nougat, <code>file://</code> URIs are not allowed anymore. We should use <code>content://</code> URIs instead. However, my app needs to open files in root directories. Any ideas?</p>
<p>If your <code>targetSdkVersion &gt;= 24</code>, then we have to use <code>FileProvider</code> class to give access to the particular file or folder to make them accessible for other apps. We create our own class inheriting <code>FileProvider</code> in order to make sure our FileProvider doesn't conflict with FileProviders declared in imported dependencies as described <a href="https://commonsware.com/blog/2017/06/27/fileprovider-libraries.html" rel="noreferrer">here</a>.</p> <p>Steps to replace <code>file://</code> URI with <code>content://</code> URI:</p> <ul> <li>Add a FileProvider <code>&lt;provider&gt;</code> tag in <code>AndroidManifest.xml</code> under <code>&lt;application&gt;</code> tag. Specify a unique authority for the <code>android:authorities</code> attribute to avoid conflicts, imported dependencies might specify <code>${applicationId}.provider</code> and other commonly used authorities.</li> </ul> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; ... &lt;application ... &lt;provider android:name=&quot;androidx.core.content.FileProvider&quot; android:authorities=&quot;${applicationId}.provider&quot; android:exported=&quot;false&quot; android:grantUriPermissions=&quot;true&quot;&gt; &lt;meta-data android:name=&quot;android.support.FILE_PROVIDER_PATHS&quot; android:resource=&quot;@xml/provider_paths&quot; /&gt; &lt;/provider&gt; &lt;/application&gt; &lt;/manifest&gt; </code></pre> <ul> <li>Then create a <code>provider_paths.xml</code> file in <code>res/xml</code> folder. A folder may be needed to be created if it doesn't exist yet. The content of the file is shown below. It describes that we would like to share access to the External Storage at root folder <code>(path=&quot;.&quot;)</code> with the name <strong>external_files</strong>.</li> </ul> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;paths&gt; &lt;external-path name=&quot;external_files&quot; path=&quot;.&quot;/&gt; &lt;/paths&gt; </code></pre> <ul> <li><p>The final step is to change the line of code below in</p> <pre><code> Uri photoURI = Uri.fromFile(createImageFile()); </code></pre> <p>to</p> <pre><code> Uri photoURI = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + &quot;.provider&quot;, createImageFile()); </code></pre> </li> <li><p><strong>Edit:</strong> If you're using an intent to make the system open your file, you may need to add the following line of code:</p> <pre><code> intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); </code></pre> </li> </ul> <p>Please refer to the full code and solution that have been explained <a href="https://inthecheesefactory.com/blog/how-to-share-access-to-file-with-fileprovider-on-android-nougat/en" rel="noreferrer">here.</a></p>
{ "question_id": 38200282, "question_date": "2016-07-05T09:51:40.530Z", "question_score": 881, "tags": "android|android-file|android-7.0-nougat", "answer_id": 38858040, "answer_date": "2016-08-09T18:33:21.063Z", "answer_score": 1575 }
Please answer the following Stack Overflow question: Title: How do you implement a Stack and a Queue in JavaScript? <p>What is the best way to implement a Stack and a Queue in JavaScript?</p> <p>I'm looking to do the shunting-yard algorithm and I'm going to need these data-structures.</p>
<pre class="lang-js prettyprint-override"><code>var stack = []; stack.push(2); // stack is now [2] stack.push(5); // stack is now [2, 5] var i = stack.pop(); // stack is now [2] alert(i); // displays 5 var queue = []; queue.push(2); // queue is now [2] queue.push(5); // queue is now [2, 5] var i = queue.shift(); // queue is now [5] alert(i); // displays 2 </code></pre> <p>taken from &quot;<a href="https://www.chevtek.io/9-javascript-tips-you-may-not-know/#stack" rel="noreferrer">9 JavaScript Tips You May Not Know</a>&quot;</p>
{ "question_id": 1590247, "question_date": "2009-10-19T18:15:53.917Z", "question_score": 881, "tags": "javascript|data-structures|stack|queue", "answer_id": 1590262, "answer_date": "2009-10-19T18:19:09.153Z", "answer_score": 1603 }
Please answer the following Stack Overflow question: Title: How to check if PHP array is associative or sequential? <p>PHP treats all arrays as associative, so there aren't any built in functions. Can anyone recommend a fairly efficient way to check if an array <em>&quot;is a list&quot;</em> (contains only numeric keys starting from 0)?</p> <p>Basically, I want to be able to differentiate between this:</p> <pre><code>$sequentialArray = [ 'apple', 'orange', 'tomato', 'carrot' ]; </code></pre> <p>and this:</p> <pre><code>$assocArray = [ 'fruit1' =&gt; 'apple', 'fruit2' =&gt; 'orange', 'veg1' =&gt; 'tomato', 'veg2' =&gt; 'carrot' ]; </code></pre>
<p>You have asked two questions that are not quite equivalent:</p> <ul> <li>Firstly, how to determine whether an array has only numeric keys</li> <li>Secondly, how to determine whether an array has <em>sequential</em> numeric keys, starting from 0</li> </ul> <p>Consider which of these behaviours you actually need. (It may be that either will do for your purposes.)</p> <p>The first question (simply checking that all keys are numeric) is <a href="https://stackoverflow.com/a/4254008/1709587">answered well by Captain kurO</a>.</p> <p>For the second question (checking whether the array is zero-indexed and sequential), you can use the following function:</p> <pre class="lang-php prettyprint-override"><code>function isAssoc(array $arr) { if (array() === $arr) return false; return array_keys($arr) !== range(0, count($arr) - 1); } var_dump(isAssoc(['a', 'b', 'c'])); // false var_dump(isAssoc(["0" =&gt; 'a', "1" =&gt; 'b', "2" =&gt; 'c'])); // false var_dump(isAssoc(["1" =&gt; 'a', "0" =&gt; 'b', "2" =&gt; 'c'])); // true var_dump(isAssoc(["a" =&gt; 'a', "b" =&gt; 'b', "c" =&gt; 'c'])); // true </code></pre>
{ "question_id": 173400, "question_date": "2008-10-06T07:01:13.140Z", "question_score": 881, "tags": "php|arrays", "answer_id": 173479, "answer_date": "2008-10-06T07:36:26.533Z", "answer_score": 728 }
Please answer the following Stack Overflow question: Title: How to remove text from a string? <p>I've got a <code>data-123</code> string.</p> <p>How can I remove <code>data-</code> from the string while leaving the <code>123</code>?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var ret = "data-123".replace('data-',''); console.log(ret); //prints: 123</code></pre> </div> </div> </p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace" rel="noreferrer">Docs.</a></p> <hr> <p>For all occurrences to be discarded use:</p> <pre><code>var ret = "data-123".replace(/data-/g,''); </code></pre> <p>PS: The replace function returns a new string and leaves the original string unchanged, so use the function return value after the replace() call.</p>
{ "question_id": 10398931, "question_date": "2012-05-01T14:12:38.847Z", "question_score": 879, "tags": "javascript|string", "answer_id": 10398941, "answer_date": "2012-05-01T14:14:00.627Z", "answer_score": 1696 }
Please answer the following Stack Overflow question: Title: Shuffling a list of objects <p>How do I shuffle a list of objects? I tried <a href="https://docs.python.org/library/random.html#random.shuffle" rel="nofollow noreferrer"><code>random.shuffle</code></a>:</p> <pre><code>import random b = [object(), object()] print(random.shuffle(b)) </code></pre> <p>But it outputs:</p> <pre><code>None </code></pre>
<p><a href="https://docs.python.org/library/random.html#random.shuffle" rel="noreferrer"><code>random.shuffle</code></a> should work. Here's an example, where the objects are lists:</p> <pre><code>from random import shuffle x = [[i] for i in range(10)] shuffle(x) print(x) # print(x) gives [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]] </code></pre> <p>Note that <code>shuffle</code> works <strong>in place</strong>, and returns <code>None</code>.</p> <p>More generally in Python, mutable objects can be passed into functions, and when a function mutates those objects, the standard is to return <code>None</code> (rather than, say, the mutated object).</p>
{ "question_id": 976882, "question_date": "2009-06-10T16:56:59.503Z", "question_score": 879, "tags": "python|list|random|shuffle", "answer_id": 976918, "answer_date": "2009-06-10T17:03:37.447Z", "answer_score": 1393 }
Please answer the following Stack Overflow question: Title: Identify if a string is a number <p>If I have these strings:</p> <ol> <li><p><code>"abc"</code> = <code>false</code></p></li> <li><p><code>"123"</code> = <code>true</code></p></li> <li><p><code>"ab2"</code> = <code>false</code></p></li> </ol> <p>Is there a command, like <code>IsNumeric()</code> or something else, that can identify if a string is a valid number?</p>
<pre><code>int n; bool isNumeric = int.TryParse("123", out n); </code></pre> <p><strong>Update</strong> As of C# 7:</p> <pre><code>var isNumeric = int.TryParse("123", out int n); </code></pre> <p>or if you don't need the number you can <a href="https://docs.microsoft.com/en-us/dotnet/csharp/discards" rel="noreferrer">discard</a> the out parameter</p> <pre><code>var isNumeric = int.TryParse("123", out _); </code></pre> <p>The <em>var</em> s can be replaced by their respective types!</p>
{ "question_id": 894263, "question_date": "2009-05-21T18:06:27.297Z", "question_score": 878, "tags": "c#|string|parsing|isnumeric", "answer_id": 894271, "answer_date": "2009-05-21T18:08:47.260Z", "answer_score": 1429 }
Please answer the following Stack Overflow question: Title: Convert date to datetime in Python <p>Is there a built-in method for converting a <code>date</code> to a <code>datetime</code> in Python, for example getting the <code>datetime</code> for the midnight of the given date? The opposite conversion is easy: <code>datetime</code> has a <code>.date()</code> method.</p> <p>Do I really have to manually call <code>datetime(d.year, d.month, d.day)</code>?</p>
<p>You can use <a href="https://docs.python.org/2/library/datetime.html#datetime.datetime.combine" rel="noreferrer"><code>datetime.combine(date, time)</code></a>; for the time, you create a <code>datetime.time</code> object initialized to midnight.</p> <pre><code>from datetime import date from datetime import datetime dt = datetime.combine(date.today(), datetime.min.time()) </code></pre>
{ "question_id": 1937622, "question_date": "2009-12-21T00:26:01.660Z", "question_score": 878, "tags": "python|datetime|date", "answer_id": 1937636, "answer_date": "2009-12-21T00:33:40.997Z", "answer_score": 1105 }
Please answer the following Stack Overflow question: Title: What does functools.wraps do? <p>In a comment on this <a href="https://stackoverflow.com/questions/306130/python-decorator-makes-function-forget-that-it-belongs-to-a-class#306277">answer to another question</a>, someone said that they weren't sure what <code>functools.wraps</code> was doing. So, I'm asking this question so that there will be a record of it on StackOverflow for future reference: what does <code>functools.wraps</code> do, exactly?</p>
<p>When you use a decorator, you're replacing one function with another. In other words, if you have a decorator</p> <pre><code>def logged(func): def with_logging(*args, **kwargs): print(func.__name__ + " was called") return func(*args, **kwargs) return with_logging </code></pre> <p>then when you say</p> <pre><code>@logged def f(x): """does some math""" return x + x * x </code></pre> <p>it's exactly the same as saying</p> <pre><code>def f(x): """does some math""" return x + x * x f = logged(f) </code></pre> <p>and your function <code>f</code> is replaced with the function <code>with_logging</code>. Unfortunately, this means that if you then say</p> <pre><code>print(f.__name__) </code></pre> <p>it will print <code>with_logging</code> because that's the name of your new function. In fact, if you look at the docstring for <code>f</code>, it will be blank because <code>with_logging</code> has no docstring, and so the docstring you wrote won't be there anymore. Also, if you look at the pydoc result for that function, it won't be listed as taking one argument <code>x</code>; instead it'll be listed as taking <code>*args</code> and <code>**kwargs</code> because that's what with_logging takes.</p> <p>If using a decorator always meant losing this information about a function, it would be a serious problem. That's why we have <code>functools.wraps</code>. This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc. And since <code>wraps</code> is itself a decorator, the following code does the correct thing:</p> <pre><code>from functools import wraps def logged(func): @wraps(func) def with_logging(*args, **kwargs): print(func.__name__ + " was called") return func(*args, **kwargs) return with_logging @logged def f(x): """does some math""" return x + x * x print(f.__name__) # prints 'f' print(f.__doc__) # prints 'does some math' </code></pre>
{ "question_id": 308999, "question_date": "2008-11-21T14:53:40.610Z", "question_score": 878, "tags": "python|decorator|functools", "answer_id": 309000, "answer_date": "2008-11-21T14:53:47.410Z", "answer_score": 1423 }
Please answer the following Stack Overflow question: Title: UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined> <p>I'm trying to get a Python 3 program to do some manipulations with a text file filled with information. However, when trying to read the file I get the following error:</p> <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last): File &quot;SCRIPT LOCATION&quot;, line NUMBER, in &lt;module&gt; text = file.read() File &quot;C:\Python31\lib\encodings\cp1252.py&quot;, line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2907500: character maps to `&lt;undefined&gt;` </code></pre>
<p>The file in question is not using the <code>CP1252</code> encoding. It's using another encoding. Which one you have to figure out yourself. Common ones are <code>Latin-1</code> and <code>UTF-8</code>. Since <em>0x90</em> doesn't actually mean anything in <code>Latin-1</code>, <code>UTF-8</code> (where <em>0x90</em> is a continuation byte) is more likely.</p> <p>You specify the encoding when you open the file:</p> <pre><code>file = open(filename, encoding="utf8") </code></pre>
{ "question_id": 9233027, "question_date": "2012-02-10T18:43:57.830Z", "question_score": 877, "tags": "python|python-3.x|unicode|file-io|decode", "answer_id": 9233174, "answer_date": "2012-02-10T18:53:59.320Z", "answer_score": 1551 }
Please answer the following Stack Overflow question: Title: Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project <p>When creating a new Java project in IntelliJ IDEA, the following directories and files are created:</p> <pre><code>./projectname.iml ./projectname.ipr ./projectname.iws ./src/ </code></pre> <p>I want to configure IntelliJ IDEA to include my dependency JARs in <code>./lib/*.jar</code> to the project. What is the correct way to achieve this in IntelliJ IDEA?</p>
<p><a href="https://i.stack.imgur.com/ZlENo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZlENo.png" alt="dialogue in Intellij 20.3" /></a></p> <p>Steps for adding external jars in <strong>IntelliJ IDEA</strong>:</p> <ol> <li>Click <strong>File</strong> from the toolbar</li> <li>Select <strong>Project Structure</strong> option (<kbd>CTRL</kbd> + <kbd>SHIFT</kbd> + <kbd>ALT</kbd> + <kbd>S</kbd> on Windows/Linux, <kbd>⌘</kbd> + <kbd>;</kbd> on Mac OS X)</li> <li>Select <strong>Modules</strong> at the left panel</li> <li>Select <strong>Dependencies</strong> tab</li> <li>Select <strong>+</strong> icon</li> <li>Select <strong>1 JARs or directories</strong> option</li> </ol>
{ "question_id": 1051640, "question_date": "2009-06-26T22:58:35.393Z", "question_score": 877, "tags": "java|intellij-idea", "answer_id": 1051705, "answer_date": "2009-06-26T23:29:34.053Z", "answer_score": 1578 }
Please answer the following Stack Overflow question: Title: An invalid form control with name='' is not focusable <p>In Google Chrome some customers are not able to proceed to my payment page. When trying to submit a form I get this error:</p> <blockquote> <p>An invalid form control with name='' is not focusable.</p> </blockquote> <p>This is from the JavaScript console.</p> <p>I read that the problem could be due to hidden fields having the required attribute. Now the problem is that we are using .net webforms required field validators, and not the html5 required attribute.</p> <p>It seems random who gets this error. Is there anyone who knows a solution for this?</p>
<p>This issue occurs on Chrome if a form field fails validation, but due to the respective invalid control not being focusable the browser's attempt to display the message <em><strong>&quot;Please fill out this field&quot;</strong></em> next to it fails as well.</p> <p>A form control may not be focusable at the time validation is triggered for several reasons. The two scenarios described below are the most prominent causes:</p> <ul> <li><p>The field is irrelevant according to the current context of the business logic. In such a scenario, the respective control should be disabled or removed from the DOM or not be marked with the <code>required</code> attribute at that point.</p> </li> <li><p>Premature validation may occur due to a user pressing <em>ENTER</em> key on an input. Or a user clicking on a button/input control in the form which has not defined the <em><strong><code>type</code></strong></em> attribute of the control correctly. If the type attribute of a button is not set to <em><strong><code>button</code></strong></em>, Chrome (or any other browser for that matter) performs a validation each time the button is clicked because <em><strong><code>submit</code></strong></em> is the default value of a button's <em><strong><code>type</code></strong></em> attribute.</p> </li> </ul> <p>To solve the problem, if you have a button on your page that does something else other than <em><strong>submit</strong></em> or <em><strong>reset</strong></em>, always remember to do this: <code>&lt;button type=&quot;button&quot;&gt;</code>.</p>
{ "question_id": 22148080, "question_date": "2014-03-03T13:29:20.273Z", "question_score": 877, "tags": "html|validation", "answer_id": 28340579, "answer_date": "2015-02-05T09:38:27.703Z", "answer_score": 1065 }
Please answer the following Stack Overflow question: Title: Best practices for API versioning? <p>Are there any known how-tos or best practices for web service REST API versioning?</p> <p>I have noticed that <a href="http://docs.aws.amazon.com/AmazonSimpleDB/latest/DeveloperGuide/APIUsage.html" rel="noreferrer">AWS does versioning by the URL of the endpoint</a>. Is this the only way or are there other ways to accomplish the same goal? If there are multiple ways, what are the merits of each way? </p>
<p>This is a good and a tricky question. The topic of <strong>URI design is</strong> at the same time <strong>the most prominent part of a REST API and</strong>, therefore, a potentially <strong>long-term commitment towards the users of that API</strong>.</p> <p>Since evolution of an application and, to a lesser extent, its API is a fact of life and that it's even similar to the evolution of a seemingly complex product like a programming language, the <strong>URI design</strong> should have less <strong>natural constraints</strong> and it <strong>should be preserved over time</strong>. The longer the application's and API's lifespan, the greater the commitment to the users of the application and API.</p> <p>On the other hand, another fact of life is that it is hard to foresee all the resources and their aspects that would be consumed through the API. Luckily, it is not necessary to design the entire API which will be used until <a href="http://en.wikipedia.org/wiki/Apocalypse" rel="noreferrer">Apocalypse</a>. It is sufficient to correctly define all the resource end-points and the addressing scheme of every resource and resource instance.</p> <p>Over time you may need to add new resources and new attributes to each particular resource, but the method that API users follow to access a particular resources should not change once a resource addressing scheme becomes public and therefore final.</p> <p>This method applies to HTTP verb semantics (e.g. PUT should always update/replace) and HTTP status codes that are supported in earlier API versions (they should continue to work so that API clients that have worked without human intervention should be able to continue to work like that).</p> <p>Furthermore, since embedding of API version into the URI would disrupt the concept of <a href="http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_5" rel="noreferrer">hypermedia as the engine of application state</a> (stated in Roy T. Fieldings PhD dissertation) by having a resource address/URI that would change over time, I would conclude that <strong>API versions should not be kept in resource URIs for a long time</strong> meaning that <strong>resource URIs that API users can depend on should be permalinks</strong>.</p> <p>Sure, <strong>it is possible to embed API version in base URI</strong> but <strong>only for reasonable and restricted uses like debugging a API client</strong> that works with the the new API version. Such versioned APIs should be time-limited and available to limited groups of API users (like during closed betas) only. Otherwise, you commit yourself where you shouldn't.</p> <p>A couple of thoughts regarding maintenance of API versions that have expiration date on them. All programming platforms/languages commonly used to implement web services (Java, .NET, PHP, Perl, Rails, etc.) allow easy binding of web service end-point(s) to a base URI. This way it's easy to <strong>gather and keep</strong> a collection of files/classes/methods <strong>separate across different API versions</strong>. </p> <p>From the API users POV, it's also easier to work with and bind to a particular API version when it's this obvious but only for limited time, i.e. during development.</p> <p>From the API maintainer's POV, it's easier to maintain different API versions in parallel by using source control systems that predominantly work on files as the smallest unit of (source code) versioning.</p> <p>However, with API versions clearly visible in URI there's a caveat: one might also object this approach since <strong>API history becomes visible/aparent in the URI design</strong> <strong>and therefore is prone to changes over time</strong> which goes against the guidelines of REST. I agree!</p> <p>The way to go around this reasonable objection, is to implement the latest API version under versionless API base URI. In this case, API client developers can choose to either:</p> <ul> <li><p>develop against the latest one (committing themselves to maintain the application protecting it from eventual API changes that might break their <strong>badly designed API client</strong>).</p></li> <li><p>bind to a specific version of the API (which becomes apparent) but only for a limited time</p></li> </ul> <p>For example, if API v3.0 is the latest API version, the following two should be aliases (i.e. behave identically to all API requests):</p> <pre> <b>http://shonzilla/api/customers/1234</b> http://shonzilla/api<b>/v3.0</b>/customers/1234 http://shonzilla/api<b>/v3</b>/customers/1234 </pre> <p>In addition, API clients that still try to point to the <em>old</em> API should be informed to use the latest previous API version, <strong>if the API version they're using is obsolete or not supported anymore</strong>. So accessing any of the obsolete URIs like these:</p> <pre> http://shonzilla/api<b>/v2.2</b>/customers/1234 http://shonzilla/api<b>/v2.0</b>/customers/1234 http://shonzilla/api<b>/v2</b>/customers/1234 http://shonzilla/api<b>/v1.1</b>/customers/1234 http://shonzilla/api<b>/v1</b>/customers/1234 </pre> <p>should return any of the <strong>30x HTTP status codes that indicate redirection</strong> that are used in conjunction with <code>Location</code> HTTP header that redirects to the appropriate version of resource URI which remain to be this one:</p> <pre> <b>http://shonzilla/api/customers/1234</b> </pre> <p>There are at least two redirection HTTP status codes that are appropriate for API versioning scenarios:</p> <ul> <li><p><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.2" rel="noreferrer">301 Moved permanently</a> indicating that the resource with a requested URI is moved permanently to another URI (which should be a resource instance permalink that does not contain API version info). This status code can be used to indicate an obsolete/unsupported API version, informing API client that a <strong>versioned resource URI been replaced by a resource permalink</strong>.</p></li> <li><p><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.3" rel="noreferrer">302 Found</a> indicating that the requested resource temporarily is located at another location, while requested URI may still supported. This status code may be useful when the version-less URIs are temporarily unavailable and that a request should be repeated using the redirection address (e.g. pointing to the URI with APi version embedded) and we want to tell clients to keep using it (i.e. the permalinks).</p></li> <li><p>other scenarios can be found in <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3" rel="noreferrer">Redirection 3xx chapter of HTTP 1.1 specification</a></p></li> </ul>
{ "question_id": 389169, "question_date": "2008-12-23T15:32:42.387Z", "question_score": 877, "tags": "rest|versioning", "answer_id": 398564, "answer_date": "2008-12-29T20:24:36.380Z", "answer_score": 682 }
Please answer the following Stack Overflow question: Title: Function overloading in Javascript - Best practices <p>What is the best way(s) to fake function overloading in Javascript? </p> <p>I know it is not possible to overload functions in Javascript as in other languages. If I needed a function with two uses <code>foo(x)</code> and <code>foo(x,y,z)</code> which is the best / preferred way:</p> <ol> <li>Using different names in the first place</li> <li>Using optional arguments like <code>y = y || 'default'</code></li> <li>Using number of arguments</li> <li>Checking types of arguments</li> <li>Or how?</li> </ol>
<p>The best way to do function overloading with parameters is not to check the argument length or the types; checking the types will just make your code slow and you have the fun of Arrays, nulls, Objects, etc.</p> <p>What most developers do is tack on an object as the last argument to their methods. This object can hold anything. </p> <pre><code>function foo(a, b, opts) { // ... if (opts['test']) { } //if test param exists, do something.. } foo(1, 2, {"method":"add"}); foo(3, 4, {"test":"equals", "bar":"tree"}); </code></pre> <p>Then you can handle it anyway you want in your method. [Switch, if-else, etc.]</p>
{ "question_id": 456177, "question_date": "2009-01-19T00:06:27.343Z", "question_score": 877, "tags": "javascript|overloading", "answer_id": 457589, "answer_date": "2009-01-19T13:32:17.107Z", "answer_score": 689 }
Please answer the following Stack Overflow question: Title: When do we need curly braces around shell variables? <p>In shell scripts, when do we use <code>{}</code> when expanding variables?</p> <p>For example, I have seen the following:</p> <pre><code>var=10 # Declare variable echo "${var}" # One use of the variable echo "$var" # Another use of the variable </code></pre> <p>Is there a significant difference, or is it just style? Is one preferred over the other?</p>
<p>In this particular example, it makes no difference. However, the <code>{}</code> in <code>${}</code> are useful if you want to expand the variable <code>foo</code> in the string</p> <pre><code>"${foo}bar" </code></pre> <p>since <code>"$foobar"</code> would instead expand the variable identified by <code>foobar</code>.</p> <p>Curly braces are also unconditionally required when:</p> <ul> <li>expanding array elements, as in <code>${array[42]}</code></li> <li>using parameter expansion operations, as in <code>${filename%.*}</code> (remove extension)</li> <li>expanding positional parameters beyond 9: <code>"$8 $9 ${10} ${11}"</code></li> </ul> <p>Doing this everywhere, instead of just in potentially ambiguous cases, <em>can</em> be considered good programming practice. This is both for consistency and to avoid surprises like <code>$foo_$bar.jpg</code>, where it's not visually obvious that the underscore becomes part of the variable name.</p>
{ "question_id": 8748831, "question_date": "2012-01-05T19:54:03.940Z", "question_score": 877, "tags": "bash|shell|curly-braces|variable-expansion|brace-expansion", "answer_id": 8748880, "answer_date": "2012-01-05T19:56:34.780Z", "answer_score": 995 }