input_text
stringlengths
115
13.8k
output_text
stringlengths
24
15k
metadata
dict
Please answer the following Stack Overflow question: Title: How to efficiently remove all null elements from a ArrayList or String Array? <p>I try with a loop like that</p> <pre><code>// ArrayList tourists for (Tourist t : tourists) { if (t != null) { t.setId(idForm); } } </code></pre> <p>But it isn't nice. Can anyone suggest me a better solution?</p> <hr /> <p>Some useful benchmarks to make better decision:</p> <p><a href="http://www.mkyong.com/java/while-loop-for-loop-and-iterator-performance-test-java/" rel="noreferrer">While loop, For loop and Iterator Performance Test</a></p>
<p>Try:</p> <pre><code>tourists.removeAll(Collections.singleton(null)); </code></pre> <p>Read the <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#singleton-T-" rel="noreferrer">Java API</a>. The code will throw <code>java.lang.UnsupportedOperationException</code> for immutable lists (such as created with <code>Arrays.asList</code>); see <a href="https://stackoverflow.com/a/15381271/59087">this answer</a> for more details.</p>
{ "question_id": 4819635, "question_date": "2011-01-27T17:21:07.220Z", "question_score": 211, "tags": "java|performance|loops|for-loop|arraylist", "answer_id": 4819668, "answer_date": "2011-01-27T17:24:25.330Z", "answer_score": 389 }
Please answer the following Stack Overflow question: Title: Change fill color on vector asset in Android Studio <p>Android Studio now supports vector assets on 21+ and will generate pngs for lower versions at compile time. I have a vector asset (from the Material Icons) that I want to change the fill color. This works on 21+, but the generated pngs do not change color. Is there a way to do this?</p> <pre><code>&lt;vector android:height="48dp" android:viewportHeight="24.0" android:viewportWidth="24.0" android:width="48dp" xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;path android:fillColor="@color/primary" android:pathData="M9,16.17L4.83,12l-1.42,1.41L9,19 21,7l-1.41,-1.41z"/&gt; </code></pre> <p></p>
<p>Don't edit the vector assets directly. If you're using a vector drawable in an ImageButton, just choose your color in <code>android:tint</code>.</p> <pre><code>&lt;ImageButton android:layout_width="48dp" android:layout_height="48dp" android:id="@+id/button" android:src="@drawable/ic_more_vert_24dp" android:tint="@color/primary" /&gt; </code></pre>
{ "question_id": 32924986, "question_date": "2015-10-03T16:44:33.717Z", "question_score": 211, "tags": "android|android-studio|vector-graphics|android-vectordrawable", "answer_id": 32926960, "answer_date": "2015-10-03T20:04:54.050Z", "answer_score": 405 }
Please answer the following Stack Overflow question: Title: What are the safe characters for making URLs? <p>I am making a website with articles, and I need the articles to have &quot;friendly&quot; URLs, based on the title.</p> <p>For example, if the title of my article is <code>&quot;Article Test&quot;</code>, I would like the URL to be <code>http://www.example.com/articles/article_test</code>.</p> <p>However, article titles (as any string) can contain multiple special characters that would not be possible to put literally in my URL. For instance, I know that <code>?</code> or <code>#</code> need to be replaced, but I don't know all the others.</p> <p>What characters are permissible in URLs? What is safe to keep?</p>
<p>To quote section 2.3 of <a href="http://www.ietf.org/rfc/rfc3986.txt" rel="noreferrer">RFC 3986</a>:</p> <blockquote> <p>Characters that are allowed in a URI, but do not have a reserved purpose, are called unreserved. These include uppercase and lowercase letters, decimal digits, hyphen, period, underscore, and tilde.</p> <pre><code> ALPHA DIGIT &quot;-&quot; / &quot;.&quot; / &quot;_&quot; / &quot;~&quot; </code></pre> </blockquote> <p>Note that RFC 3986 lists fewer reserved punctuation marks than the older <a href="http://www.ietf.org/rfc/rfc2396.txt" rel="noreferrer">RFC 2396</a>.</p>
{ "question_id": 695438, "question_date": "2009-03-29T21:42:36.700Z", "question_score": 211, "tags": "url|friendly-url", "answer_id": 695469, "answer_date": "2009-03-29T21:57:33.607Z", "answer_score": 261 }
Please answer the following Stack Overflow question: Title: How to swap two variables in JavaScript <p>I have this two variables:</p> <pre><code>var a = 1, b = 2; </code></pre> <p>My question is how to swap them? Only this variables, not any objects.</p>
<p>Here's a one-liner to swap the values of two variables.<br> Given variables <code>a</code> and <code>b</code>:</p> <pre><code>b = [a, a = b][0]; </code></pre> <p>Demonstration below:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var a=1, b=2, output=document.getElementById('output'); output.innerHTML="&lt;p&gt;Original: "+a+", "+b+"&lt;/p&gt;"; b = [a, a = b][0]; output.innerHTML+="&lt;p&gt;Swapped: "+a+", "+b+"&lt;/p&gt;";</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="output"&gt;&lt;/div&gt;</code></pre> </div> </div> </p>
{ "question_id": 16201656, "question_date": "2013-04-24T20:35:13.110Z", "question_score": 211, "tags": "javascript|variables|swap", "answer_id": 16201730, "answer_date": "2013-04-24T20:39:39.250Z", "answer_score": 348 }
Please answer the following Stack Overflow question: Title: collapse cell in jupyter notebook <p>I am using ipython Jupyter notebook. Let's say I defined a function that occupies a lot of space on my screen. Is there a way to collapse the cell? </p> <p>I want the function to remain executed and callable, yet I want to hide / collapse the cell in order to better visualize the notebook. How can I do this?</p>
<p><strong>UPDATE</strong>:</p> <p>The newer <code>jupyter-lab</code> is a more modern and feature-rich interface which supports cell folding by default. See @intsco's answer below</p> <p><strong>UPDATE 2</strong></p> <p>Since <code>jupyter-lab</code> now also supports extensions, you can extend the built-in cell-folding functionality with the <a href="https://github.com/aquirdTurtle/Collapsible_Headings" rel="noreferrer"><code>Collapsible_Headings</code></a> extension.</p> <p><strong>Original answer:</strong></p> <p>The <a href="https://github.com/ipython-contrib/jupyter_contrib_nbextensions" rel="noreferrer"><code>jupyter contrib nbextensions</code></a> Python package contains a code-folding extension that can be enabled within the notebook. Follow the link (Github) for documentation.</p> <p>To install using command line:</p> <pre><code>pip install jupyter_contrib_nbextensions jupyter contrib nbextension install --user </code></pre> <p>To make life easier in managing them, I'd also recommend the <a href="https://github.com/Jupyter-contrib/jupyter_nbextensions_configurator" rel="noreferrer"><code>jupyter nbextensions configurator</code></a> package. This provides an extra tab in your Notebook interface from where you can easily (de)activate all installed extensions.</p> <p>Installation:</p> <pre><code>pip install jupyter_nbextensions_configurator jupyter nbextensions_configurator enable --user </code></pre>
{ "question_id": 33159518, "question_date": "2015-10-15T22:21:54.250Z", "question_score": 211, "tags": "python|ipython|ipython-notebook|jupyter", "answer_id": 42056357, "answer_date": "2017-02-05T19:35:42.247Z", "answer_score": 142 }
Please answer the following Stack Overflow question: Title: JavaScript: Difference between .forEach() and .map() <p>I know that there were a lot of topics like this. And I know the basics: <code>.forEach()</code> operates on original array and <code>.map()</code> on the new one.</p> <p>In my case:</p> <pre><code>function practice (i){ return i+1; }; var a = [ -1, 0, 1, 2, 3, 4, 5 ]; var b = [ 0 ]; var c = [ 0 ]; console.log(a); b = a.forEach(practice); console.log("====="); console.log(a); console.log(b); c = a.map(practice); console.log("====="); console.log(a); console.log(c); </code></pre> <p>And this is output:</p> <pre><code>[ -1, 0, 1, 2, 3, 4, 5 ] ===== [ -1, 0, 1, 2, 3, 4, 5 ] undefined ===== [ -1, 0, 1, 2, 3, 4, 5 ] [ 0, 1, 2, 3, 4, 5, 6 ] </code></pre> <p>I can't understand why using <code>practice</code> changes value of <code>b</code> to <code>undefined</code>.<br> I'm sorry if this is silly question, but I'm quite new in this language and answers I found so far didn't satisfy me.</p>
<p>They are not one and the same. Let me explain the difference.</p> <p><code>forEach</code>: This iterates over a list and applies some operation with side effects to each list member (example: saving every list item to the database) and does not return anything.</p> <p><code>map</code>: This iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members (example: transforming list of strings to uppercase). It does not mutate the array on which it is called (although the callback function may do so).</p> <p>References</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach" rel="noreferrer">Array.prototype.forEach() - JavaScript | MDN</a></p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="noreferrer">Array.prototype.map() - JavaScript | MDN</a></p>
{ "question_id": 34426458, "question_date": "2015-12-22T23:54:34.627Z", "question_score": 211, "tags": "javascript|arrays|loops|foreach", "answer_id": 34426481, "answer_date": "2015-12-22T23:56:31.483Z", "answer_score": 300 }
Please answer the following Stack Overflow question: Title: The split() method in Java does not work on a dot (.) <p>I have prepared a simple code snippet in order to separate the erroneous portion from my web application.</p> <pre><code>public class Main { public static void main(String[] args) throws IOException { System.out.print("\nEnter a string:-&gt;"); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String temp = br.readLine(); String words[] = temp.split("."); for (int i = 0; i &lt; words.length; i++) { System.out.println(words[i] + "\n"); } } } </code></pre> <p>I have tested it while building a web application JSF. I just want to know why in the above code <code>temp.split(".")</code> does not work. The statement,</p> <pre><code>System.out.println(words[i]+"\n"); </code></pre> <p>displays nothing on the console means that it doesn't go through the loop. When I change the argument of the <code>temp.split()</code> method to other characters, It works just fine as usual. What might be the problem?</p>
<p><a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#split-java.lang.String-"><code>java.lang.String.split</code></a> splits on regular expressions, and <code>.</code> in a regular expression means "any character".</p> <p>Try <code>temp.split("\\.")</code>.</p>
{ "question_id": 7935858, "question_date": "2011-10-28T23:22:40.047Z", "question_score": 211, "tags": "java|string|split", "answer_id": 7935873, "answer_date": "2011-10-28T23:26:23.323Z", "answer_score": 539 }
Please answer the following Stack Overflow question: Title: Run ssh and immediately execute command <p>I'm trying to find UNIX or bash command to run a command after connecting to an ssh server. For example:</p> <pre><code>ssh name@ip "tmux list-sessions" </code></pre> <p>The above code works, it lists the sessions, but it then immediately disconnects. Putting it in the sshrc on the server side works, but I need to be able to type it in client side. I want to be able to run a command, it logs in, opens up the window, then runs the command I've set. Ive tried </p> <pre><code>[command] | ssh name@ip ssh name@ip [command] ssh name@ip "[command]" ssh -t name@ip [command] </code></pre>
<pre><code>ssh -t 'command; bash -l' </code></pre> <p>will execute the command and then start up a login shell when it completes. For example:</p> <pre><code>ssh -t [email protected] 'cd /some/path; bash -l' </code></pre>
{ "question_id": 18522647, "question_date": "2013-08-29T23:38:32.467Z", "question_score": 211, "tags": "bash|unix|ssh", "answer_id": 18522811, "answer_date": "2013-08-29T23:56:53.533Z", "answer_score": 322 }
Please answer the following Stack Overflow question: Title: SQL Server Restore Error - Access is Denied <p>I created a database on my local machine and then did a backup called <code>tables.bak</code> of table <code>DataLabTables</code>. </p> <p>I moved that backup to a remote machine without that table and tried to do a restore but get the following error:</p> <blockquote> <p>System.Data.SqlClient.SqlError: The operating system returned the error '5(Access is denied.)' while attempting 'RestoreContainer::ValidateTargetForCreation' on 'c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DataLabTables.mdf'.</p> </blockquote> <p>How do I fix my rights, if that is the problem?</p>
<p>I have just had this issue with SQL Server 2012.</p> <p>It turns out all I had to do was tick the box marked 'Relocate all files to folder' on the 'Files' section:</p> <p><a href="https://i.stack.imgur.com/kFmwH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kFmwH.png" alt="enter image description here"></a></p> <p>(Click to see image full size)</p> <p>This of course assumes you have the correct version of SQL Server installed.</p>
{ "question_id": 7031792, "question_date": "2011-08-11T19:35:42.180Z", "question_score": 211, "tags": "sql-server|sql-server-2005|backup|restore", "answer_id": 17146338, "answer_date": "2013-06-17T11:24:08.217Z", "answer_score": 678 }
Please answer the following Stack Overflow question: Title: How to replace ${} placeholders in a text file? <p>I want to pipe the output of a "template" file into MySQL, the file having variables like <code>${dbName}</code> interspersed. What is the command line utility to replace these instances and dump the output to standard output?</p>
<p><a href="https://en.wikipedia.org/wiki/Sed" rel="noreferrer">Sed</a>!</p> <p>Given template.txt:</p> <pre> The number is ${i} The word is ${word} </pre> <p>we just have to say:</p> <pre><code>sed -e "s/\${i}/1/" -e "s/\${word}/dog/" template.txt </code></pre> <p>Thanks to Jonathan Leffler for the tip to pass multiple <code>-e</code> arguments to the same <code>sed</code> invocation.</p>
{ "question_id": 415677, "question_date": "2009-01-06T07:00:16.113Z", "question_score": 211, "tags": "bash|command-line|text-processing|templating", "answer_id": 415775, "answer_date": "2009-01-06T08:01:21.887Z", "answer_score": 236 }
Please answer the following Stack Overflow question: Title: Convert command line arguments into an array in Bash <p>How do I convert command-line arguments into a bash script array?</p> <p>I want to take this:</p> <pre><code>./something.sh arg1 arg2 arg3 </code></pre> <p>and convert it to </p> <pre><code>myArray=( arg1 arg2 arg3 ) </code></pre> <p>so that I can use myArray for further use in the script.</p> <p>This previous SO post comes close, but doesn't go into how to create an array: <a href="https://stackoverflow.com/questions/192249/how-do-i-parse-command-line-arguments-in-bash">How do I parse command line arguments in Bash?</a></p> <p>I need to convert the arguments into a regular bash script array; I realize I could use other languages (Python, for instance) but need to do this in bash. I guess I'm looking for an "append" function or something similar?</p> <p>UPDATE: I also wanted to ask how to check for zero arguments and assign a default array value, and thanks to the answer below, was able to get this working:</p> <pre><code>if [ "$#" -eq 0 ]; then myArray=( defaultarg1 defaultarg2 ) else myArray=( "$@" ) fi </code></pre>
<p>Actually your command line arguments are <em>practically</em> like an array already. At least, you can treat the <code>$@</code> variable much like an array. That said, you can convert it into an actual array like this:</p> <pre><code>myArray=( "$@" ) </code></pre> <p>If you just want to type some arguments and feed them into the <code>$@</code> value, use <code>set</code>:</p> <pre><code>$ set -- apple banana "kiwi fruit" $ echo "$#" 3 $ echo "$@" apple banana kiwi fruit </code></pre> <p>Understanding how to use the argument structure is particularly useful in POSIX sh, which has nothing else like an array.</p>
{ "question_id": 12711786, "question_date": "2012-10-03T15:30:16.783Z", "question_score": 211, "tags": "arrays|bash|shell", "answer_id": 12711837, "answer_date": "2012-10-03T15:33:13.110Z", "answer_score": 257 }
Please answer the following Stack Overflow question: Title: Creating the Singleton design pattern in PHP5 <p>How would one create a Singleton class using PHP5 classes?</p>
<pre><code>/** * Singleton class * */ final class UserFactory { private static $inst = null; // Prevent cloning and de-serializing private function __clone(){} private function __wakeup(){} /** * Call this method to get singleton * * @return UserFactory */ public static function Instance() { if ($inst === null) { $inst = new UserFactory(); } return $inst; } /** * Private ctor so nobody else can instantiate it * */ private function __construct() { } } </code></pre> <p>To use:</p> <pre><code>$fact = UserFactory::Instance(); $fact2 = UserFactory::Instance(); </code></pre> <p><code>$fact == $fact2;</code></p> <p>But:</p> <pre><code>$fact = new UserFactory() </code></pre> <p>Throws an error.</p> <p>See <a href="http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static" rel="nofollow noreferrer" title="PHP: Variable Scope : Using Static Variables">http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static</a> to understand static variable scopes and why setting <code>static $inst = null;</code> works.</p>
{ "question_id": 203336, "question_date": "2008-10-15T00:33:27.650Z", "question_score": 211, "tags": "php|oop|design-patterns|singleton", "answer_id": 203359, "answer_date": "2008-10-15T00:45:17.190Z", "answer_score": 271 }
Please answer the following Stack Overflow question: Title: External VS2013 build error "error MSB4019: The imported project <path> was not found" <p>I am building a project through the command line and not inside Visual Studio 2013. Note, I had upgraded my project from Visual Studio 2012 to 2013. The project builds fine inside the IDE. Also, I completely uninstalled VS2012 first, rebooted, and installed VS2013. The only version of Visual Studio that I have is 2013 Ultimate.</p> <pre><code>ValidateProjects: 39&gt;path_to_project.csproj(245,3): error MSB4019: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\WebApplications\Microsoft.WebApplication.targets" was not found. Confirm that the path in the &lt;Import&gt; declaration is correct, and that the file exists on disk. 39&gt;Done Building Project "path_to_project.csproj" (Clean target(s)) -- FAILED. </code></pre> <p>Here are the two lines in question:</p> <pre><code>&lt;Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" /&gt; &lt;Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v12.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" /&gt; </code></pre> <p>The original second line was v10.0, but I manually changed that to v12.0.</p> <p>$(VSToolsPath) elongates from what I see to the v11.0 (VS2012) folder, which obviously is not there anymore. The path should have been to v12.0.</p> <pre><code>C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\WebApplications\ </code></pre> <p>I tried specifying VSToolsPath in my system environment variables table, but the external build utility still uses v11.0. I tried searching through the registry and that came up with nothing.</p> <p>Sadly, I do not see any easy way to get the exact command line used. I use a build tool.</p> <p>Thoughts?</p>
<p>I had the same issue and find an easier solution</p> <p>It is due to Vs2012 adding the following to the csproj file:</p> <pre><code>&lt;PropertyGroup&gt; &lt;VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''"&gt;10.0&lt;/VisualStudioVersion&gt; &lt;VSToolsPath Condition="'$(VSToolsPath)' == ''"&gt;$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)&lt;/VSToolsPath&gt; &lt;/PropertyGroup&gt; </code></pre> <p>You can safely remove that part and your solution will build.</p> <blockquote> <p>As <a href="https://stackoverflow.com/questions/19718281/external-vs2013-build-error-error-msb4019-the-imported-project-path-was-not/20095260#comment33639922_20095260">Sielu pointed out</a> you have to ensure that the .proj file begin with <code>&lt;Project ToolsVersion="12"</code> otherwise the next time you open the project with visual studio 2010, it will add the removed node again.</p> </blockquote> <p>Otherwise, if you need to use webdeploy or you use a build server, the above solution will not work but you can specify the <code>VisualStudioVersion</code> property in your build script:</p> <pre><code>msbuild myproject.csproj /p:VisualStudioVersion=12.0 </code></pre> <p>or edit your build definition:</p> <p><img src="https://i.stack.imgur.com/OvFTQ.png" alt="edit build definition to specify the &lt;code&gt;VisualStudioVersion&lt;/code&gt; property"></p>
{ "question_id": 19718281, "question_date": "2013-10-31T23:19:12.277Z", "question_score": 211, "tags": "c#|web-applications|visual-studio-2013|build|visual-build-professional", "answer_id": 20095260, "answer_date": "2013-11-20T11:54:44.987Z", "answer_score": 259 }
Please answer the following Stack Overflow question: Title: “Unable to find manifest signing certificate in the certificate store” - even when add new key <p>I cannot build projects with a strong name key signing - the message in the title always comes up.</p> <p>Yes the project was initially copied over from another machine. However even if I add a new key via the Signing tab in Project Properties, this error is still shown.</p> <p>I have tried running Visual Studio as an Administrator and have tried manually adding the keys to Windows Certificate Store.</p> <p>Help!</p> <p>Edit: I don't get this error with a new project, but I'd quite like to get this existing project working. It won't work even if I create a new certificate!</p>
<p>I've finally found the solution.</p> <ol> <li><p>Edit the <code>.csproj</code> file for the project in question.</p> </li> <li><p>Delete the following lines of code:</p> <pre><code>&lt;PropertyGroup&gt; &lt;ManifestCertificateThumbprint&gt;...........&lt;/ManifestCertificateThumbprint&gt; &lt;/PropertyGroup&gt; &lt;PropertyGroup&gt; &lt;ManifestKeyFile&gt;xxxxxxxx.pfx&lt;/ManifestKeyFile&gt; &lt;/PropertyGroup&gt; &lt;PropertyGroup&gt; &lt;GenerateManifests&gt;true&lt;/GenerateManifests&gt; &lt;/PropertyGroup&gt; &lt;PropertyGroup&gt; &lt;SignManifests&gt;false&lt;/SignManifests&gt; &lt;/PropertyGroup&gt; </code></pre> </li> </ol>
{ "question_id": 11957295, "question_date": "2012-08-14T17:03:34.987Z", "question_score": 211, "tags": "visual-studio-2010|visual-studio|code-signing|strongname", "answer_id": 12130113, "answer_date": "2012-08-26T12:27:04.500Z", "answer_score": 351 }
Please answer the following Stack Overflow question: Title: Output of git branch in tree like fashion <p>Right now, when I type "git branch"</p> <p>it lists my branches in an arbitrary order.</p> <p>What I would prefer would be if "git branch" listed my output in a tree like fasion, somethign like:</p> <pre><code>master |-- foo |-- foo1 |-- foo2 |-- bar |-- bar4 </code></pre> <p>Where here, foo &amp; bar were branched from master; foo1 &amp; foo2 were branched from foo; bar4 was branched from bar.</p> <p>Is this easy to accomplish?</p> <p>[Command line utilities only. This needs to fit into my zsh/vim workflow.]</p>
<p>The <a href="https://stackoverflow.com/a/9726638/6309">answer below</a> uses <a href="http://git-scm.com/docs/git-log" rel="noreferrer"><code>git log</code></a>:</p> <p>I mentioned a similar approach in 2009 with "<a href="https://stackoverflow.com/a/1064431/6309">Unable to show a Git tree in terminal</a>":</p> <pre><code>git log --graph --pretty=oneline --abbrev-commit </code></pre> <p>But the full one I have been using is in "<a href="https://stackoverflow.com/a/7023272/6309">How to display the tag name and branch name using git log --graph</a>" (2011):</p> <pre><code>git config --global alias.lgb "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)&lt;%an&gt;%Creset%n' --abbrev-commit --date=relative --branches" git lgb </code></pre> <hr> <p>Original answer (2010)</p> <p><a href="http://www.kernel.org/pub/software/scm/git/docs/git-show-branch.html" rel="noreferrer"><code>git show-branch --list</code></a> comes close of what you are looking for (with the topo order)</p> <pre><code>--topo-order </code></pre> <blockquote> <p>By default, the branches and their commits are shown in reverse chronological order.<br> This option makes them appear in topological order (i.e., descendant commits are shown before their parents).</p> </blockquote> <p>But the tool <a href="https://github.com/michaelklishin/git-wtf" rel="noreferrer">git wtf</a> can <a href="http://www.mountainprogramming.com/2009/09/git-wtf-in-git-sh.html" rel="noreferrer">help too</a>. Example:</p> <pre><code>$ git wtf Local branch: master [ ] NOT in sync with remote (needs push) - Add before-search hook, for shortcuts for custom search queries. [4430d1b] (edwardzyang@...; 7 days ago) Remote branch: origin/master ([email protected]:sup/mainline.git) [x] in sync with local Feature branches: { } origin/release-0.8.1 is NOT merged in (1 commit ahead) - bump to 0.8.1 [dab43fb] (wmorgan-sup@...; 2 days ago) [ ] labels-before-subj is NOT merged in (1 commit ahead) - put labels before subject in thread index view [790b64d] (marka@...; 4 weeks ago) {x} origin/enclosed-message-display-tweaks merged in (x) experiment merged in (only locally) NOTE: working directory contains modified files </code></pre> <blockquote> <p><code>git-wtf</code> shows you:</p> <ul> <li>How your branch relates to the remote repo, if it's a tracking branch.</li> <li>How your branch relates to non-feature ("version") branches, if it's a feature branch.</li> <li>How your branch relates to the feature branches, if it's a version branch</li> </ul> </blockquote>
{ "question_id": 2421011, "question_date": "2010-03-10T22:10:26.923Z", "question_score": 211, "tags": "git", "answer_id": 2421063, "answer_date": "2010-03-10T22:16:38.013Z", "answer_score": 273 }
Please answer the following Stack Overflow question: Title: Editing the git commit message in GitHub <p>Is there any way of online editing the commit message in <code>GitHub.com</code>, after submission?</p> <p>From the command line, one can do</p> <pre><code>git commit --amend -m "New commit message" </code></pre> <p>as correctly suggested in <a href="https://stackoverflow.com/questions/179123/how-do-i-edit-an-incorrect-commit-message-in-git">another question</a>.</p> <p>Trying <code>git pull</code> and then <code>git push</code> has worked (without any other commit having interfered in the mean time).</p> <p>But can it be done via the <code>GitHub</code> website?</p>
<p>No, this is not directly possible. The hash for every Git commit is also calculated based on the commit message. When you change the commit message, you change the commit hash. If you want to push that commit, you have to force that push (git push -f). But if already someone pulled your old commit and started a work based on that commit, they would have to rebase their work onto your new commit.</p>
{ "question_id": 10728420, "question_date": "2012-05-23T21:52:48.767Z", "question_score": 211, "tags": "git|github|commit|post-commit", "answer_id": 10728453, "answer_date": "2012-05-23T21:56:02.163Z", "answer_score": 126 }
Please answer the following Stack Overflow question: Title: Best Practice: Software Versioning <p>Is there any guideline or standard best practice how to version a software you develop in your spare time for fun, but nevertheless will be used by some people? I think it's necessary to version such software so that you know about with version one is talking about (e.g. for bug fixing, support, and so on).</p> <p>But where do I start the versioning? 0.0.0? or 0.0? And then how to I increment the numbers? major release.minor change? and shouldn't any commit to a version control system be another version? or is this only for versions which are used in a productive manner?</p>
<p>You should start with version 1, unless you know that the first version you "release" is incomplete in some way.</p> <p>As to how you increment the versions, that's up to you, but use the major, minor, build numbering as a guide.</p> <p>It's not necessary to have every version you commit to source control as another version - you'll soon have a very large version number indeed. You only need to increment the version number (in some way) when you release a new version to the outside world.</p> <p>So If you make a major change move from version 1.0.0.0 to version 2.0.0.0 (you changed from WinForms to WPF for example). If you make a smaller change move from 1.0.0.0 to 1.1.0.0 (you added support for png files). If you make a minor change then go from 1.0.0.0 to 1.0.1.0 (you fixed some bugs).</p> <p>If you really want to get detailed use the final number as the build number which would increment for every checkin/commit (but I think that's going too far).</p>
{ "question_id": 2864448, "question_date": "2010-05-19T09:58:42.143Z", "question_score": 211, "tags": "versioning", "answer_id": 2864502, "answer_date": "2010-05-19T10:06:01.483Z", "answer_score": 125 }
Please answer the following Stack Overflow question: Title: postgresql list and order tables by size <p>How can I <strong>list all the tables</strong> of a PostgreSQL database and <strong>order them by size</strong>?</p>
<pre><code>select table_name, pg_relation_size(quote_ident(table_name)) from information_schema.tables where table_schema = 'public' order by 2 </code></pre> <p>This shows you the size of all tables in the schema <code>public</code> if you have multiple schemas, you might want to use:</p> <pre><code>select table_schema, table_name, pg_relation_size('"'||table_schema||'"."'||table_name||'"') from information_schema.tables order by 3 </code></pre> <p>SQLFiddle example: <a href="http://sqlfiddle.com/#!15/13157/3" rel="noreferrer">http://sqlfiddle.com/#!15/13157/3</a></p> <p>List of all object size functions in the <a href="https://www.postgresql.org/docs/current/static/functions-admin.html#FUNCTIONS-ADMIN-DBSIZE" rel="noreferrer">manual</a>.</p>
{ "question_id": 21738408, "question_date": "2014-02-12T20:02:59.430Z", "question_score": 211, "tags": "sql|postgresql|postgresql-9.3", "answer_id": 21738505, "answer_date": "2014-02-12T20:07:49.390Z", "answer_score": 265 }
Please answer the following Stack Overflow question: Title: The relationship could not be changed because one or more of the foreign-key properties is non-nullable <p>I am getting this error when I GetById() on an entity and then set the collection of child entities to my new list which comes from the MVC view.</p> <blockquote> <p>The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.</p> </blockquote> <p>I don't quite understand this line:</p> <blockquote> <p>The relationship could not be changed because one or more of the foreign-key properties is non-nullable.</p> </blockquote> <p>Why would I change the relationship between 2 entities? It should remain the same throughout the lifetime of the whole application.</p> <p>The code the exception occurs on is simple assigning modified child classes in a collection to the existing parent class. This would hopefully cater for removal of child classes, addition of new ones and modifications. I would have thought Entity Framework handles this.</p> <p>The lines of code can be distilled to:</p> <pre><code>var thisParent = _repo.GetById(1); thisParent.ChildItems = modifiedParent.ChildItems(); _repo.Save(); </code></pre>
<p>You should delete old child items <code>thisParent.ChildItems</code> one by one manually. Entity Framework doesn't do that for you. It finally cannot decide what you want to do with the old child items - if you want to throw them away or if you want to keep and assign them to other parent entities. You must tell Entity Framework your decision. But one of these two decisions you HAVE to make since the child entities cannot live alone without a reference to any parent in the database (due to the foreign key constraint). That's basically what the exception says. </p> <p><strong>Edit</strong></p> <p>What I would do if child items could be added, updated and deleted:</p> <pre><code>public void UpdateEntity(ParentItem parent) { // Load original parent including the child item collection var originalParent = _dbContext.ParentItems .Where(p =&gt; p.ID == parent.ID) .Include(p =&gt; p.ChildItems) .SingleOrDefault(); // We assume that the parent is still in the DB and don't check for null // Update scalar properties of parent, // can be omitted if we don't expect changes of the scalar properties var parentEntry = _dbContext.Entry(originalParent); parentEntry.CurrentValues.SetValues(parent); foreach (var childItem in parent.ChildItems) { var originalChildItem = originalParent.ChildItems .Where(c =&gt; c.ID == childItem.ID &amp;&amp; c.ID != 0) .SingleOrDefault(); // Is original child item with same ID in DB? if (originalChildItem != null) { // Yes -&gt; Update scalar properties of child item var childEntry = _dbContext.Entry(originalChildItem); childEntry.CurrentValues.SetValues(childItem); } else { // No -&gt; It's a new child item -&gt; Insert childItem.ID = 0; originalParent.ChildItems.Add(childItem); } } // Don't consider the child items we have just added above. // (We need to make a copy of the list by using .ToList() because // _dbContext.ChildItems.Remove in this loop does not only delete // from the context but also from the child collection. Without making // the copy we would modify the collection we are just interating // through - which is forbidden and would lead to an exception.) foreach (var originalChildItem in originalParent.ChildItems.Where(c =&gt; c.ID != 0).ToList()) { // Are there child items in the DB which are NOT in the // new child item collection anymore? if (!parent.ChildItems.Any(c =&gt; c.ID == originalChildItem.ID)) // Yes -&gt; It's a deleted child item -&gt; Delete _dbContext.ChildItems.Remove(originalChildItem); } _dbContext.SaveChanges(); } </code></pre> <p>Note: This is not tested. It's assuming that the child item collection is of type <code>ICollection</code>. (I usually have <code>IList</code> and then the code looks a bit different.) I've also stripped away all repository abstractions to keep it simple.</p> <p>I don't know if that is a good solution, but I believe that some kind of hard work along these lines must be done to take care of all kinds of changes in the navigation collection. I would also be happy to see an easier way of doing it.</p>
{ "question_id": 5538974, "question_date": "2011-04-04T13:13:27.907Z", "question_score": 211, "tags": "entity-framework|entity-framework-4.1", "answer_id": 5540956, "answer_date": "2011-04-04T15:45:09.717Z", "answer_score": 169 }
Please answer the following Stack Overflow question: Title: How to make layout with View fill the remaining space? <p>I'm designing my application UI. I need a layout looks like this:</p> <p><img src="https://i.stack.imgur.com/t5Ulu.png" alt="Example of desired layout"></p> <p>(&lt; and > are Buttons). The problem is, I don't know how to make sure the TextView will fill the remaining space, with two buttons have fixed size.</p> <p>If I use fill_parent for Text View, the second button (>) can't be shown.</p> <p>How can I craft a layout that looks like the image?</p>
<p>Answer from woodshy worked for me, and it is simpler than the answer by Ungureanu Liviu since it does not use <code>RelativeLayout</code>. I am giving my layout for clarity:</p> <pre><code>&lt;LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" &gt; &lt;Button android:layout_width = "80dp" android:layout_weight = "0" android:layout_height = "wrap_content" android:text="&amp;lt;"/&gt; &lt;TextView android:layout_width = "fill_parent" android:layout_height = "wrap_content" android:layout_weight = "1"/&gt; &lt;Button android:layout_width = "80dp" android:layout_weight = "0" android:layout_height = "wrap_content" android:text="&amp;gt;"/&gt; &lt;/LinearLayout&gt; </code></pre>
{ "question_id": 6316540, "question_date": "2011-06-11T14:45:56.430Z", "question_score": 211, "tags": "android|layout|android-layout", "answer_id": 25781167, "answer_date": "2014-09-11T07:04:50.873Z", "answer_score": 240 }
Please answer the following Stack Overflow question: Title: ModelState.AddModelError - How can I add an error that isn't for a property? <p>I am checking my database in <code>Create(FooViewModel fvm){...}</code> to see if the <code>fvm.prop1</code> and <code>fvm.prop2</code> already exist in that combination; if so, I want to add an error to the modelstate, then return the whole view. I tried:</p> <pre class="lang-cs prettyprint-override"><code>public ActionResult Create(FooViewModel fvm){ if (ThatComboAlreadyExists(fvm)) { ModelState.AddModelError("Model", "There is already one like that"); return View(fvm); } } </code></pre> <p>...but I get no display of errors in the <code>Html.ValidationSummary</code>, which is where I assume they would appear. I have the suspicion that "Model" is not the right key, but I haven't been able to find anything a la Google. </p>
<p>I eventually stumbled upon <a href="http://www.asp.net/entity-framework/tutorials/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application" rel="noreferrer">an example</a> of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call: </p> <pre><code>ModelState.AddModelError(string key, string errorMessage); </code></pre> <p>but use an empty string for the key:</p> <pre><code>ModelState.AddModelError(string.Empty, "There is something wrong with Foo."); </code></pre> <p>The error message will present itself in the <code>&lt;%: Html.ValidationSummary() %&gt;</code> as you'd expect.</p>
{ "question_id": 5739362, "question_date": "2011-04-21T04:00:30.387Z", "question_score": 211, "tags": "asp.net-mvc-2|asp.net-mvc-2-validation|modelstate", "answer_id": 5740852, "answer_date": "2011-04-21T07:19:51.897Z", "answer_score": 367 }
Please answer the following Stack Overflow question: Title: Is there a common Java utility to break a list into batches? <p>I wrote myself a utility to break a list into batches of given size. I just wanted to know if there is already any apache commons util for this.</p> <pre><code>public static &lt;T&gt; List&lt;List&lt;T&gt;&gt; getBatches(List&lt;T&gt; collection,int batchSize){ int i = 0; List&lt;List&lt;T&gt;&gt; batches = new ArrayList&lt;List&lt;T&gt;&gt;(); while(i&lt;collection.size()){ int nextInc = Math.min(collection.size()-i,batchSize); List&lt;T&gt; batch = collection.subList(i,i+nextInc); batches.add(batch); i = i + nextInc; } return batches; } </code></pre> <p>Please let me know if there any existing utility already for the same.</p>
<p>Check out <a href="https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/Lists.html#partition(java.util.List,%20int)" rel="noreferrer"> <code>Lists.partition(java.util.List, int)</code></a> from <a href="http://code.google.com/p/guava-libraries/" rel="noreferrer">Google Guava</a>:</p> <blockquote> <p>Returns consecutive sublists of a list, each of the same size (the final list may be smaller). For example, partitioning a list containing <code>[a, b, c, d, e]</code> with a partition size of 3 yields <code>[[a, b, c]</code>, <code>[d, e]]</code> -- an outer list containing two inner lists of three and two elements, all in the original order.</p> </blockquote>
{ "question_id": 12026885, "question_date": "2012-08-19T13:34:23.357Z", "question_score": 211, "tags": "java|collections", "answer_id": 12026908, "answer_date": "2012-08-19T13:38:07.477Z", "answer_score": 325 }
Please answer the following Stack Overflow question: Title: How to determine MIME type of file in android? <p>Suppose I have a full path of file like:(/sdcard/tlogo.png). I want to know its mime type.</p> <p>I created a function for it </p> <pre><code>public static String getMimeType(File file, Context context) { Uri uri = Uri.fromFile(file); ContentResolver cR = context.getContentResolver(); MimeTypeMap mime = MimeTypeMap.getSingleton(); String type = mime.getExtensionFromMimeType(cR.getType(uri)); return type; } </code></pre> <p>but when i call it, it returns null.</p> <pre><code>File file = new File(filePath); String fileType=CommonFunctions.getMimeType(file, context); </code></pre>
<p>First and foremost, you should consider calling <code>MimeTypeMap#getMimeTypeFromExtension()</code>, like this:</p> <pre><code>// url = file path or whatever suitable URL you want. public static String getMimeType(String url) { String type = null; String extension = MimeTypeMap.getFileExtensionFromUrl(url); if (extension != null) { type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } return type; } </code></pre>
{ "question_id": 8589645, "question_date": "2011-12-21T12:13:03.427Z", "question_score": 211, "tags": "android|filesystems|mime-types", "answer_id": 8591230, "answer_date": "2011-12-21T14:17:09.450Z", "answer_score": 370 }
Please answer the following Stack Overflow question: Title: How can I mix LaTeX in with Markdown? <p>I've been using Markdown for class notes, and it's great. I even do some preprocessing on the Markdown so I can do things like tables. But this term I'm teaching a class with a lot of math, and I'd love to be able to put LaTeX formulas with Markdown, something like this:</p> <pre class="lang-latex prettyprint-override"><code>The refinement relation is written $a \sqsubseteq b$, which can be pronounced "$a$ approximates $b$" or "$b$ is at least as defined as $a$". </code></pre> <p>I'd like to be able to take each fragment of LaTeX and preprocess it into a nice antialiased PNG file which I could then include in my Markdown via the HTML <code>&lt;img&gt;</code> tag. But I have absolutely no idea how to take a fragment of LaTeX and get a nice image that</p> <ul> <li>Has the right bounding box</li> <li>Is antialiased</li> </ul> <p>All I know how to do is get full pages in DVI, PostScript, or PDF formats.</p> <p>I'm sure this problem has been addressed, but I haven't been able to guess the right search terms. Any suggestions how to solve it or where to look for an existing solution?</p> <hr> <p><strong>EDIT</strong>: Having installed mathTeX, I can say that the code is inflexible, that it violates the Linux Filesystem Hierarchy standard, and that it is amateur work&mdash;in both the good and bad senses of that word. The code is so complex that there are no obvious faults. I will be looking for alternatives.</p> <p>Also, it's clear that at bottom, solutions are based on <a href="http://savannah.nongnu.org/projects/dvipng/" rel="noreferrer"><code>dvipng</code></a>.</p> <hr> <p><strong>ONE YEAR LATER</strong>: I never did get the seamless integration I had been hoping for, but I am limping along on a script of my own devising. It turns out that instead of <code>dvipng</code> it is a little easier to use <code>dvips -E</code> and the <code>convert</code> program of ImageMagick. The benefits are slightly more control of things like scaling, and ease of making a transparent background. The curious can inspect <a href="http://www.cs.tufts.edu/comp/105-2011s/notes.html" rel="noreferrer">this example</a>. </p> <p>I can't recommend this solution to anyone. But I can't recommend MathTeX either.</p>
<p>Have you tried with <a href="http://johnmacfarlane.net/pandoc/" rel="noreferrer">Pandoc</a>?</p> <blockquote> <p><strong>EDIT:</strong></p> <p>Although the documentation has become a bit complex, <strong>pandoc</strong> has supported <em>inline LaTeX</em> and <em>LaTeX templates</em> for 10 years.</p> <p>Documents like the following one can be written in <em>Markdown</em>:</p> <pre><code>--- title: Just say hello! author: My Friend header-includes: | \usepackage{tikz,pgfplots} \usepackage{fancyhdr} \pagestyle{fancy} \fancyhead[CO,CE]{This is fancy} \fancyfoot[CO,CE]{So is this} \fancyfoot[LE,RO]{\thepage} abstract: This is a pandoc test with Markdown + inline LaTeX --- Just say hello! =============== This could be a good example or inlined \LaTeX: \begin{tikzpicture} \begin{axis} \addplot[color=red]{exp(x)}; \end{axis} \end{tikzpicture} %Here ends the furst plot \hskip 5pt %Here begins the 3d plot \begin{tikzpicture} \begin{axis} \addplot3[ surf, ] {exp(-x^2-y^2)*x}; \end{axis} \end{tikzpicture} And now, just a few words to terminate: &gt; Goodbye folks! </code></pre> <p>Which can be converted to LaTeX using commands like this: <code>pandoc -s -i Hello.md -o Hello.tex</code></p> <p>Following is an image of the converted <code>Hello.md</code> to <code>Hello.pdf</code> file using <strong>MiKTeX</strong> as LaTeX processor with the command: <code>pandoc -s -i Hello.md -o Hello.pdf</code></p> <p><a href="https://i.stack.imgur.com/UE6hx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UE6hx.png" alt="enter image description here" /></a></p> <p>Finally, there are some open source <em>LaTeX templates</em> like this one: <a href="https://github.com/Wandmalfarbe/pandoc-latex-template" rel="noreferrer">https://github.com/Wandmalfarbe/pandoc-latex-template</a>, that can be used for better formatting.</p> <p>As always, the reader should dig deeper if he has less trivial use cases than presented here.</p> </blockquote>
{ "question_id": 2188884, "question_date": "2010-02-03T00:36:19.193Z", "question_score": 211, "tags": "html|latex|markdown|mathematical-typesetting", "answer_id": 2552701, "answer_date": "2010-03-31T12:08:20.407Z", "answer_score": 87 }
Please answer the following Stack Overflow question: Title: Find out a Git branch creator <p>I want to find out who created a branch.</p> <p>I am sort of able to do so with:</p> <pre><code>git branch -a | xargs -L 1 bash -c 'echo "$1 `git log --pretty=format:"%H %an" $1^..$1`"' _ </code></pre> <p>However, this returns the last committer per branch, not necessarily the person who created the branch.</p>
<p>A branch is nothing but a commit pointer. As such, it doesn't track metadata like "who created me." See for yourself. Try <code>cat .git/refs/heads/&lt;branch&gt;</code> in your repository.</p> <p>That written, if you're really into tracking this information in your repository, check out <a href="https://stackoverflow.com/a/11886179/877115">branch descriptions.</a> They allow you to attach arbitrary metadata to branches, locally at least.</p> <p>Also <a href="https://stackoverflow.com/a/19135644/877115">DarVar's answer below</a> is a very clever way to get at this information.</p>
{ "question_id": 12055198, "question_date": "2012-08-21T12:48:39.450Z", "question_score": 211, "tags": "git|git-branch", "answer_id": 12055538, "answer_date": "2012-08-21T13:06:26.710Z", "answer_score": 74 }
Please answer the following Stack Overflow question: Title: How do I open phone settings when a button is clicked? <p>I am trying to implement a feature in an App that shows an alert when the internet connection is not available. The alert has two actions (OK and Settings), whenever a user clicks on settings, I want to take them to the phone settings programmatically.</p> <p>I am using Swift and Xcode.</p>
<p>Using <code>UIApplication.openSettingsURLString</code></p> <p>Update for Swift 5.1</p> <pre><code> override func viewDidAppear(_ animated: Bool) { let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert) let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -&gt; Void in guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.open(settingsUrl, completionHandler: { (success) in print("Settings opened: \(success)") // Prints true }) } } alertController.addAction(settingsAction) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } </code></pre> <p>Swift 4.2</p> <pre><code>override func viewDidAppear(_ animated: Bool) { let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert) let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -&gt; Void in guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else { return } if UIApplication.shared.canOpenURL(settingsUrl) { UIApplication.shared.open(settingsUrl, completionHandler: { (success) in print("Settings opened: \(success)") // Prints true }) } } alertController.addAction(settingsAction) let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil) alertController.addAction(cancelAction) present(alertController, animated: true, completion: nil) } </code></pre>
{ "question_id": 28152526, "question_date": "2015-01-26T14:52:29.340Z", "question_score": 211, "tags": "ios|swift|settings", "answer_id": 28152624, "answer_date": "2015-01-26T14:57:26.550Z", "answer_score": 391 }
Please answer the following Stack Overflow question: Title: Visual studio code - keyboard shortcuts - expand/collapse all <p>Trying to find the equivalent to <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>-</kbd> in Intellij that collapses/expands all functions.</p>
<p>Here it is. </p> <pre><code>Ctrl+Shift+[ Fold (collapse) region editor.fold Ctrl+Shift+] Unfold (uncollapse) region editor.unfold Ctrl+K Ctrl+[ Fold (collapse) all subregions editor.foldRecursively Ctrl+K Ctrl+] Unfold (uncollapse) all subregions editor.unfoldRecursively Ctrl+K Ctrl+0 Fold (collapse) all regions editor.foldAll Ctrl+K Ctrl+J Unfold (uncollapse) all regions </code></pre> <p>Take Look at Visual studio Code <a href="https://code.visualstudio.com/docs/customization/keybindings" rel="noreferrer">Keybindings</a> section at this link.</p> <p>Also Platform specific Key board shortcuts available in pdf.here is the links</p> <p><a href="https://code.visualstudio.com/shortcuts/keyboard-shortcuts-windows.pdf" rel="noreferrer">Windows</a>,<a href="https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf" rel="noreferrer">MAC</a>,<a href="https://code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf" rel="noreferrer">Linux</a></p>
{ "question_id": 39718412, "question_date": "2016-09-27T07:17:31.843Z", "question_score": 211, "tags": "visual-studio-code", "answer_id": 39718649, "answer_date": "2016-09-27T07:29:07.210Z", "answer_score": 371 }
Please answer the following Stack Overflow question: Title: Angular JS: What is the need of the directive’s link function when we already had directive’s controller with scope? <p>I need to perform some operations on scope and the template. It seems that I can do that in either the <code>link</code> function or the <code>controller</code> function (since both have access to the scope).</p> <p>When is it the case when I have to use <code>link</code> function and not the controller?</p> <pre><code>angular.module('myApp').directive('abc', function($timeout) { return { restrict: 'EA', replace: true, transclude: true, scope: true, link: function(scope, elem, attr) { /* link function */ }, controller: function($scope, $element) { /* controller function */ } }; } </code></pre> <p>Also, I understand that <code>link</code> is the non-angular world. So, I can use <code>$watch</code>, <code>$digest</code> and <code>$apply</code>.</p> <p>What is the significance of the <code>link</code> function, when we already had controller?</p>
<p>After my <strong>initial</strong> struggle with the <code>link</code> and <code>controller</code> functions and reading quite a lot about them, I think now I have the answer.</p> <p>First lets <strong>understand</strong>,</p> <p><strong>How do angular directives work in a nutshell:</strong></p> <ul> <li><p>We begin with a template (as a string or loaded to a string)</p> <p><code>var templateString = '&lt;div my-directive&gt;{{5 + 10}}&lt;/div&gt;';</code></p></li> <li><p>Now, this <code>templateString</code> is wrapped as an <strong>angular element</strong></p> <p><code>var el = angular.element(templateString);</code></p></li> <li><p>With <code>el</code>, now we compile it with <code>$compile</code> to get back the <strong>link</strong> function.</p> <p><code>var l = $compile(el)</code></p> <p>Here is what happens,</p> <ul> <li><code>$compile</code> walks through the whole template and collects all the directives that it recognizes.</li> <li>All the directives that are discovered are <strong>compiled recursively</strong> and their <code>link</code> functions are collected.</li> <li>Then, all the <code>link</code> functions are wrapped in a new <code>link</code> function and returned as <code>l</code>.</li> </ul></li> <li><p>Finally, we provide <code>scope</code> function to this <code>l</code> (link) function which further executes the wrapped link functions with this <code>scope</code> and their corresponding elements.</p> <p><code>l(scope)</code></p></li> <li><p>This adds the <code>template</code> as a new node to the <code>DOM</code> and invokes <code>controller</code> which adds its watches to the <strong>scope</strong> which is shared with the template in DOM.</p></li> </ul> <p><img src="https://i.stack.imgur.com/0PwGA.png" alt="enter image description here"></p> <p>Comparing <strong>compile</strong> vs <strong>link</strong> vs <strong>controller</strong> :</p> <ul> <li><p>Every directive is <strong>compiled</strong> only once and <strong>link</strong> function is retained for re-use. Therefore, if there's something applicable to all instances of a directive should be performed inside directive's <code>compile</code> function.</p></li> <li><p>Now, after compilation we have <code>link</code> function which is executed while attaching the <strong>template</strong> to the <strong>DOM</strong>. So, therefore we perform everything that is specific to every instance of the directive. For eg: <strong>attaching events</strong>, <strong>mutating the template based on scope</strong>, etc.</p></li> <li><p>Finally, the <strong>controller</strong> is meant to be available to be live and reactive while the directive works on the <code>DOM</code> (after getting attached). Therefore:</p> <p>(1) After setting up the view[<strong>V</strong>] (i.e. template) with link. <code>$scope</code> is our [<strong>M</strong>] and <code>$controller</code> is our [<strong>C</strong>] in <strong>M V C</strong></p> <p>(2) Take advantage the <strong>2-way</strong> binding with <strong>$scope</strong> by setting up watches.</p> <p>(3) <code>$scope</code> watches are expected to be added in the controller since this is what is watching the template during run-time.</p> <p>(4) Finally, <code>controller</code> is also used to be able to communicate among related directives. (Like <code>myTabs</code> example in <a href="https://docs.angularjs.org/guide/directive" rel="noreferrer">https://docs.angularjs.org/guide/directive</a>)</p> <p>(5) It's true that we could've done all this in the <code>link</code> function as well but its about <strong>separation of concerns</strong>.</p></li> </ul> <p>Therefore, finally we have the following which fits all the pieces perfectly :</p> <p><img src="https://i.stack.imgur.com/SAFpN.png" alt="enter image description here"></p>
{ "question_id": 20018507, "question_date": "2013-11-16T12:34:11.733Z", "question_score": 211, "tags": "javascript|angularjs|angularjs-directive", "answer_id": 23722351, "answer_date": "2014-05-18T13:18:28.800Z", "answer_score": 315 }
Please answer the following Stack Overflow question: Title: Cache an HTTP 'Get' service response in AngularJS? <p>I want to be able to create a custom AngularJS service that makes an HTTP 'Get' request when its data object is empty and populates the data object on success.</p> <p>The next time a call is made to this service, I would like to bypass the overhead of making the HTTP request again and instead return the cached data object.</p> <p>Is this possible?</p>
<p>Angular's <a href="http://docs.angularjs.org/api/ng.$http" rel="noreferrer">$http</a> has a <a href="https://docs.angularjs.org/api/ng/service/$http#caching" rel="noreferrer">cache built in</a>. According to the docs:</p> <blockquote> <p><strong>cache</strong> – {boolean|Object} – A boolean value <strong>or object</strong> created with $cacheFactory to enable or disable caching of the HTTP response. See <a href="https://docs.angularjs.org/api/ng/service/$http#caching" rel="noreferrer">$http Caching for more information</a>.</p> </blockquote> <h1>Boolean value</h1> <p>So you can set <code>cache</code> to <strong>true</strong> in its options:</p> <pre><code>$http.get(url, { cache: true}).success(...); </code></pre> <p>or, if you prefer the config type of call:</p> <pre><code>$http({ cache: true, url: url, method: 'GET'}).success(...); </code></pre> <h1>Cache Object</h1> <p>You can also use a cache factory:</p> <pre><code>var cache = $cacheFactory('myCache'); $http.get(url, { cache: cache }) </code></pre> <p>You can implement it yourself using <a href="http://docs.angularjs.org/api/ng.$cacheFactory" rel="noreferrer">$cacheFactory</a> (especially handly when using $resource):</p> <pre><code>var cache = $cacheFactory('myCache'); var data = cache.get(someKey); if (!data) { $http.get(url).success(function(result) { data = result; cache.put(someKey, data); }); } </code></pre>
{ "question_id": 14117653, "question_date": "2013-01-02T06:15:39.403Z", "question_score": 211, "tags": "angularjs|ajax|caching|http-get", "answer_id": 14117744, "answer_date": "2013-01-02T06:25:38.020Z", "answer_score": 317 }
Please answer the following Stack Overflow question: Title: How to use newline '\n' in f-string to format output in Python 3.6? <p>I would like to know how to format this case in a Pythonic way with f-strings:</p> <pre><code>names = ['Adam', 'Bob', 'Cyril'] text = f"Winners are:\n{'\n'.join(names)}" print(text) </code></pre> <p>The problem is that <code>'\'</code> cannot be used inside the <code>{...}</code> expression portions of an f-string. Expected output:</p> <pre><code>Winners are: Adam Bob Cyril </code></pre>
<p>You can't. Backslashes cannot appear inside the curly braces <code>{}</code>; doing so results in a <code>SyntaxError</code>: </p> <pre><code>&gt;&gt;&gt; f'{\}' SyntaxError: f-string expression part cannot include a backslash </code></pre> <p>This is specified in the <a href="https://www.python.org/dev/peps/pep-0498/#escape-sequences" rel="noreferrer">PEP</a> for f-strings:</p> <blockquote> <p>Backslashes may not appear inside the expression portions of f-strings, [...]</p> </blockquote> <p>One option is assinging <code>'\n'</code> to a name and then <code>.join</code> on that inside the <code>f</code>-string; that is, without using a literal:</p> <pre><code>names = ['Adam', 'Bob', 'Cyril'] nl = '\n' text = f"Winners are:{nl}{nl.join(names)}" print(text) </code></pre> <p>Results in:</p> <pre><code>Winners are: Adam Bob Cyril </code></pre> <p>Another option, as specified by @wim, is to use <code>chr(10)</code> to get <code>\n</code> returned and then join there. <code>f"Winners are:\n{chr(10).join(names)}"</code></p> <p>Yet another, of course, is to <code>'\n'.join</code> beforehand and then add the name accordingly:</p> <pre><code>n = "\n".join(names) text = f"Winners are:\n{n}" </code></pre> <p>which results in the same output.</p> <h2><em>Note:</em></h2> <p>This is one of the small differences between <code>f</code>-strings and <code>str.format</code>. In the latter, you can always use punctuation granted that a corresponding wacky dict is unpacked that contains those keys:</p> <pre><code>&gt;&gt;&gt; "{\\} {*}".format(**{"\\": 'Hello', "*": 'World!'}) "Hello World!" </code></pre> <p><sub>(Please don't do this.)</sub></p> <p>In the former, punctuation isn't allowed because you can't have identifiers that use them.</p> <hr> <p>Aside: I would definitely opt for <code>print</code> or <code>format</code>, as the other answers suggest as an alternative. The options I've given only apply if you <em>must</em> for some reason use f-strings. </p> <p>Just because something is new, doesn't mean you should try and do everything with it ;-)</p>
{ "question_id": 44780357, "question_date": "2017-06-27T12:30:35.803Z", "question_score": 211, "tags": "python|python-3.x|newline|python-3.6|f-string", "answer_id": 44780467, "answer_date": "2017-06-27T12:35:42.140Z", "answer_score": 227 }
Please answer the following Stack Overflow question: Title: How to add a 'or' condition in #ifdef <p>How can I add a 'or' condition in #ifdef ?</p> <p>I have tried:</p> <pre class="lang-c prettyprint-override"><code>#ifdef CONDITION1 || CONDITION2 #endif </code></pre> <p>This does not work.</p>
<pre><code>#if defined(CONDITION1) || defined(CONDITION2) </code></pre> <p>should work. :)</p> <p><code>#ifdef</code> is a bit less typing, but doesn't work well with more complex conditions</p>
{ "question_id": 2998864, "question_date": "2010-06-08T15:38:34.267Z", "question_score": 211, "tags": "c++|c|c-preprocessor", "answer_id": 2998876, "answer_date": "2010-06-08T15:39:41.247Z", "answer_score": 387 }
Please answer the following Stack Overflow question: Title: How can I assign an ID to a view programmatically? <p>In an XML file, we can assign an ID to a view like <code>android:id="@+id/something"</code> and then call <code>findViewById()</code>, but when creating a view programmatically, how do I assign an ID?</p> <p>I think <code>setId()</code> is not the same as default assignment. <code>setId()</code> is extra.</p> <p>Can anybody correct me?</p>
<h2>Android <code>id</code> overview</h2> <p>An Android <code>id</code> is an integer commonly used to identify views; this <code>id</code> can be assigned via XML (when possible) and via code (programmatically.) The <code>id</code> is most useful for getting references for XML-defined <code>View</code>s generated by an <code>Inflater</code> (such as by using <code>setContentView</code>.)</p> <h3>Assign <code>id</code> via <code>XML</code></h3> <ul> <li>Add an attribute of <code>android:id="@+id/</code>somename<code>"</code> to your view.</li> <li>When your application is built, the <code>android:id</code> will be assigned a <strong>unique</strong> <code>int</code> for use in code.</li> <li>Reference your <code>android:id</code>'s <code>int</code> value in code using "<code>R.id.</code>somename" (effectively a constant.)</li> <li><em>this <code>int</code> can change from build to build</em> so <strong>never copy an id</strong> from <code>gen/</code>package.name/<code>R.java</code>, just use "<code>R.id.</code>somename".</li> <li>(Also, an <code>id</code> assigned to a <code>Preference</code> in XML is not used when the <code>Preference</code> generates its <code>View</code>.)</li> </ul> <h3>Assign <code>id</code> via code (programmatically)</h3> <ul> <li>Manually set <code>id</code>s using <code>someView.setId(</code>int<code>);</code></li> <li>The <code>int</code> must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)</li> <li><em>For example, if creating and numbering several views representing items, you could use their item number.</em></li> </ul> <h3>Uniqueness of <code>id</code>s</h3> <ul> <li><code>XML</code>-assigned <code>id</code>s will be unique.</li> <li>Code-assigned <code>id</code>s do <em>not</em> have to be unique</li> <li>Code-assigned <code>id</code>s can (theoretically) conflict with <code>XML</code>-assigned <code>id</code>s.</li> <li>These conflicting <code>id</code>s won't matter if queried correctly <em>(keep reading)</em>.</li> </ul> <h3>When (and why) conflicting <code>id</code>s don't matter</h3> <ul> <li><code>findViewById(int)</code> will iterate depth-first recursively through the view hierarchy <em>from the View you specify</em> and return the first <code>View</code> it finds with a matching <code>id</code>.</li> <li>As long as there are no code-assigned <code>id</code>s assigned before an XML-defined <code>id</code> in the hierarchy, <code>findViewById(R.id.somename)</code> will always return the XML-defined View so <code>id</code>'d.</li> </ul> <h3>Dynamically Creating Views and Assigning <code>ID</code>s</h3> <ul> <li>In layout XML, define an empty <code>ViewGroup</code> with <code>id</code>.</li> <li><em>Such as a <code>LinearLayout</code> with <code>android:id="@+id/placeholder"</code>.</em></li> <li>Use code to populate the placeholder <code>ViewGroup</code> with <code>View</code>s.</li> <li>If you need or want, assign any <code>id</code>s that are convenient to each view.</li> <li><p>Query these child views using placeholder.findViewById(convenientInt);</p></li> <li><p>API 17 introduced <code>View.generateViewId()</code> which allows you to generate a unique ID. </p></li> </ul> <p><strong>If you choose to keep references to your views around</strong>, be sure to instantiate them with <code>getApplicationContext()</code> and be sure to set each reference to null in <code>onDestroy</code>. Apparently <em>leaking</em> the <code>Activity</code> (hanging onto it after is is destroyed) is wasteful.. :)</p> <h3>Reserve an XML <code>android:id</code> for use in code</h3> <p><em>API 17 introduced</em> <code>View.generateViewId()</code> <em>which generates a unique ID.</em> (Thanks to take-chances-make-changes for pointing this out.)*</p> <p>If your <code>ViewGroup</code> cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:</p> <p><strong>Here, <em>values/ids.xml</em> defines a custom <code>id</code>:</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;resources&gt; &lt;item name="reservedNamedId" type="id"/&gt; &lt;/resources&gt; </code></pre> <p><strong>Then once the ViewGroup or View has been created, you can attach the custom id</strong></p> <pre><code>myViewGroup.setId(R.id.reservedNamedId); </code></pre> <h2>Conflicting <code>id</code> example</h2> <p>For clarity by way of obfuscating example, lets examine what happens when there is an <code>id</code> conflict behind the scenes.</p> <p><strong>layout/mylayout.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" &gt; &lt;LinearLayout android:id="@+id/placeholder" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" &gt; &lt;/LinearLayout&gt; </code></pre> <p><em>To simulate a conflict, lets say our latest build assigned <code>R.id.placeholder</code>(<code>@+id/placeholder</code>) an <code>int</code> value of</em> <code>12</code>..</p> <p>Next, <strong>MyActivity.java</strong> defines some adds views programmatically (via code):</p> <pre><code>int placeholderId = R.id.placeholder; // placeholderId==12 // returns *placeholder* which has id==12: ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId); for (int i=0; i&lt;20; i++){ TextView tv = new TextView(this.getApplicationContext()); // One new TextView will also be assigned an id==12: tv.setId(i); placeholder.addView(tv); } </code></pre> <p>So <code>placeholder</code> and one of our new <code>TextView</code>s both have an <code>id</code> of 12! But this isn't really a problem if we query placeholder's child views:</p> <pre><code>// Will return a generated TextView: placeholder.findViewById(12); // Whereas this will return the ViewGroup *placeholder*; // as long as its R.id remains 12: Activity.this.findViewById(12); </code></pre> <p>*Not so bad</p>
{ "question_id": 8460680, "question_date": "2011-12-10T23:17:12.733Z", "question_score": 211, "tags": "android|android-view|android-resources|findviewbyid|android-identifiers", "answer_id": 13241629, "answer_date": "2012-11-05T22:45:50.790Z", "answer_score": 535 }
Please answer the following Stack Overflow question: Title: Hashing a dictionary? <p>For caching purposes I need to generate a cache key from GET arguments which are present in a dict.</p> <p>Currently I'm using <code>sha1(repr(sorted(my_dict.items())))</code> (<code>sha1()</code> is a convenience method that uses <a href="https://docs.python.org/3/library/hashlib.html" rel="noreferrer">hashlib</a> internally) but I'm curious if there's a better way.</p>
<p>If your dictionary is not nested, you could make a frozenset with the dict's items and use <a href="https://docs.python.org/2/library/functions.html#hash" rel="noreferrer"><code>hash()</code></a>:</p> <pre><code>hash(frozenset(my_dict.items())) </code></pre> <p>This is much less computationally intensive than generating the JSON string or representation of the dictionary.</p> <p>UPDATE: Please see the comments below, why this approach might not produce a stable result. </p>
{ "question_id": 5884066, "question_date": "2011-05-04T13:19:38.897Z", "question_score": 211, "tags": "python|hash|dictionary", "answer_id": 5884123, "answer_date": "2011-05-04T13:24:33.580Z", "answer_score": 141 }
Please answer the following Stack Overflow question: Title: Android Studio was unable to find a valid Jvm (Related to MAC OS) <p>I am unable to start my Android Studio for Android development on Mac OS (10.10.1 - Yosemite)</p>
<p>Open the application package for <em>Android Studio</em> in finder, and edit the <strong>Info.plist</strong> file. Change the key JVMversion. Put 1.6+ instead of 1.6*. That worked for me!.</p> <p>Cheers!</p> <p>Edited:</p> <p>While this was necessary in older versions of Android Studio, this is no longer recommended. See the official statement </p> <p><strong>"Please note: Do not edit Info.plist to pick a different version. That will break not only the application signature, but also future patch updates to your installation."</strong> </p> <p>Antonio Jose's <a href="https://stackoverflow.com/a/27370525/906523">answer</a> is the correct one.</p> <p>Thanks aried3r!</p>
{ "question_id": 27369269, "question_date": "2014-12-09T00:03:39.030Z", "question_score": 211, "tags": "java|android|macos|android-studio|ide", "answer_id": 27369596, "answer_date": "2014-12-09T00:38:05.737Z", "answer_score": 355 }
Please answer the following Stack Overflow question: Title: ASP.NET Identity DbContext confusion <p>A default MVC 5 App comes with this piece of code in IdentityModels.cs - this piece of code is for all the ASP.NET Identity operations for the default templates:</p> <pre><code>public class ApplicationDbContext : IdentityDbContext&lt;ApplicationUser&gt; { public ApplicationDbContext() : base("DefaultConnection") { } } </code></pre> <p>If I scaffold a new controller using views with Entity Framework and create a "New data context..." in the dialog, I get this generated for me:</p> <pre><code>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace WebApplication1.Models { public class AllTheOtherStuffDbContext : DbContext { // You can add custom code to this file. Changes will not be overwritten. // // If you want Entity Framework to drop and regenerate your database // automatically whenever you change your model schema, please use data migrations. // For more information refer to the documentation: // http://msdn.microsoft.com/en-us/data/jj591621.aspx public AllTheOtherStuffDbContext() : base("name=AllTheOtherStuffDbContext") { } public System.Data.Entity.DbSet&lt;WebApplication1.Models.Movie&gt; Movies { get; set; } } } </code></pre> <p>If I scaffold another controller + view using EF, say for instance for an Animal model, this new line would get autogenerated right under <code>public System.Data.Entity.DbSet&lt;WebApplication1.Models.Movie&gt; Movies { get; set; }</code> - like this:</p> <pre><code>using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace WebApplication1.Models { public class AllTheOtherStuffDbContext : DbContext { // You can add custom code to this file. Changes will not be overwritten. // // If you want Entity Framework to drop and regenerate your database // automatically whenever you change your model schema, please use data migrations. // For more information refer to the documentation: // http://msdn.microsoft.com/en-us/data/jj591621.aspx public AllTheOtherStuffDbContext() : base("name=AllTheOtherStuffDbContext") { } public System.Data.Entity.DbSet&lt;WebApplication1.Models.Movie&gt; Movies { get; set; } public System.Data.Entity.DbSet&lt;WebApplication1.Models.Animal&gt; Animals { get; set; } } } </code></pre> <p><code>ApplicationDbContext</code> (for all the ASP.NET Identity stuff) inherits from <code>IdentityDbContext</code> which in turn inherits from <code>DbContext</code>. <code>AllOtherStuffDbContext</code> (for my own stuff) inherits from <code>DbContext</code>.</p> <p>So my question is:</p> <p>Which of these two (<code>ApplicationDbContext</code> and <code>AllOtherStuffDbContext</code>) should I use for all my other own models? Or should I just use the default autogenerated <code>ApplicationDbContext</code> since it shouldn't be a problem using it since it derives from the base class <code>DbContext</code>, or will there be some overhead? You should use only one <code>DbContext</code> object in your app for all your models (I've read this somewhere) so I should not even consider using both <code>ApplicationDbContext</code> and <code>AllOtherStuffDbContext</code> in a single app? Or what is best practice in MVC 5 with ASP.NET Identity?</p>
<p>I would use a single Context class inheriting from IdentityDbContext. This way you can have the context be aware of any relations between your classes and the IdentityUser and Roles of the IdentityDbContext. There is very little overhead in the IdentityDbContext, it is basically a regular DbContext with two DbSets. One for the users and one for the roles.</p>
{ "question_id": 19902756, "question_date": "2013-11-11T09:21:42.680Z", "question_score": 211, "tags": "asp.net|asp.net-mvc|entity-framework|asp.net-mvc-5|asp.net-identity", "answer_id": 19904081, "answer_date": "2013-11-11T10:30:00.243Z", "answer_score": 190 }
Please answer the following Stack Overflow question: Title: argparse module How to add option without any argument? <p>I have created a script using <code>argparse</code>.</p> <p>The script needs to take a configuration file name as an option, and user can specify whether they need to proceed totally the script or only simulate it.</p> <p>The args to be passed: <code>./script -f config_file -s</code> or <code>./script -f config_file</code>.</p> <p>It's ok for the -f config_file part, but It keeps asking me for arguments for the -s which is optionnal and should not be followed by any.</p> <p>I have tried this:</p> <pre><code>parser = argparse.ArgumentParser() parser.add_argument('-f', '--file') #parser.add_argument('-s', '--simulate', nargs = '0') args = parser.parse_args() if args.file: config_file = args.file if args.set_in_prod: simulate = True else: pass </code></pre> <p>With the following errors:</p> <pre><code>File "/usr/local/lib/python2.6/dist-packages/argparse.py", line 2169, in _get_nargs_pattern nargs_pattern = '(-*%s-*)' % '-*'.join('A' * nargs) TypeError: can't multiply sequence by non-int of type 'str' </code></pre> <p>And same errror with <code>''</code> instead of <code>0</code>.</p>
<p>As <a href="https://stackoverflow.com/questions/5262702/argparse-module-how-to-add-option-without-any-argument/5262769#5262769">@Felix Kling suggested</a> use <code>action='store_true'</code>:</p> <pre><code>&gt;&gt;&gt; from argparse import ArgumentParser &gt;&gt;&gt; p = ArgumentParser() &gt;&gt;&gt; _ = p.add_argument('-f', '--foo', action='store_true') &gt;&gt;&gt; args = p.parse_args() &gt;&gt;&gt; args.foo False &gt;&gt;&gt; args = p.parse_args(['-f']) &gt;&gt;&gt; args.foo True </code></pre>
{ "question_id": 5262702, "question_date": "2011-03-10T16:29:58.023Z", "question_score": 211, "tags": "python|argparse", "answer_id": 5271692, "answer_date": "2011-03-11T10:25:06.547Z", "answer_score": 312 }
Please answer the following Stack Overflow question: Title: How to disable textarea resizing? <p>I need to disable textarea horizontal resize. Sometimes I want to allow vertical resize on the textarea. </p> <p>Whenever I create a contact us page the textarea is making my design ugly.</p> <p>could any one give me a solution to disable it please?</p>
<p>You can use css </p> <p>disable all</p> <pre><code>textarea { resize: none; } </code></pre> <p>only vertical resize </p> <pre><code>textarea { resize: vertical; } </code></pre> <p>only horizontal resize </p> <pre><code>textarea { resize: horizontal; } </code></pre> <p>disable vertical and horizontal with limit</p> <pre><code>textarea { resize: horizontal; max-width: 400px; min-width: 200px; } </code></pre> <p>disable horizontal and vertical with limit</p> <pre><code>textarea { resize: vertical; max-height: 300px; min-height: 200px; } </code></pre> <p>I think <code>min-height</code> should be useful for you</p>
{ "question_id": 9382245, "question_date": "2012-02-21T17:32:35.153Z", "question_score": 211, "tags": "html|css", "answer_id": 9382316, "answer_date": "2012-02-21T17:37:08.707Z", "answer_score": 391 }
Please answer the following Stack Overflow question: Title: How is CountDownLatch used in Java Multithreading? <p>Can someone help me to understand what Java <code>CountDownLatch</code> is and when to use it? </p> <p>I don't have a very clear idea of how this program works. As I understand all three threads start at once and each Thread will call CountDownLatch after 3000ms. So count down will decrement one by one. After latch becomes zero the program prints "Completed". Maybe the way I understood is incorrect. </p> <pre class="lang-java prettyprint-override"><code>import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; class Processor implements Runnable { private CountDownLatch latch; public Processor(CountDownLatch latch) { this.latch = latch; } public void run() { System.out.println("Started."); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } latch.countDown(); } } </code></pre> <p>// -----------------------------------------------------</p> <pre class="lang-java prettyprint-override"><code>public class App { public static void main(String[] args) { CountDownLatch latch = new CountDownLatch(3); // coundown from 3 to 0 ExecutorService executor = Executors.newFixedThreadPool(3); // 3 Threads in pool for(int i=0; i &lt; 3; i++) { executor.submit(new Processor(latch)); // ref to latch. each time call new Processes latch will count down by 1 } try { latch.await(); // wait until latch counted down to 0 } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Completed."); } } </code></pre>
<p>Yes, you understood correctly. <code>CountDownLatch</code> works in latch principle, the main thread will wait until the gate is open. One thread waits for <em>n</em> threads, specified while creating the <code>CountDownLatch</code>.</p> <p>Any thread, usually the main thread of the application, which calls <code>CountDownLatch.await()</code> will wait until count reaches zero or it's interrupted by another thread. All other threads are required to count down by calling <code>CountDownLatch.countDown()</code> once they are completed or ready. </p> <p>As soon as count reaches zero, the waiting thread continues. One of the disadvantages/advantages of <code>CountDownLatch</code> is that it's not reusable: once count reaches zero you cannot use <code>CountDownLatch</code> any more.</p> <p><strong>Edit:</strong> </p> <p>Use <code>CountDownLatch</code> when one thread (like the main thread) requires to wait for one or more threads to complete, before it can continue processing.</p> <p>A classical example of using <code>CountDownLatch</code> in Java is a server side core Java application which uses services architecture, where multiple services are provided by multiple threads and the application cannot start processing until all services have started successfully.</p> <p>P.S. OP's question has a pretty straightforward example so I didn't include one.</p>
{ "question_id": 17827022, "question_date": "2013-07-24T06:47:48.327Z", "question_score": 211, "tags": "java|multithreading|countdown|countdownlatch", "answer_id": 17827339, "answer_date": "2013-07-24T07:06:46.260Z", "answer_score": 219 }
Please answer the following Stack Overflow question: Title: Recommended add-ons/plugins for Microsoft Visual Studio <p>Can anyone recommend any good <strong>add-ons</strong> or <strong>plugins</strong> for <code>Microsoft Visual Studio</code>?<br> Freebies are preferred, but if it is worth the cost then that's fine.</p>
<p><a href="http://weblogs.asp.net/alex_papadimoulis/archive/2004/05/25/Smart-Paster-1.1-Add-In---StringBuilder-and-Better-C_2300_-Handling.aspx" rel="noreferrer">SmartPaster</a> - (FREE) Copy/Paste code generator for strings</p> <p><a href="http://ankhsvn.open.collab.net/" rel="noreferrer">AnkhSvn</a> - (FREE) SVN Source Control Integration for VS.NET</p> <p><a href="http://www.visualsvn.com/server/" rel="noreferrer">VisualSVN Server</a> - (FREE) Source Control</p> <p><a href="http://www.jetbrains.com/resharper/index.html" rel="noreferrer">ReSharper</a> - IDE enhancement that helps with refactoring and productivity</p> <p><a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/" rel="noreferrer">CodeRush</a> - Code gen macros on steroids</p> <p><a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/Refactoring/" rel="noreferrer">Refactor</a> - Code refactoring aid</p> <p><a href="http://www.codemaid.net/" rel="noreferrer">CodeMaid</a> (FREE) - Code cleanup, organization and complexity analysis</p> <p><a href="http://www.codesmithtools.com/" rel="noreferrer">CodeSmith</a> - Code Generator</p> <p><a href="http://www.roland-weigelt.de/ghostdoc/" rel="noreferrer">GhostDoc</a> - (FREE) Simple code commenting tool</p> <p><a href="http://www.devexpress.com/Downloads/Visual_Studio_Add-in/DXCore/" rel="noreferrer">DXCore</a> (FREE) and its many awesome plugins: <a href="http://code.google.com/p/dxcorecommunityplugins/" rel="noreferrer">DxCore Community Plugins</a>, <a href="http://code.google.com/p/cr-documentor/" rel="noreferrer">CR_Documentor</a>, <a href="http://joel.fjorden.se/static.php?page=CodeStyleEnforcer" rel="noreferrer">CodeStyleEnforcer</a>, <a href="http://www.rorybecker.me.uk/DevExpress/Plugins/Community/RedGreen/" rel="noreferrer">RedGreen</a></p> <p><a href="http://www.testdriven.net/" rel="noreferrer">TestDriven.Net</a> - (FREE/PAY) Unit Testing Aid</p> <p><a href="http://www.red-gate.com/products/reflector/" rel="noreferrer">Reflector</a> - (PAY) Feature rich .Net Disassembler <a href="http://www.codeplex.com/reflectoraddins" rel="noreferrer">Reflector AddIn's</a></p> <p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=0AA30AE8-C73B-4BDD-BB1B-FE697256C459&amp;displaylang=en" rel="noreferrer">Web Deployment Projects</a> - Provides additional functionality to build and deploy Web sites and Web applications (<a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=0AA30AE8-C73B-4BDD-BB1B-FE697256C459&amp;displaylang=en" rel="noreferrer">source</a>).</p> <p>StudioTools - (FREE) Navigation assistant, code metrics tool, incremental search, file explorer in visual studio and tear off editor windows. Moved from <a href="https://web.archive.org/web/20100218144023/http://www.exactmagic.com/products/studiotools/index.html" rel="noreferrer">old site (archive.org)</a> to <a href="http://submain.com/products/studiotools.aspx" rel="noreferrer">new site</a> and discontinued.</p>
{ "question_id": 2767, "question_date": "2008-08-05T20:02:33.033Z", "question_score": 211, "tags": "visual-studio|plugins|add-on", "answer_id": 75338, "answer_date": "2008-09-16T18:17:49.600Z", "answer_score": 139 }
Please answer the following Stack Overflow question: Title: What is the meaning of three dots (...) in PHP? <p>While I am installing Magento 2 on my Server, I got an error. After investigating the code and found that there is are three dots (<code>...</code>), which is producing the error. I included the code I found below:</p> <pre class="lang-php prettyprint-override"><code>return new $type(...array_values($args)); </code></pre> <p>What is this operator called, and what is its purpose?</p>
<p>This is literally called the <a href="https://www.php.net/manual/en/migration56.new-features.php" rel="noreferrer"><code>...</code> operator in PHP</a>, but is known as the splat operator from other languages. From <a href="http://lornajane.net/posts/2014/php-5-6-and-the-splat-operator" rel="noreferrer">a 2014 LornaJane blog post</a> on the feature:</p> <blockquote> <p>This feature allows you to capture a variable number of arguments to a function, combined with &quot;normal&quot; arguments passed in if you like. It's easiest to see with an example:</p> <pre><code>function concatenate($transform, ...$strings) { $string = ''; foreach($strings as $piece) { $string .= $piece; } return($transform($string)); } </code></pre> <p>echo concatenate(&quot;strtoupper&quot;, &quot;I'd &quot;, &quot;like &quot;, 4 + 2, &quot; apples&quot;);</p> </blockquote> <p>(This would print <code>I'D LIKE 6 APPLES</code>)</p> <blockquote> <p>The parameters list in the function declaration has the <code>...</code> operator in it, and it basically means &quot; ... and everything else should go into <code>$strings</code>&quot;. You can pass 2 or more arguments into this function and the second and subsequent ones will be added to the $strings <code>array</code>, ready to be used.</p> </blockquote>
{ "question_id": 41124015, "question_date": "2016-12-13T14:51:40.627Z", "question_score": 211, "tags": "php|syntax|operators", "answer_id": 41124083, "answer_date": "2016-12-13T14:54:40.267Z", "answer_score": 298 }
Please answer the following Stack Overflow question: Title: delete_all vs destroy_all? <p>I am looking for the best approach to delete records from a table. For instance, I have a user whose user ID is across many tables. I want to delete this user and every record that has his ID in all tables.</p> <pre><code>u = User.find_by_name('JohnBoy') u.usage_indexes.destroy_all u.sources.destroy_all u.user_stats.destroy_all u.delete </code></pre> <p>This works and removes all references of the user from all tables, but I heard that <code>destroy_all</code> was very process heavy, so I tried <code>delete_all</code>. It only removes the user from his own user table and the <code>id</code> from all the other tables are made null, but leaves the records intact in them. Can someone share what the correct process is for performing a task like this? </p> <p>I see that <code>destroy_all</code> calls the <code>destroy</code> function on all associated objects but I just want to confirm the correct approach.</p>
<p>You are right. If you want to delete the User and all associated objects -> <code>destroy_all</code> However, if you just want to delete the User without suppressing all associated objects -> <code>delete_all</code></p> <p>According to this post : <a href="https://stackoverflow.com/questions/2797339/rails-dependent-destroy-vs-dependent-delete-all">Rails :dependent =&gt; :destroy VS :dependent =&gt; :delete_all</a></p> <ul> <li><code>destroy</code> / <code>destroy_all</code>: The associated objects are destroyed alongside this object by calling their destroy method</li> <li><code>delete</code> / <code>delete_all</code>: All associated objects are destroyed immediately without calling their :destroy method</li> </ul>
{ "question_id": 6698207, "question_date": "2011-07-14T18:32:13.807Z", "question_score": 211, "tags": "ruby-on-rails|ruby|database|activerecord", "answer_id": 6698259, "answer_date": "2011-07-14T18:36:44.227Z", "answer_score": 272 }
Please answer the following Stack Overflow question: Title: Convert Enumeration to a Set/List <p>Is there some one-liner bridge method to dump a given <em>Enumeration</em> to <code>java.util.List</code> or <code>java.util.Set</code>?</p> <p>Something built-in like <code>Arrays.asList()</code> or <code>Collection.toArray()</code> should exist somewhere, but I'm unable to find that in my IntelliJ debugger's evaluator window (and Google/SO results, too).</p>
<p>You can use <a href="http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#list%28java.util.Enumeration%29"><code>Collections.list()</code></a> to convert an <code>Enumeration</code> to a <code>List</code> in one line:</p> <pre><code>List&lt;T&gt; list = Collections.list(enumeration); </code></pre> <p>There's no similar method to get a <code>Set</code>, however you can still do it one line:</p> <pre><code>Set&lt;T&gt; set = new HashSet&lt;T&gt;(Collections.list(enumeration)); </code></pre>
{ "question_id": 5610822, "question_date": "2011-04-10T09:17:52.397Z", "question_score": 211, "tags": "java|collections|conventions", "answer_id": 5610838, "answer_date": "2011-04-10T09:20:05.273Z", "answer_score": 383 }
Please answer the following Stack Overflow question: Title: What is the difference between Forking and Cloning on GitHub? <p>I'd like to know the differences between doing a Fork of a project and doing a <code>clone</code> of it.</p> <p>Can I only send pull requests via GitHub if I've forked a project?</p>
<p>Basically, yes. <strong>A <code>fork</code> is just a request for GitHub to clone the project and registers it under your username</strong>; GitHub also keeps track of the relationship between the two repositories, so you can visualize the commits and pulls between the two projects (and other forks).</p> <p>You can still request that people pull from your cloned repository, even if you don't use <code>fork</code> -- but you'd have to deal with making it publicly available yourself. Or send the developers patches (see <code>git format-patch</code>) that they can apply to their trees.</p>
{ "question_id": 7057194, "question_date": "2011-08-14T13:50:51.770Z", "question_score": 211, "tags": "git|github", "answer_id": 7057224, "answer_date": "2011-08-14T13:57:39.197Z", "answer_score": 122 }
Please answer the following Stack Overflow question: Title: What is the difference between parentheses, brackets and asterisks in Angular2? <p>I have been reading the Angular 1 to 2 quick reference in the <a href="https://angular.io/docs/ts/latest/cookbook/a1-a2-quick-reference.html" rel="noreferrer">Angular website</a>, and one thing I didn't completely understand was the difference between these special characters. For example one that uses asterisks:</p> <pre class="lang-html prettyprint-override"><code>&lt;tr *ngFor=&quot;#movie of movies&quot;&gt; &lt;td&gt;{{movie.title}}&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>I understand here that the hash (#) symbol defines <code>movie</code> as a local template variable, but what does the asterisk before <code>ngFor</code> mean? And, is it necessary?</p> <p>Next, are the examples that use brackets:</p> <pre class="lang-html prettyprint-override"><code>&lt;a [routerLink]=&quot;['Movies']&quot;&gt;Movies&lt;/a&gt; </code></pre> <p>I somewhat understand that the brackets around <code>routerLink</code> bind it to that HTML attribute / Angular directive. Does this mean that they are a pointer for Angular to evaluate an expression? Like <code>[id]=&quot;movieId&quot;</code> would be the equivalent of <code>id=&quot;movie-{{movieId}}&quot;</code> in Angular 1?</p> <p>Lastly, are parentheses:</p> <pre class="lang-html prettyprint-override"><code>&lt;button (click)=&quot;toggleImage($event)&quot;&gt; </code></pre> <p>Are these only used for DOM events and can we use other events like <code>(load)=&quot;someFn()&quot;</code> or <code>(mouseenter)=&quot;someFn()&quot;</code>?</p> <p>I guess the real question is, do these symbols have a special meaning in Angular 2, and what is the easiest way to know <strong>when to use each one</strong>? Thanks!!</p>
<p>All details can be found here: <a href="https://angular.io/docs/ts/latest/guide/template-syntax.html" rel="noreferrer">https://angular.io/docs/ts/latest/guide/template-syntax.html</a></p> <ul> <li><p><code>directiveName</code> - is the short hand form for structural directives where the long form can only be applied to <code>&lt;template&gt;</code> tags. The short form implicitely wraps the element where it's applied in a <code>&lt;template&gt;</code>.</p></li> <li><p><code>[prop]="value"</code> is for object binding to properties (<code>@Input()</code> of an Angular component or directive or a property of a DOM element).<br> There are special forms: </p> <ul> <li><code>[class.className]</code> binds to a css class to enable/disable it</li> <li><code>[style.stylePropertyName]</code> binds to a style property</li> <li><code>[style.stylePropertyName.px]</code> binds to a style property with a preset unit</li> <li><code>[attr.attrName]</code> binds a value to an attribute (visible in the DOM, while properties are not visible)</li> <li><code>[role.roleName]</code> binds to the ARIA role attribute (not yet available)</li> </ul></li> <li><p><code>prop="{{value}}"</code> binds a value to a property. The value is stringified (aka interpolation)</p></li> <li><p><code>(event)="expr"</code> binds an event handler to an <code>@Output()</code> or DOM event</p></li> <li><p><code>#var</code> or <code>#var</code> has different functions depending on the context</p> <ul> <li><strike> In an <code>*ngFor="#x in y;#i=index"</code> scope variables for the iteration are created</strike><br> (In beta.17 this is changed to *ngFor="let x in y; let i=index"`)</li> <li>On a DOM element <code>&lt;div #mydiv&gt;</code> a reference to the element </li> <li>On an Angular component a reference to the component</li> <li>On an element that is an Angular component or has an Angular directive where <code>exportAs:"ngForm"</code> is defined, <code>#myVar="ngForm"</code> creates a reference to this component or directive.</li> </ul></li> </ul>
{ "question_id": 35944749, "question_date": "2016-03-11T16:03:07.123Z", "question_score": 211, "tags": "angular", "answer_id": 35944965, "answer_date": "2016-03-11T16:14:17.650Z", "answer_score": 222 }
Please answer the following Stack Overflow question: Title: How to create a GUID/UUID using iOS <p>I want to be able to create a GUID/UUID on the iPhone and iPad. </p> <p>The intention is to be able to create keys for distributed data that are all unique. Is there a way to do this with the iOS SDK?</p>
<pre><code>[[UIDevice currentDevice] uniqueIdentifier] </code></pre> <p>Returns the Unique ID of your iPhone.</p> <blockquote> <p>EDIT: <code>-[UIDevice uniqueIdentifier]</code> is now deprecated and apps are being rejected from the App Store for using it. The method below is now the preferred approach.</p> </blockquote> <p>If you need to create several UUID, just use this method (with ARC):</p> <pre><code>+ (NSString *)GetUUID { CFUUIDRef theUUID = CFUUIDCreate(NULL); CFStringRef string = CFUUIDCreateString(NULL, theUUID); CFRelease(theUUID); return (__bridge NSString *)string; } </code></pre> <p>EDIT: Jan, 29 2014: If you're targeting iOS 6 or later, you can now use the much simpler method:</p> <pre><code>NSString *UUID = [[NSUUID UUID] UUIDString]; </code></pre>
{ "question_id": 427180, "question_date": "2009-01-09T05:45:16.437Z", "question_score": 211, "tags": "ios|uuid|guid", "answer_id": 427521, "answer_date": "2009-01-09T09:35:28.280Z", "answer_score": 324 }
Please answer the following Stack Overflow question: Title: Does IE9 support console.log, and is it a real function? <p>In which circumstances is <code>window.console.log</code> defined in Internet Explorer 9?</p> <p>Even when <code>window.console.log</code> is defined, <code>window.console.log.apply</code> and <code>window.console.log.call</code> are undefined. Why is this?</p> <p>[Related question for IE8: <a href="https://stackoverflow.com/questions/690251/what-happened-to-console-log-in-ie8">What happened to console.log in IE8?</a>.]</p>
<p>In Internet Explorer 9 (and 8), the <code>console</code> object is only exposed when the developer tools are opened for a particular tab. If you hide the developer tools window for that tab, the <code>console</code> object remains exposed for each page you navigate to. If you open a new tab, you must also open the developer tools for that tab in order for the <code>console</code> object to be exposed.</p> <p>The <code>console</code> object is not part of any standard and is an extension to the Document Object Model. Like other DOM objects, it is considered a host object and is not required to inherit from <code>Object</code>, nor its methods from <code>Function</code>, like native ECMAScript functions and objects do. This is the reason <code>apply</code> and <code>call</code> are undefined on those methods. In IE 9, most DOM objects were improved to inherit from native ECMAScript types. As the developer tools are considered an extension to IE (albeit, a built-in extension), they clearly didn't receive the same improvements as the rest of the DOM. </p> <p>For what it's worth, you can still use some <code>Function.prototype</code> methods on <code>console</code> methods with a little <a href="http://msdn.microsoft.com/en-us/library/ff841995%28v=vs.94%29.aspx"><code>bind()</code></a> magic:</p> <pre><code>var log = Function.prototype.bind.call(console.log, console); log.apply(console, ["this", "is", "a", "test"]); //-&gt; "thisisatest" </code></pre>
{ "question_id": 5472938, "question_date": "2011-03-29T13:03:05.410Z", "question_score": 211, "tags": "javascript|logging|internet-explorer-9", "answer_id": 5473193, "answer_date": "2011-03-29T13:22:07.397Z", "answer_score": 301 }
Please answer the following Stack Overflow question: Title: NodeJS require a global module/package <p>I'm trying to install globally and then use <code>forever</code> and <code>forever-monitor</code> like this:</p> <p><code>npm install -g forever forever-monitor</code></p> <p>I see the usual output and also the operations that copy the files to the global path, but then if I try to <code>require("forever");</code> I get an error saying that the module wasn't found.</p> <p>I'm using latest version of both node and npm and I already know about the change that npm made in global vs local install, but I <strong>really don't want</strong> to install localy on every project and I'm working on a platform that doesn't support <code>link</code> so <code>npm link</code> after a global install isn't possible for me.</p> <p>My question is: why I can't require a globally installed package? Is that a feature or a bug? Or am I doing something wrong?</p> <p>PS: Just to make it crystal clear: I don't want to install locally.</p>
<p>In Node.js, require doesn't look in the folder where global modules are installed.</p> <p>You can fix this by setting the NODE_PATH environment variable. In Linux this will be:</p> <pre><code>export NODE_PATH=/usr/lib/node_modules </code></pre> <p><sup>Note: This depend on where your global modules are actually installed.</sup></p> <p>See: <a href="https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders" rel="noreferrer">Loading from the global folders</a>.</p>
{ "question_id": 15636367, "question_date": "2013-03-26T11:49:07.180Z", "question_score": 211, "tags": "node.js|package|npm", "answer_id": 15646750, "answer_date": "2013-03-26T20:28:19.417Z", "answer_score": 263 }
Please answer the following Stack Overflow question: Title: Connect to a heroku database with pgadmin <p>I would like to manage my Heroku database with <code>pgadmin</code> client. By now, I've been doing this with <code>psql</code>. When I use data from <code>heroku pg:credentials</code> to connect de DB using <code>pgadmin</code>, I obtain:</p> <blockquote> <p>An error has occurred:</p> <p>Error connecting to the server: FATAL: permission denied for database &quot;postgres&quot; DETAIL: User does not have CONNECT privilege.</p> </blockquote> <p>How to achieve the connection?</p>
<p>Open the "Properties" of the Heroku server in pgAdminIII and change the "Maintenance DB" value to be the name of the database you want to connect to.</p> <p><img src="https://i.stack.imgur.com/wzVp5.jpg" alt="pgAdmin III - New Server Registration"></p> <p>The default setup is suitable for DBAs et al who can connect to any database on the server, but apparently that isn't true in your case.</p>
{ "question_id": 11769860, "question_date": "2012-08-02T01:31:29.353Z", "question_score": 211, "tags": "database|postgresql|heroku|pgadmin", "answer_id": 11775090, "answer_date": "2012-08-02T09:56:11.083Z", "answer_score": 359 }
Please answer the following Stack Overflow question: Title: Class inheritance in Python 3.7 dataclasses <p>I'm currently trying my hands on the new dataclass constructions introduced in Python 3.7. I am currently stuck on trying to do some inheritance of a parent class. It looks like the order of the arguments are botched by my current approach such that the bool parameter in the child class is passed before the other parameters. This is causing a type error.</p> <pre><code>from dataclasses import dataclass @dataclass class Parent: name: str age: int ugly: bool = False def print_name(self): print(self.name) def print_age(self): print(self.age) def print_id(self): print(f'The Name is {self.name} and {self.name} is {self.age} year old') @dataclass class Child(Parent): school: str ugly: bool = True jack = Parent('jack snr', 32, ugly=True) jack_son = Child('jack jnr', 12, school = 'havard', ugly=True) jack.print_id() jack_son.print_id() </code></pre> <p>When I run this code I get this <code>TypeError</code>:</p> <pre><code>TypeError: non-default argument 'school' follows default argument </code></pre> <p>How do I fix this?</p>
<p>The way dataclasses combines attributes prevents you from being able to use attributes with defaults in a base class and then use attributes without a default (positional attributes) in a subclass.</p> <p>That's because the attributes are combined by starting from the bottom of the MRO, and building up an ordered list of the attributes in first-seen order; overrides are kept in their original location. So <code>Parent</code> starts out with <code>['name', 'age', 'ugly']</code>, where <code>ugly</code> has a default, and then <code>Child</code> adds <code>['school']</code> to the end of that list (with <code>ugly</code> already in the list). This means you end up with <code>['name', 'age', 'ugly', 'school']</code> and because <code>school</code> doesn't have a default, this results in an invalid argument listing for <code>__init__</code>.</p> <p>This is documented in <a href="https://www.python.org/dev/peps/pep-0557/" rel="nofollow noreferrer">PEP-557 <em>Dataclasses</em></a>, under <a href="https://www.python.org/dev/peps/pep-0557/#inheritance" rel="nofollow noreferrer"><em>inheritance</em></a>:</p> <blockquote> <p>When the Data Class is being created by the <code>@dataclass</code> decorator, it looks through all of the class's base classes in reverse MRO (that is, starting at <code>object</code>) and, for each Data Class that it finds, adds the fields from that base class to an ordered mapping of fields. After all of the base class fields are added, it adds its own fields to the ordered mapping. All of the generated methods will use this combined, calculated ordered mapping of fields. Because the fields are in insertion order, derived classes override base classes.</p> </blockquote> <p>and under <a href="https://www.python.org/dev/peps/pep-0557/#id7" rel="nofollow noreferrer"><em>Specification</em></a>:</p> <blockquote> <p><code>TypeError</code> will be raised if a field without a default value follows a field with a default value. This is true either when this occurs in a single class, or as a result of class inheritance.</p> </blockquote> <p>You do have a few options here to avoid this issue.</p> <p>The first option is to use separate base classes to force fields with defaults into a later position in the MRO order. At all cost, avoid setting fields directly on classes that are to be used as base classes, such as <code>Parent</code>.</p> <p>The following class hierarchy works:</p> <pre><code># base classes with fields; fields without defaults separate from fields with. @dataclass class _ParentBase: name: str age: int @dataclass class _ParentDefaultsBase: ugly: bool = False @dataclass class _ChildBase(_ParentBase): school: str @dataclass class _ChildDefaultsBase(_ParentDefaultsBase): ugly: bool = True # public classes, deriving from base-with, base-without field classes # subclasses of public classes should put the public base class up front. @dataclass class Parent(_ParentDefaultsBase, _ParentBase): def print_name(self): print(self.name) def print_age(self): print(self.age) def print_id(self): print(f&quot;The Name is {self.name} and {self.name} is {self.age} year old&quot;) @dataclass class Child(_ChildDefaultsBase, Parent, _ChildBase): pass </code></pre> <p>By pulling out fields into <em>separate</em> base classes with fields without defaults and fields with defaults, and a carefully selected inheritance order, you can produce an MRO that puts all fields without defaults before those with defaults. The reversed MRO (ignoring <code>object</code>) for <code>Child</code> is:</p> <pre><code>_ParentBase _ChildBase _ParentDefaultsBase Parent _ChildDefaultsBase </code></pre> <p>Note that while <code>Parent</code> doesn't set any new fields, it does inherit the fields from <code>_ParentDefaultsBase</code> and should <em>not</em> end up 'last' in the field listing order; the above order puts <code>_ChildDefaultsBase</code> last so its fields 'win'. The dataclass rules are also satisfied; the classes with fields without defaults (<code>_ParentBase</code> and <code>_ChildBase</code>) precede the classes with fields with defaults (<code>_ParentDefaultsBase</code> and <code>_ChildDefaultsBase</code>).</p> <p>The result is <code>Parent</code> and <code>Child</code> classes with a sane field older, while <code>Child</code> is still a subclass of <code>Parent</code>:</p> <pre><code>&gt;&gt;&gt; from inspect import signature &gt;&gt;&gt; signature(Parent) &lt;Signature (name: str, age: int, ugly: bool = False) -&gt; None&gt; &gt;&gt;&gt; signature(Child) &lt;Signature (name: str, age: int, school: str, ugly: bool = True) -&gt; None&gt; &gt;&gt;&gt; issubclass(Child, Parent) True </code></pre> <p>and so you can create instances of both classes:</p> <pre><code>&gt;&gt;&gt; jack = Parent('jack snr', 32, ugly=True) &gt;&gt;&gt; jack_son = Child('jack jnr', 12, school='havard', ugly=True) &gt;&gt;&gt; jack Parent(name='jack snr', age=32, ugly=True) &gt;&gt;&gt; jack_son Child(name='jack jnr', age=12, school='havard', ugly=True) </code></pre> <p>Another option is to only use fields with defaults; you can still make in an error to not supply a <code>school</code> value, by raising one in <code>__post_init__</code>:</p> <pre><code>_no_default = object() @dataclass class Child(Parent): school: str = _no_default ugly: bool = True def __post_init__(self): if self.school is _no_default: raise TypeError(&quot;__init__ missing 1 required argument: 'school'&quot;) </code></pre> <p>but this <em>does</em> alter the field order; <code>school</code> ends up after <code>ugly</code>:</p> <pre><code>&lt;Signature (name: str, age: int, ugly: bool = True, school: str = &lt;object object at 0x1101d1210&gt;) -&gt; None&gt; </code></pre> <p>and a type hint checker <em>will</em> complain about <code>_no_default</code> not being a string.</p> <p>You can also use the <a href="http://www.attrs.org/en/stable/" rel="nofollow noreferrer"><code>attrs</code> project</a>, which was the project that inspired <code>dataclasses</code>. It uses a different inheritance merging strategy; it pulls overridden fields in a subclass to the end of the fields list, so <code>['name', 'age', 'ugly']</code> in the <code>Parent</code> class becomes <code>['name', 'age', 'school', 'ugly']</code> in the <code>Child</code> class; by overriding the field with a default, <code>attrs</code> allows the override without needing to do a MRO dance.</p> <p><code>attrs</code> supports defining fields without type hints, but lets stick to the <a href="http://www.attrs.org/en/stable/types.html" rel="nofollow noreferrer">supported type hinting mode</a> by setting <code>auto_attribs=True</code>:</p> <pre><code>import attr @attr.s(auto_attribs=True) class Parent: name: str age: int ugly: bool = False def print_name(self): print(self.name) def print_age(self): print(self.age) def print_id(self): print(f&quot;The Name is {self.name} and {self.name} is {self.age} year old&quot;) @attr.s(auto_attribs=True) class Child(Parent): school: str ugly: bool = True </code></pre>
{ "question_id": 51575931, "question_date": "2018-07-28T23:08:40.613Z", "question_score": 211, "tags": "python|python-3.x|python-3.7|python-dataclasses", "answer_id": 53085935, "answer_date": "2018-10-31T14:38:11.540Z", "answer_score": 278 }
Please answer the following Stack Overflow question: Title: ERROR ITMS-9000: "Redundant Binary Upload. There already exists a binary upload with build version '1.0' for train '1.0'" <p>I am trying to upload my build on iTunes Connect via Xcode 5.1.1 but it is continuously showing that it is loading and app is not getting uploaded. So I have tried uploading with Application Loader but its showing the below error:</p> <blockquote> <p>ERROR ITMS-9000: &quot;Redundant Binary Upload. There already exists a binary upload with build version '1.0' for train '1.0'&quot;</p> </blockquote> <p>App status on iTunes is Waiting for Upload. One time the upload was successfully done, but the status is not reflecting and it's now allowing to upload again.</p> <p>Also I just checked that website is also changed. Don't know what's wrong.</p> <hr /> <p>Edit: There was no submit for review button on apples new website. But now I can see that button. That has solved my issue. Also I recommend to upload the build using Application Loader as it's quicker than organizer.</p>
<p>More than one binary may be uploaded to <strong>App Store Connect</strong> for the same version, if the the Build number is increasing for each build uploaded to iTunesConnect. The build number just has to be <strong>unique</strong> (and higher) for each <strong>binary that is uploaded</strong> (select the Target, then Xcode -> General -> Build, see the picture below). For example in the image below the build uploaded has <strong>version 3.1.4</strong> (3.75 in the older image) and the <strong>build number is 1</strong>. Thus, after uploading this image <strong>increase the build to a minimum 2 or higher</strong>. Then this binary may also be uploaded to App Store Connect as it's a later build according to the <code>build number</code>.</p> <p>The <code>version</code> notes the <strong>release version of the app</strong> your releasing to the user. The <code>build number</code> remarks the final <strong>build</strong> of the binary uploaded to the store, i.e. after many bug fixes.</p> <p>After <strong>Xcode 9</strong> you are not able to upload a new build (for the same version), if there is a previous build with the same build number in the store. So, check your build number and increase if not certain.</p> <p>EDIT: It's more correct to use <code>1</code>, <code>2</code>, <code>3</code>, <code>4</code>, etc. for the build number, but the version number has to be increasing, 1.0 -> 1.1 -> 1.2 etc. The build number has to be higher than what was submitted previously for the same version number, if not an error is posted. So, if a new binary is submitted that has version 3.75 and a build 1 has already been submitted, then next build shall be 2 or higher, but the version can still remain 3.75.</p> <p><strong>New updated and the recommended</strong> way of having the <strong>build numbers serial</strong>: <a href="https://i.stack.imgur.com/Gb2Cr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Gb2Cr.png" alt="enter image description here"></a></p> <p>The older image to match the one below: <img src="https://i.stack.imgur.com/NAlCV.jpg" alt="Showing where to set the Build Version in XCode"></p> <p>After a new binary is uploaded and processed (~5-20 min processing time, if it doesn´t show up upload again and wait), then you can select the new binary and submit it for review. In the picture below you may see the old and the new binary listed in App Store Connect in the Build section of the current App version (you click the plus sign). Then the new binary is selected -> <code>Saved</code> -> <code>Submit for Review</code>. (Sometimes an error comes when submitting, then just try after a few mins or upload a new binary).</p> <p><img src="https://i.stack.imgur.com/5eqc6.jpg" alt="Showing list of binaries in iTunesConnect"></p> <p>For those inclined to do this automatically with an Xcode script, here is a description of making an automatic script for updating Build numbers <a href="https://stackoverflow.com/questions/9258344/better-way-of-incrementing-build-number">Better way of incrementing build number?</a></p>
{ "question_id": 25680604, "question_date": "2014-09-05T07:24:37.770Z", "question_score": 211, "tags": "ios|xcode5|itunes|app-store-connect", "answer_id": 25699582, "answer_date": "2014-09-06T11:05:30.043Z", "answer_score": 376 }
Please answer the following Stack Overflow question: Title: Swift compiler error: "non-modular header inside framework module" <p>Now I would like to migrate my ObjC framework to Swift and I got the following error:</p> <pre><code>include of non-modular header inside framework module 'SOGraphDB' </code></pre> <p>The references is to a header file which just define a protocol and I use this header file in some classes to use this protocol.</p> <p>Is seems related to the module feature but it is at the moment not quite clear how to fix, do you know a solution?</p> <p>UPDATE:</p> <p>This is a Swift compiler error.</p> <p>UPDATE 2:</p> <p>A quick fix (but not solving the root cause) is to set the following setting to yes: CLANG_ALLOW_NON_MODULAR_INCLUDES_IN_FRAMEWORK_MODULES = YES</p>
<p>Is your header public?</p> <p>Select the header file in the project explorer. Then in the section on the right in xcode, you'll notice there is a dropdown next to the target. Change that from "project" to "public". This worked for me.</p> <p><img src="https://i.stack.imgur.com/OXRXL.png" alt="public header"></p>
{ "question_id": 24103169, "question_date": "2014-06-08T05:04:23.910Z", "question_score": 211, "tags": "objective-c|frameworks|swift", "answer_id": 24317456, "answer_date": "2014-06-19T22:50:44.037Z", "answer_score": 325 }
Please answer the following Stack Overflow question: Title: Why does PostgreSQL perform sequential scan on indexed column? <p>Very simple example - one table, one index, one query:</p> <pre><code>CREATE TABLE book ( id bigserial NOT NULL, "year" integer, -- other columns... ); CREATE INDEX book_year_idx ON book (year) EXPLAIN SELECT * FROM book b WHERE b.year &gt; 2009 </code></pre> <p>gives me:</p> <pre><code>Seq Scan on book b (cost=0.00..25663.80 rows=105425 width=622) Filter: (year &gt; 2009) </code></pre> <p>Why it does NOT perform index scan instead? What am I missing?</p>
<p>If the SELECT returns more than approximately 5-10% of all rows in the table, a sequential scan is much faster than an index scan. </p> <p>This is because an index scan requires <em>several</em> IO operations for each row (look up the row in the index, then retrieve the row from the heap). Whereas a sequential scan only requires a single IO for each row - or even less because a block (page) on the disk contains more than one row, so more than one row can be fetched with a single IO operation.</p> <p>Btw: this is true for other DBMS as well - some optimizations as "index only scans" taken aside (but for a SELECT * it's highly unlikely such a DBMS would go for an "index only scan")</p>
{ "question_id": 5203755, "question_date": "2011-03-05T12:17:20.113Z", "question_score": 211, "tags": "postgresql|indexing|sequence|database-scan", "answer_id": 5203827, "answer_date": "2011-03-05T12:33:13.530Z", "answer_score": 334 }
Please answer the following Stack Overflow question: Title: Access Container View Controller from Parent iOS <p>in iOS6 I noticed the new Container View but am not quite sure how to access it's controller from the containing view.</p> <p>Scenario:</p> <p><img src="https://i.stack.imgur.com/aNOLJ.png" alt="example"></p> <p>I want to access the labels in Alert view controller from the view controller that houses the container view.</p> <p>There's a segue between them, can I use that?</p>
<p>Yes, you can use the segue to get access the child view controller (and its view and subviews). Give the segue an identifier (such as <code>alertview_embed</code>), using the Attributes inspector in Storyboard. Then have the parent view controller (the one housing the container view) implement a method like this:</p> <pre><code>- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { NSString * segueName = segue.identifier; if ([segueName isEqualToString: @"alertview_embed"]) { AlertViewController * childViewController = (AlertViewController *) [segue destinationViewController]; AlertView * alertView = childViewController.view; // do something with the AlertView's subviews here... } } </code></pre>
{ "question_id": 13279105, "question_date": "2012-11-07T22:07:28.517Z", "question_score": 211, "tags": "ios|objective-c|swift|uiviewcontroller|uicontainerview", "answer_id": 13279703, "answer_date": "2012-11-07T22:56:10.813Z", "answer_score": 368 }
Please answer the following Stack Overflow question: Title: What's the difference(s) between .ToList(), .AsEnumerable(), AsQueryable()? <p>I know some differences of LINQ to Entities and LINQ to Objects which the first implements <code>IQueryable</code> and the second implements <code>IEnumerable</code> and my question scope is within EF 5. </p> <p>My question is what's the technical difference(s) of those 3 methods? I see that in many situations all of them work. I also see using combinations of them like <code>.ToList().AsQueryable()</code>. </p> <ol> <li><p>What do those methods mean, exactly?</p></li> <li><p>Is there any performance issue or something that would lead to the use of one over the other?</p></li> <li><p>Why would one use, for example, <code>.ToList().AsQueryable()</code> instead of <code>.AsQueryable()</code>?</p></li> </ol>
<p>There is a lot to say about this. Let me focus on <code>AsEnumerable</code> and <code>AsQueryable</code> and mention <code>ToList()</code> along the way.</p> <h2>What do these methods do?</h2> <p><code>AsEnumerable</code> and <code>AsQueryable</code> cast or convert to <code>IEnumerable</code> or <code>IQueryable</code>, respectively. I say <em>cast or convert</em> with a reason:</p> <ul> <li><p>When the source object already implements the target interface, the source object itself is returned but <em>cast</em> to the target interface. In other words: the type is not changed, but the compile-time type is.</p> </li> <li><p>When the source object does not implement the target interface, the source object is <em>converted</em> into an object that implements the target interface. So both the type and the compile-time type are changed.</p> </li> </ul> <p>Let me show this with some examples. I've got this little method that reports the compile-time type and the actual type of an object (<a href="https://stackoverflow.com/a/9063184/861716">courtesy Jon Skeet</a>):</p> <pre class="lang-cs prettyprint-override"><code>void ReportTypeProperties&lt;T&gt;(T obj) { Console.WriteLine(&quot;Compile-time type: {0}&quot;, typeof(T).Name); Console.WriteLine(&quot;Actual type: {0}&quot;, obj.GetType().Name); } </code></pre> <p>Let's try an arbitrary linq-to-sql <code>Table&lt;T&gt;</code>, which implements <code>IQueryable</code>:</p> <pre class="lang-cs prettyprint-override"><code>ReportTypeProperties(context.Observations); ReportTypeProperties(context.Observations.AsEnumerable()); ReportTypeProperties(context.Observations.AsQueryable()); </code></pre> <p>The result:</p> <pre class="lang-none prettyprint-override"><code>Compile-time type: Table`1 Actual type: Table`1 Compile-time type: IEnumerable`1 Actual type: Table`1 Compile-time type: IQueryable`1 Actual type: Table`1 </code></pre> <p>You see that the table class itself is always returned, but its representation changes.</p> <p>Now an object that implements <code>IEnumerable</code>, not <code>IQueryable</code>:</p> <pre class="lang-cs prettyprint-override"><code>var ints = new[] { 1, 2 }; ReportTypeProperties(ints); ReportTypeProperties(ints.AsEnumerable()); ReportTypeProperties(ints.AsQueryable()); </code></pre> <p>The results:</p> <pre class="lang-none prettyprint-override"><code>Compile-time type: Int32[] Actual type: Int32[] Compile-time type: IEnumerable`1 Actual type: Int32[] Compile-time type: IQueryable`1 Actual type: EnumerableQuery`1 </code></pre> <p>There it is. <code>AsQueryable()</code> has converted the array into an <a href="http://msdn.microsoft.com/en-us/library/cc190116.aspx" rel="noreferrer"><code>EnumerableQuery</code></a>, which &quot;represents an <code>IEnumerable&lt;T&gt;</code> collection as an <code>IQueryable&lt;T&gt;</code> data source.&quot; (MSDN).</p> <h2>What's the use?</h2> <p><strong><code>AsEnumerable</code></strong> is frequently used to switch from any <code>IQueryable</code> implementation to LINQ to objects (L2O), mostly because the former does not support functions that L2O has. For more details see <a href="https://stackoverflow.com/q/5311034/861716">What is the effect of AsEnumerable() on a LINQ Entity?</a>.</p> <p>For example, in an Entity Framework query we can only use a restricted number of methods. So if, for example, we need to use one of our own methods in a query we would typically write something like</p> <pre><code>var query = context.Observations.Select(o =&gt; o.Id) .AsEnumerable().Select(x =&gt; MySuperSmartMethod(x)) </code></pre> <p><strong><code>ToList</code></strong> – which converts an <code>IEnumerable&lt;T&gt;</code> to a <code>List&lt;T&gt;</code> – is often used for this purpose as well. The advantage of using <code>AsEnumerable</code> vs. <code>ToList</code> is that <code>AsEnumerable</code> does not execute the query. <code>AsEnumerable</code> preserves deferred execution and does not build an often useless intermediate list.</p> <p>On the other hand, when forced execution of a LINQ query is desired, <code>ToList</code> can be a way to do that.</p> <p><strong><code>AsQueryable</code></strong> can be used to make an enumerable collection accept expressions in LINQ statements. See here for more details: <a href="https://stackoverflow.com/q/10510890/861716">Do i really need use AsQueryable() on collection?</a>.</p> <h3>Note on substance abuse!</h3> <p><code>AsEnumerable</code> works like a drug. It's a quick fix, but at a cost and it doesn't address the underlying problem.</p> <p>In many Stack Overflow answers, I see people applying <code>AsEnumerable</code> to fix just about any problem with unsupported methods in LINQ expressions. But the price isn't always clear. For instance, if you do this:</p> <pre><code>context.MyLongWideTable // A table with many records and columns .Where(x =&gt; x.Type == &quot;type&quot;) .Select(x =&gt; new { x.Name, x.CreateDate }) </code></pre> <p>...everything is neatly translated into a SQL statement that <em>filters</em> (<code>Where</code>) and <em>projects</em> (<code>Select</code>). That is, both the length and the width, respectively, of the SQL result set are reduced.</p> <p>Now suppose users only want to see the date part of <code>CreateDate</code>. In Entity Framework you'll quickly discover that...</p> <pre><code>.Select(x =&gt; new { x.Name, x.CreateDate.Date }) </code></pre> <p>...is not supported (at the time of writing). Ah, fortunately there's the <code>AsEnumerable</code> fix:</p> <pre><code>context.MyLongWideTable.AsEnumerable() .Where(x =&gt; x.Type == &quot;type&quot;) .Select(x =&gt; new { x.Name, x.CreateDate.Date }) </code></pre> <p>Sure, it runs, probably. But it pulls the entire table into memory and then applies the filter and the projections. Well, most people are smart enough to do the <code>Where</code> first:</p> <pre><code>context.MyLongWideTable .Where(x =&gt; x.Type == &quot;type&quot;).AsEnumerable() .Select(x =&gt; new { x.Name, x.CreateDate.Date }) </code></pre> <p>But still all columns are fetched first and the projection is done in memory.</p> <p>The real fix is:</p> <pre><code>context.MyLongWideTable .Where(x =&gt; x.Type == &quot;type&quot;) .Select(x =&gt; new { x.Name, DbFunctions.TruncateTime(x.CreateDate) }) </code></pre> <p>(But that requires just a little bit more knowledge...)</p> <h2>What do these methods NOT do?</h2> <h3>Restore IQueryable capabilities</h3> <p>Now an important caveat. When you do</p> <pre><code>context.Observations.AsEnumerable() .AsQueryable() </code></pre> <p>you will end up with the source object represented as <code>IQueryable</code>. (Because both methods only cast and don't convert).</p> <p>But when you do</p> <pre><code>context.Observations.AsEnumerable().Select(x =&gt; x) .AsQueryable() </code></pre> <p>what will the result be?</p> <p>The <code>Select</code> produces a <code>WhereSelectEnumerableIterator</code>. This is an internal .Net class that implements <code>IEnumerable</code>, <em>not <code>IQueryable</code></em>. So a conversion to another type has taken place and the subsequent <code>AsQueryable</code> can never return the original source anymore.</p> <p>The implication of this is that using <code>AsQueryable</code> is <strong>not a way to magically inject a query provider</strong> with its specific features into an enumerable. Suppose you do</p> <pre><code>var query = context.Observations.Select(o =&gt; o.Id) .AsEnumerable().Select(x =&gt; x.ToString()) .AsQueryable() .Where(...) </code></pre> <p>The where condition will never be translated into SQL. <code>AsEnumerable()</code> followed by LINQ statements definitively cuts the connection with entity framework query provider.</p> <p>I deliberately show this example because I've seen questions here where people for instance try to 'inject' <code>Include</code> capabilities into a collection by calling <code>AsQueryable</code>. It compiles and runs, but it does nothing because the underlying object does not have an <code>Include</code> implementation anymore.</p> <h3>Execute</h3> <p>Both <code>AsQueryable</code> and <code>AsEnumerable</code> don't execute (or <em>enumerate</em>) the source object. They only change their type or representation. Both involved interfaces, <code>IQueryable</code> and <code>IEnumerable</code>, are nothing but &quot;an enumeration waiting to happen&quot;. They are not executed before they're forced to do so, for example, as mentioned above, by calling <code>ToList()</code>.</p> <p>That means that executing an <code>IEnumerable</code> obtained by calling <code>AsEnumerable</code> on an <code>IQueryable</code> object, will execute the underlying <code>IQueryable</code>. A subsequent execution of the <code>IEnumerable</code> will again execute the <code>IQueryable</code>. Which may be very expensive.</p> <h2>Specific Implementations</h2> <p>So far, this was only about the <a href="http://msdn.microsoft.com/en-us/library/bb507003.aspx" rel="noreferrer"><code>Queryable.AsQueryable</code></a> and <a href="http://msdn.microsoft.com/en-us/library/bb335435.aspx" rel="noreferrer"><code>Enumerable.AsEnumerable</code></a> extension methods. But of course anybody can write instance methods or extension methods with the same names (and functions).</p> <p>In fact, a common example of a specific <code>AsEnumerable</code> extension method is <a href="http://msdn.microsoft.com/en-us/library/system.data.datatableextensions.asenumerable.aspx" rel="noreferrer"><code>DataTableExtensions.AsEnumerable</code></a>. <code>DataTable</code> does not implement <code>IQueryable</code> or <code>IEnumerable</code>, so the regular extension methods don't apply.</p>
{ "question_id": 17968469, "question_date": "2013-07-31T10:56:52.643Z", "question_score": 211, "tags": "entity-framework|entity-framework-4|linq-to-entities|entity-framework-5", "answer_id": 17996264, "answer_date": "2013-08-01T14:03:19.783Z", "answer_score": 424 }
Please answer the following Stack Overflow question: Title: Why does typeof NaN return 'number'? <p>Just out of curiosity.</p> <p>It doesn't seem very logical that <code>typeof NaN</code> is number. Just like <code>NaN === NaN</code> or <code>NaN == NaN</code> returning false, by the way. Is this one of the peculiarities of JavaScript, or would there be a reason for this?</p> <p>Edit: thanks for your answers. It's not an easy thing to get ones head around though. Reading answers and the wiki I understood more, but still, a sentence like</p> <blockquote> <p>A comparison with a <code>NaN</code> always returns an unordered result even when comparing with itself. The comparison predicates are either signaling or non-signaling, the signaling versions signal an invalid exception for such comparisons. The equality and inequality predicates are non-signaling so <code>x = x</code> returning false can be used to test if x is a quiet <code>NaN</code>.</p> </blockquote> <p>just keeps my head spinning. If someone can translate this in human (as opposed to, say, mathematician) readable language, I would be grateful.</p>
<p>It means Not a Number. It is not a peculiarity of javascript but common computer science principle.</p> <p>From <a href="http://en.wikipedia.org/wiki/NaN" rel="noreferrer">http://en.wikipedia.org/wiki/NaN</a>:</p> <blockquote> <p>There are three kinds of operation which return NaN:</p> <p>Operations with a NaN as at least one operand </p> <p>Indeterminate forms </p> <ul> <li>The divisions 0/0, ∞/∞, ∞/−∞, −∞/∞, and −∞/−∞ </li> <li>The multiplications 0×∞ and 0×−∞ </li> <li>The power 1^∞ </li> <li>The additions ∞ + (−∞), (−∞) + ∞ and equivalent subtractions. </li> </ul> <p>Real operations with complex results: </p> <ul> <li>The square root of a negative number </li> <li>The logarithm of a negative number </li> <li>The tangent of an odd multiple of 90 degrees (or π/2 radians) </li> <li>The inverse sine or cosine of a number which is less than −1 or greater than +1.</li> </ul> </blockquote> <p>All these values may not be the same. A simple test for a NaN is to test <code>value == value</code> is false.</p>
{ "question_id": 2801601, "question_date": "2010-05-10T09:30:31.763Z", "question_score": 211, "tags": "javascript|nan", "answer_id": 2801629, "answer_date": "2010-05-10T09:35:43.503Z", "answer_score": 67 }
Please answer the following Stack Overflow question: Title: Django self-referential foreign key <p>I'm kind of new to webapps and database stuff in general so this might be a dumb question. I want to make a model ("CategoryModel") with a field that points to the primary id of another instance of the model (its parent).</p> <pre><code>class CategoryModel(models.Model): parent = models.ForeignKey(CategoryModel) </code></pre> <p>How do I do this? Thanks! </p>
<p>You can pass in the name of a model as a string to ForeignKey and it will do the right thing.</p> <p>So:</p> <pre><code>parent = models.ForeignKey("CategoryModel") </code></pre> <p>Or you can use the string "self"</p> <pre><code>parent = models.ForeignKey("self") </code></pre>
{ "question_id": 15285626, "question_date": "2013-03-08T02:22:10.363Z", "question_score": 211, "tags": "python|django|django-orm", "answer_id": 15285656, "answer_date": "2013-03-08T02:25:18.277Z", "answer_score": 345 }
Please answer the following Stack Overflow question: Title: What's the difference between dynamic (C# 4) and var? <p>I had read a ton of articles about that new keyword that is shipping with C# v4, but I couldn't make out the difference between a "dynamic" and "var".</p> <p><a href="http://www.hanselman.com/blog/C4AndTheDynamicKeywordWhirlwindTourAroundNET4AndVisualStudio2010Beta1.aspx" rel="noreferrer">This article</a> made me think about it, but I still can't see any difference.</p> <p>Is it that you can use "var" only as a local variable, but dynamic as both local and global?</p> <p>Could you show some code without dynamic keyword and then show the same code with dynamic keyword?</p>
<p><code>var</code> is static typed - the compiler and runtime <strong>know</strong> the type - they just save you some typing... the following are 100% identical:</p> <pre><code>var s = "abc"; Console.WriteLine(s.Length); </code></pre> <p>and</p> <pre><code>string s = "abc"; Console.WriteLine(s.Length); </code></pre> <p>All that happened was that the <strong>compiler</strong> figured out that <code>s</code> must be a string (from the initializer). In both cases, it knows (in the IL) that <code>s.Length</code> means the (instance) <code>string.Length</code> property.</p> <p><code>dynamic</code> is a <strong>very</strong> different beast; it is most similar to <code>object</code>, but with dynamic dispatch:</p> <pre><code>dynamic s = "abc"; Console.WriteLine(s.Length); </code></pre> <p>Here, <code>s</code> is typed <strong>as dynamic</strong>. It doesn't know about <code>string.Length</code>, because it doesn't know <strong>anything</strong> about <code>s</code> at compile time. For example, the following would compile (but not run) too:</p> <pre><code>dynamic s = "abc"; Console.WriteLine(s.FlibbleBananaSnowball); </code></pre> <p>At runtime (only), it would <em>check</em> for the <code>FlibbleBananaSnowball</code> property - fail to find it, and explode in a shower of sparks.</p> <p>With <code>dynamic</code>, properties / methods / operators / etc are resolved <strong>at runtime</strong>, based on the actual object. Very handy for talking to COM (which can have runtime-only properties), the DLR, or other dynamic systems, like <code>javascript</code>.</p>
{ "question_id": 961581, "question_date": "2009-06-07T09:45:10.540Z", "question_score": 211, "tags": "c#|dynamic", "answer_id": 961594, "answer_date": "2009-06-07T09:51:34.207Z", "answer_score": 470 }
Please answer the following Stack Overflow question: Title: Alternative for __dirname in Node.js when using ES6 modules <p>I use the flag <code>--experimental-modules</code> when running my Node application in order to use ES6 modules.</p> <p>However when I use this flag the metavariable <code>__dirname</code> is not available. Is there an alternative way to get the same string that is stored in <code>__dirname</code> that is compatible with this mode?</p>
<p>As of Node.js 10.12 there's an alternative that doesn't require creating multiple files and handles special characters in filenames across platforms:</p> <pre><code>import { dirname } from 'path'; import { fileURLToPath } from 'url'; const __dirname = dirname(fileURLToPath(import.meta.url)); </code></pre>
{ "question_id": 46745014, "question_date": "2017-10-14T13:17:55.037Z", "question_score": 211, "tags": "node.js|ecmascript-6|es6-modules", "answer_id": 50052194, "answer_date": "2018-04-26T21:37:10.517Z", "answer_score": 344 }
Please answer the following Stack Overflow question: Title: Limit a stream by a predicate <p>Is there a Java 8 stream operation that limits a (potentially infinite) <code>Stream</code> until the first element fails to match a predicate?</p> <p>In Java 9 we can use <code>takeWhile</code> as in the example below to print all the numbers less than 10.</p> <pre><code>IntStream .iterate(1, n -&gt; n + 1) .takeWhile(n -&gt; n &lt; 10) .forEach(System.out::println); </code></pre> <p>As there is no such operation in Java 8, what's the best way of implementing it in a general way? </p>
<p>Operations <code>takeWhile</code> and <code>dropWhile</code> have been added to JDK 9. Your example code</p> <pre><code>IntStream .iterate(1, n -&gt; n + 1) .takeWhile(n -&gt; n &lt; 10) .forEach(System.out::println); </code></pre> <p>will behave exactly as you expect it to when compiled and run under JDK 9.</p> <p>JDK 9 has been released. It is available for download here: <a href="http://jdk.java.net/9/" rel="noreferrer">JDK 9 Releases</a>.</p>
{ "question_id": 20746429, "question_date": "2013-12-23T15:24:59.750Z", "question_score": 211, "tags": "java|java-8|java-stream", "answer_id": 32304570, "answer_date": "2015-08-31T05:36:53.713Z", "answer_score": 163 }
Please answer the following Stack Overflow question: Title: Rename a git submodule <p>Is there some easy way to rename a git submodule directory (other than going through the entire motion of <a href="https://stackoverflow.com/questions/1260748/how-do-i-remove-a-git-submodule">deleting</a> it and re-adding it with a new destination name). </p> <p>And while we are at it, why is it that I simply cannot do the following in the parent directory: <code>git mv old-submodule-name new-submodule-name</code></p>
<p>I found following workflow working:</p> <ul> <li>Update .gitmodules</li> <li><code>mv oldpath newpath</code></li> <li><code>git rm oldpath</code></li> <li><code>git add newpath</code></li> <li><code>git submodule sync</code></li> </ul> <p>Note: this approach does not update the index and <code>.gitmodules</code> properly in 2018 versions of GIT.</p> <p>Note: You may be able to just do <code>git mv oldpath newpath</code> now, as pointed out in <a href="https://stackoverflow.com/users/6309/vonc">VonC</a>'s <a href="https://stackoverflow.com/a/18712756/6309">answer</a>. (Ensure you are using the latest version of git)</p>
{ "question_id": 4526910, "question_date": "2010-12-24T14:52:18.327Z", "question_score": 211, "tags": "git|git-submodules", "answer_id": 5540263, "answer_date": "2011-04-04T14:52:44.573Z", "answer_score": 115 }
Please answer the following Stack Overflow question: Title: Hg: How to do a rebase like git's rebase <p>In Git I can do this:</p> <pre> 1. Start working on new feature: $ git co -b newfeature-123 # (a local feature development branch) do a few commits (M, N, O) master A---B---C \ newfeature-123 M---N---O 2. Pull new changes from upstream master: $ git pull (master updated with ff-commits) master A---B---C---D---E---F \ newfeature-123 M---N---O 3. Rebase off master so that my new feature can be developed against the latest upstream changes: (from newfeature-123) $ git rebase master master A---B---C---D---E---F \ newfeature-123 M---N---O </pre> <p><br /></p> <p>I want to know how to do the same thing in Mercurial, and I've scoured the web for an answer, but the best I could find was: <a href="https://www.mercurial-scm.org/pipermail/mercurial/2007-June/013393.html" rel="noreferrer">git rebase - can hg do that</a></p> <p>That link provides 2 examples:<br /> 1. I'll admit that this: (replacing the revisions from the example with those from my own example)</p> <pre> hg up -C F hg branch -f newfeature-123 hg transplant -a -b newfeature-123 </pre> <p>is not too bad, except that it leaves behind the pre-rebase M-N-O as an unmerged head and creates 3 new commits M',N',O' that represent them branching off the updated mainline.</p> <p>Basically the problem is that I end up with this:</p> <pre> master A---B---C---D---E---F \ \ newfeature-123 \ M'---N'---O' \ newfeature-123 M---N---O </pre> <p>this is not good because it leaves behind local, unwanted commits that should be dropped.</p> <ol start="2"> <li>The other option from the same link is </li> </ol> <pre> hg qimport -r M:O hg qpop -a hg up F hg branch newfeature-123 hg qpush -a hg qdel -r qbase:qtip </pre> <p>and this does result in the desired graph:</p> <pre> master A---B---C---D---E---F \ newfeature-123 M---N---O </pre> <p>but these commands (all 6 of them!) seem so much more complicated than </p> <pre> $ git rebase master </pre> <p>I want to know if this is the only equivalent in Hg or if there is some other way available that is simple like Git.</p>
<p>VonC has <a href="https://stackoverflow.com/questions/2672351/hg-how-to-do-a-rebase-like-gits-rebase/2672429#2672429">the answer you're looking for</a>, the Rebase Extension. It is, however, worth spending a second or two thinking about why neither mq nor rebase are enabled by default in mercurial: because mercurial is all about indelible changesets. When I work in the manner you're describing, which is nearly daily, here's the pattern I take:</p> <pre><code>1. Start working on a new feature: $ hg clone mainline-repo newfeature-123 do a few commits (M, N, O) master A---B---C \ newfeature-123 M---N---O 2. Pull new changes from upstream mainline: $ hg pull master A---B---C---D---E---F \ newfeature-123 M---N---O 3. merge master into my clone so that my new feature can be developed against the latest upstream changes: (from newfeature-123) $ hg merge F master A---B---C---D---E---F \ \ newfeature-123 M---N---O---P </code></pre> <p>and that's really all that's necessary. I end up with a newfeature-123 clone I can easily push back to the mainline when I'm happy with it. Most importantly, however, I <em>never changed history</em>. Someone can look at my csets and see what they were originally coded against and how I reacted to changes in the mainline throughout my work. Not everyone thinks that has value, but I'm a firm believer that it's the job of source control to show us not what we wished had happened, but what actually happened -- every deadend and every refactor should leave an indelible trace, and rebasing and other history editing techniques hide that.</p> <p>Now go pick VonC's answer while I put my soapbox away. :)</p>
{ "question_id": 2672351, "question_date": "2010-04-20T03:34:23.237Z", "question_score": 211, "tags": "git|mercurial|dvcs|rebase", "answer_id": 2672489, "answer_date": "2010-04-20T04:14:15.697Z", "answer_score": 238 }
Please answer the following Stack Overflow question: Title: How does LMAX's disruptor pattern work? <p>I am trying to understand the <a href="http://code.google.com/p/disruptor/">disruptor pattern</a>. I have watched the InfoQ video and tried to read their paper. I understand there is a ring buffer involved, that it is initialized as an extremely large array to take advantage of cache locality, eliminate allocation of new memory. </p> <p>It sounds like there are one or more atomic integers which keep track of positions. Each 'event' seems to get a unique id and it's position in the ring is found by finding its modulus with respect to the size of the ring, etc., etc.</p> <p>Unfortunately, I don't have an intuitive sense of how it works. I have done many trading applications and studied the <a href="http://en.wikipedia.org/wiki/Actor_model">actor model</a>, looked at SEDA, etc.</p> <p>In their presentation they mentioned that this pattern is basically how routers work; however I haven't found any good descriptions of how routers work either.</p> <p>Are there some good pointers to a better explanation?</p>
<p>The Google Code project does <a href="http://disruptor.googlecode.com/files/Disruptor-1.0.pdf" rel="noreferrer">reference a technical paper</a> on the implementation of the ring buffer, however it is a bit dry, academic and tough going for someone wanting to learn how it works. However there are some blog posts that have started to explain the internals in a more readable way. There is an <a href="http://mechanitis.blogspot.com/2011/06/dissecting-disruptor-whats-so-special.html" rel="noreferrer">explanation of ring buffer</a> that is the core of the disruptor pattern, a <a href="http://mechanitis.blogspot.com/2011/06/dissecting-disruptor-how-do-i-read-from.html" rel="noreferrer">description of the consumer barriers</a> (the part related to reading from the disruptor) and some <a href="http://blog.codeaholics.org/2011/the-disruptor-lock-free-publishing/" rel="noreferrer">information on handling multiple producers</a> available.</p> <p>The simplest description of the Disruptor is: It is a way of sending messages between threads in the most efficient manner possible. It can be used as an alternative to a queue, but it also shares a number of features with SEDA and Actors.</p> <p><strong>Compared to Queues:</strong></p> <p>The Disruptor provides the ability to pass a message onto another threads, waking it up if required (similar to a BlockingQueue). However, there are 3 distinct differences.</p> <ol> <li>The user of the Disruptor defines how messages are stored by extending Entry class and providing a factory to do the preallocation. This allows for either memory reuse (copying) or the Entry could contain a reference to another object.</li> <li>Putting messages into the Disruptor is a 2-phase process, first a slot is claimed in the ring buffer, which provides the user with the Entry that can be filled with the appropriate data. Then the entry must be committed, this 2-phase approach is necessary to allow for the flexible use of memory mentioned above. It is the commit that makes the message visible to the consumer threads.</li> <li>It is the responsibility of the consumer to keep track of the messages that have been consumed from the ring buffer. Moving this responsibility away from the ring buffer itself helped reduce the amount of write contention as each thread maintains its own counter.</li> </ol> <p><strong>Compared to Actors</strong></p> <p>The Actor model is closer the Disruptor than most other programming models, especially if you use the BatchConsumer/BatchHandler classes that are provided. These classes hide all of the complexities of maintaining the consumed sequence numbers and provide a set of simple callbacks when important events occur. However, there are a couple of subtle differences.</p> <ol> <li>The Disruptor uses a 1 thread - 1 consumer model, where Actors use an N:M model i.e. you can have as many actors as you like and they will be distributed across a fixed numbers of threads (generally 1 per core).</li> <li>The BatchHandler interface provides an additional (and very important) callback <code>onEndOfBatch()</code>. This allows for slow consumers, e.g. those doing I/O to batch events together to improve throughput. It is possible to do batching in other Actor frameworks, however as nearly all other frameworks don't provide a callback at the end of the batch you need to use a timeout to determine the end of the batch, resulting in poor latency.</li> </ol> <p><strong>Compared to SEDA</strong></p> <p>LMAX built the Disruptor pattern to replace a SEDA based approach.</p> <ol> <li>The main improvement that it provided over SEDA was the ability to do work in parallel. To do this the Disruptor supports multi-casting the same messages (in the same order) to multiple consumers. This avoids the need for fork stages in the pipeline.</li> <li>We also allow consumers to wait on the results of other consumers without having to put another queuing stage between them. A consumer can simply watch the sequence number of a consumer that it is dependent on. This avoids the need for join stages in pipeline.</li> </ol> <p><strong>Compared to Memory Barriers</strong></p> <p>Another way to think about it is as a structured, ordered memory barrier. Where the producer barrier forms the write barrier and the consumer barrier is the read barrier.</p>
{ "question_id": 6559308, "question_date": "2011-07-02T20:00:57.890Z", "question_score": 211, "tags": "concurrency|latency|actor|disruptor-pattern", "answer_id": 6561784, "answer_date": "2011-07-03T08:03:40.823Z", "answer_score": 214 }
Please answer the following Stack Overflow question: Title: Is there a way to automate the Android SDK installation? <p>Now I have to download and install the Android SDK and <a href="https://developer.android.com/studio/run/managing-avds" rel="nofollow noreferrer">AVD Manager</a>, and then install the APIs, tools through the UI. Is there a way to automate this process?</p>
<h1>UPDATE</h1> <p>The latest versions introduce <code>sdkmanager</code>, a command line tool that allows you to view, install, update, and uninstall packages for the Android SDK.</p> <p>The <code>sdkmanager</code> tool is provided in the Android SDK Tools package (<strong>25.2.3 and higher</strong>) and is located in <code>android_sdk/tools/bin/</code>.</p> <pre class="lang-none prettyprint-override"><code> sdkmanager [--uninstall] [&lt;common args&gt;] [--package_file &lt;file&gt;] [&lt;packages&gt;...] sdkmanager --update [&lt;common args&gt;] sdkmanager --list [&lt;common args&gt;] sdkmanager --licenses [&lt;common args&gt;] In its first form, installs, or uninstalls, or updates packages. By default, the listed packages are installed or (if already installed) updated to the latest version. --uninstall: uninstalled listed packages. &lt;package&gt; is a sdk-style path (e.g. &quot;build-tools;23.0.0&quot; or &quot;platforms;android-23&quot;). &lt;package-file&gt; is a text file where each line is a sdk-style path of a package to install or uninstall. Multiple --package_file arguments may be specified in combination with explicit paths. In its second form (with --update), all installed packages are updated to the latest version. In its third form, all installed and available packages are printed out. In its fourth form (with --licenses), show and offer the option to accept licenses for all available packages that have not already been accepted. Common Arguments: --sdk_root=&lt;sdkRootPath&gt;: Use the specified SDK root instead of the SDK containing this tool --channel=&lt;channelId&gt;: Include packages in channels up to &lt;channelId&gt;. Common channels are: 0 (Stable), 1 (Beta), 2 (Dev), and 3 (Canary). --include_obsolete: With --list, show obsolete packages in the package listing. With --update, update obsolete packages as well as non-obsolete. --no_https: Force all connections to use http rather than https. --proxy=&lt;http | socks&gt;: Connect via a proxy of the given type. --proxy_host=&lt;IP or DNS address&gt;: IP or DNS address of the proxy to use. --proxy_port=&lt;port #&gt;: Proxy port to connect to. * If the env var REPO_OS_OVERRIDE is set to &quot;windows&quot;, &quot;macosx&quot;, or &quot;linux&quot;, packages will be downloaded for that OS. </code></pre> <p>So, to update the packages run</p> <pre class="lang-none prettyprint-override"><code>sdkmanager --update </code></pre> <p>To accept the licenses,</p> <pre class="lang-none prettyprint-override"><code>yes | sdkmanager --licenses </code></pre> <h1>OLD ANSWER</h1> <p><em>(Please note: The <code>android</code> command is deprecated!)</em></p> <p>The closer you can get to automation probably is:</p> <pre class="lang-none prettyprint-override"><code>android update sdk --no-ui </code></pre> <p><code>android</code> provides these options for automatic updates:</p> <pre class="lang-none prettyprint-override"><code>Action &quot;update sdk&quot;: Updates the SDK by suggesting new platforms to install if available. Options: -f --force Forces replacement of a package or its parts, even if something has been modified -u --no-ui Updates from command-line (does not display the GUI) -o --obsolete Installs obsolete packages -t --filter A filter that limits the update to the specified types of packages in the form of a comma-separated list of [platform, tool, platform-tool, doc, sample, extra] -s --no-https Uses HTTP instead of HTTPS (the default) for downloads -n --dry-mode Simulates the update but does not download or install anything </code></pre> <p>If you want to list which packages are available for installation you can use</p> <pre class="lang-none prettyprint-override"><code>android list sdk </code></pre> <p>And you'll obtain an ordered list of packages, for example</p> <pre class="lang-none prettyprint-override"><code>Packages available for installation or update: 9 1- ARM EABI v7a System Image, Android API 15, revision 2 2- Intel x86 Atom System Image, Android API 15, revision 1 3- Android Support, revision 8 4- Google AdMob Ads SDK, revision 6 5- Google Analytics SDK, revision 2 6- Google Play APK Expansion Library, revision 1 7- Google Play Billing Library, revision 2 8- Google Play Licensing Library, revision 2 9- Google Web Driver, revision 2 </code></pre> <p>Also you can limit the update only to a desired component if you use the <code>--filter</code> option</p> <pre class="lang-none prettyprint-override"><code>android update sdk --filter &lt;component&gt; --no-ui </code></pre> <p>where component is one or more of</p> <ul> <li>the numbers returned by <code>android list sdk</code> (i.e. <strong>1</strong>, also know as <em>package index</em>)</li> <li>add-on</li> <li>doc</li> <li>extra</li> <li>platform</li> <li>platform-tool</li> <li>sample</li> <li>source</li> <li>system-image</li> <li>tool</li> </ul> <p>Or can be one or more specific identifiers. For instance, if you just want to download a small set of specific packages, you could do this:</p> <pre class="lang-none prettyprint-override"><code>android update sdk -u --filter platform-tools,android-16,extra-android-support </code></pre> <p>And you'll just get the platform tools, API level 16 and support package JAR files. This is really handy if you're building a build machine only and would have to pay for downloading all the extra stuff that you'll never use.</p> <p>To see the available options you can use --help, for example</p> <pre class="lang-none prettyprint-override"><code>android --help list sdk Usage: android [global options] list sdk [action options] Global options: -h --help : Help on a specific command. -v --verbose : Verbose mode, shows errors, warnings and all messages. --clear-cache: Clear the SDK Manager repository manifest cache. -s --silent : Silent mode, shows errors only. Action &quot;list sdk&quot;: Lists remote SDK repository. Options: -o --obsolete : Deprecated. Please use --all instead. -a --all : Lists all available packages (including obsolete and installed ones) --proxy-host: HTTP/HTTPS proxy host (overrides settings if defined) --proxy-port: HTTP/HTTPS proxy port (overrides settings if defined) -s --no-https : Uses HTTP instead of HTTPS (the default) for downloads. -e --extended : Displays extended details on each package -u --no-ui : Displays list result on console (no GUI) [Default: true] </code></pre>
{ "question_id": 4681697, "question_date": "2011-01-13T15:23:28.330Z", "question_score": 211, "tags": "android|android-sdk-tools|avd", "answer_id": 4682241, "answer_date": "2011-01-13T16:10:38.267Z", "answer_score": 396 }
Please answer the following Stack Overflow question: Title: How to implement an ordered, default dict? <p>I would like to combine <code>OrderedDict()</code> and <code>defaultdict()</code> from <code>collections</code> in one object, which shall be an ordered, default <code>dict</code>.<br /> Is this possible?</p>
<p>The following (using a modified version of <a href="http://code.activestate.com/recipes/523034-emulate-collectionsdefaultdict/" rel="noreferrer">this recipe</a>) works for me:</p> <pre><code>from collections import OrderedDict, Callable class DefaultOrderedDict(OrderedDict): # Source: http://stackoverflow.com/a/6190500/562769 def __init__(self, default_factory=None, *a, **kw): if (default_factory is not None and not isinstance(default_factory, Callable)): raise TypeError('first argument must be callable') OrderedDict.__init__(self, *a, **kw) self.default_factory = default_factory def __getitem__(self, key): try: return OrderedDict.__getitem__(self, key) except KeyError: return self.__missing__(key) def __missing__(self, key): if self.default_factory is None: raise KeyError(key) self[key] = value = self.default_factory() return value def __reduce__(self): if self.default_factory is None: args = tuple() else: args = self.default_factory, return type(self), args, None, None, self.items() def copy(self): return self.__copy__() def __copy__(self): return type(self)(self.default_factory, self) def __deepcopy__(self, memo): import copy return type(self)(self.default_factory, copy.deepcopy(self.items())) def __repr__(self): return 'OrderedDefaultDict(%s, %s)' % (self.default_factory, OrderedDict.__repr__(self)) </code></pre>
{ "question_id": 6190331, "question_date": "2011-05-31T16:02:12.377Z", "question_score": 211, "tags": "python|dictionary", "answer_id": 6190500, "answer_date": "2011-05-31T16:16:25.730Z", "answer_score": 96 }
Please answer the following Stack Overflow question: Title: What are "connecting characters" in Java identifiers? <p>I am reading for SCJP and I have a question regarding this line:</p> <blockquote> <p>Identifiers must start with a letter, a currency character ($), or a connecting character such as the underscore ( _ ). Identifiers cannot start with a number!</p> </blockquote> <p>It states that a valid identifier name can start with a connecting character <strong>such as</strong> underscore. I thought underscores were the only valid option? What other <em>connecting characters</em> are there?</p>
<p>Here is a list of connecting characters. These are characters used to connect words.</p> <p><a href="http://www.fileformat.info/info/unicode/category/Pc/list.htm" rel="noreferrer">http://www.fileformat.info/info/unicode/category/Pc/list.htm</a></p> <pre><code>U+005F _ LOW LINE U+203F ‿ UNDERTIE U+2040 ⁀ CHARACTER TIE U+2054 ⁔ INVERTED UNDERTIE U+FE33 ︳ PRESENTATION FORM FOR VERTICAL LOW LINE U+FE34 ︴ PRESENTATION FORM FOR VERTICAL WAVY LOW LINE U+FE4D ﹍ DASHED LOW LINE U+FE4E ﹎ CENTRELINE LOW LINE U+FE4F ﹏ WAVY LOW LINE U+FF3F _ FULLWIDTH LOW LINE </code></pre> <p>This compiles on Java 7.</p> <pre><code>int _, ‿, ⁀, ⁔, ︳, ︴, ﹍, ﹎, ﹏, _; </code></pre> <hr> <p>An example. In this case <code>tp</code> is the name of a column and the value for a given row.</p> <pre><code>Column&lt;Double&gt; ︴tp︴ = table.getColumn("tp", double.class); double tp = row.getDouble(︴tp︴); </code></pre> <hr> <p>The following</p> <pre><code>for (int i = Character.MIN_CODE_POINT; i &lt;= Character.MAX_CODE_POINT; i++) if (Character.isJavaIdentifierStart(i) &amp;&amp; !Character.isAlphabetic(i)) System.out.print((char) i + " "); } </code></pre> <p>prints</p> <p>$ _ ¢ £ ¤ ¥ ؋ ৲ ৳ ৻ ૱ ௹ ฿ ៛ ‿ ⁀ ⁔ ₠ ₡ ₢ ₣ ₤ ₥ ₦ ₧ ₨ ₩ ₪ ₫ € ₭ ₮ ₯ ₰ ₱ ₲ ₳ ₴ ₵ ₶ ₷ ₸ ₹ ꠸ ﷼ ︳ ︴ ﹍ ﹎ ﹏ ﹩ $ _ ¢ £ ¥ ₩</p>
{ "question_id": 11774099, "question_date": "2012-08-02T08:54:26.813Z", "question_score": 211, "tags": "java|unicode|identifier|scjp", "answer_id": 11774161, "answer_date": "2012-08-02T08:59:03.307Z", "answer_score": 270 }
Please answer the following Stack Overflow question: Title: Sphinx autodoc is not automatic enough <p>I'm trying to use Sphinx to document a 5,000+ line project in Python. It has about 7 base modules. As far as I know, In order to use autodoc I need to write code like this for each file in my project:</p> <pre><code>.. automodule:: mods.set.tests :members: :show-inheritance: </code></pre> <p>This is way too tedious because I have many files. It would be much easier if I could just specify that I wanted the 'mods' package to be documented. Sphinx could then recursively go through the package and make a page for each submodule.</p> <p>Is there a feature like this? If not I could write a script to make all the .rst files, but that would take up a lot of time.</p>
<p><s>You can check this <a href="http://www.bitbucket.org/etienned/sphinx-autopackage-script/src" rel="noreferrer">script</a> that I've made. I think it can help you.</s></p> <p>This script parses a directory tree looking for python modules and packages and creates ReST files appropriately to create code documentation with Sphinx. It also creates a modules index.</p> <p><strong>UPDATE</strong></p> <p>This script is now part of Sphinx 1.1 as <em><a href="http://www.sphinx-doc.org/en/master/man/sphinx-apidoc.html" rel="noreferrer">apidoc</a></em>.</p>
{ "question_id": 2701998, "question_date": "2010-04-23T21:11:53.733Z", "question_score": 211, "tags": "python|python-sphinx|autodoc", "answer_id": 2703173, "answer_date": "2010-04-24T04:03:35.630Z", "answer_score": 160 }
Please answer the following Stack Overflow question: Title: Is type="text/css" necessary in a <link> tag? <p>I was wondering whether or not it is necessary to use <code>&lt;link rel="stylesheet" type="text/css" href=...&gt;</code> over <code>&lt;link rel="stylesheet" href=...&gt;</code>. The <code>rel="stylesheet"</code> marks the information that it is a stylesheet - so <code>text/css</code> doesn't actually add anything as far as I'm concerned.</p> <p>The only stylesheet format used by HTML is CSS anyway, so what does <code>text/css</code> 'say' to the browser? Some websites seem to add the <code>type="text/css"</code> attribute (<a href="http://www.jquery.com/">http://www.jquery.com/</a>), whilst other ones don't (<a href="http://www.youtube.com/">http://www.youtube.com/</a>).</p> <p>So, what is the use of <code>type="text/css"</code> in a <code>&lt;link rel="stylesheet"&gt;</code> element, and is it necessary to include it?</p>
<p>It's not required with the HTML5 spec, but for older versions of HTML is it required.</p> <p><strong>Html 4 W3.org spec</strong></p> <p><a href="http://www.w3.org/TR/html40/struct/links.html#edef-LINK" rel="noreferrer">http://www.w3.org/TR/html40/struct/links.html#edef-LINK</a> <a href="http://www.w3.org/TR/html40/present/styles.html" rel="noreferrer">http://www.w3.org/TR/html40/present/styles.html</a></p> <p>Type stands for The MIME type of the style sheet. The only supported value I have ever seen is Text/CSS, which is probably why HTML5 has dropped it. I imagine they had it for earlier versions to allow future expansion possibilities which never happened.</p> <p>Using HTML5 and not specifying the type, I have run so far into no problems with compatibility even when testing older versions of IE.</p>
{ "question_id": 5409114, "question_date": "2011-03-23T17:17:31.237Z", "question_score": 211, "tags": "html|css", "answer_id": 5409146, "answer_date": "2011-03-23T17:20:04.370Z", "answer_score": 168 }
Please answer the following Stack Overflow question: Title: Why use softmax as opposed to standard normalization? <p>In the output layer of a neural network, it is typical to use the softmax function to approximate a probability distribution:</p> <p><img src="https://i.stack.imgur.com/r1MZm.png" alt="enter image description here"></p> <p>This is expensive to compute because of the exponents. Why not simply perform a Z transform so that all outputs are positive, and then normalise just by dividing all outputs by the sum of all outputs?</p>
<p>There is one nice attribute of Softmax as compared with standard normalisation. </p> <p>It react to low stimulation (think blurry image) of your neural net with rather uniform distribution and to high stimulation (ie. large numbers, think crisp image) with probabilities close to 0 and 1.</p> <p>While standard normalisation does not care as long as the proportion are the same.</p> <p>Have a look what happens when soft max has 10 times larger input, ie your neural net got a crisp image and a lot of neurones got activated</p> <pre><code>&gt;&gt;&gt; softmax([1,2]) # blurry image of a ferret [0.26894142, 0.73105858]) # it is a cat perhaps !? &gt;&gt;&gt; softmax([10,20]) # crisp image of a cat [0.0000453978687, 0.999954602]) # it is definitely a CAT ! </code></pre> <p>And then compare it with standard normalisation</p> <pre><code>&gt;&gt;&gt; std_norm([1,2]) # blurry image of a ferret [0.3333333333333333, 0.6666666666666666] # it is a cat perhaps !? &gt;&gt;&gt; std_norm([10,20]) # crisp image of a cat [0.3333333333333333, 0.6666666666666666] # it is a cat perhaps !? </code></pre>
{ "question_id": 17187507, "question_date": "2013-06-19T09:20:26.780Z", "question_score": 211, "tags": "math|neural-network|softmax", "answer_id": 45186059, "answer_date": "2017-07-19T09:14:50.887Z", "answer_score": 184 }
Please answer the following Stack Overflow question: Title: Is it expensive to use try-catch blocks even if an exception is never thrown? <p>We know that it is expensive to catch exceptions. But, is it also expensive to use a try-catch block in Java even if an exception is never thrown? </p> <p>I found the Stack Overflow question/answer <em><a href="https://stackoverflow.com/questions/164613/why-are-try-blocks-expensive">Why are try blocks expensive?</a></em>, but it is for <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="noreferrer">.NET</a>.</p>
<p><code>try</code> has almost no expense at all. Instead of doing the work of setting up the <code>try</code> at runtime, the code's metadata is structured at compile time such that when an exception is thrown, it now does a relatively expensive operation of walking up the stack and seeing if any <code>try</code> blocks exist that would catch this exception. From a layman's perspective, <code>try</code> may as well be free. It's actually throwing the exception that costs you - but unless you're throwing hundreds or thousands of exceptions, you still won't notice the cost.</p> <hr> <p><code>try</code> has some minor costs associated with it. Java cannot do some optimizations on code in a <code>try</code> block that it would otherwise do. For example, Java will often re-arrange instructions in a method to make it run faster - but Java also needs to guarantee that if an exception is thrown, the method's execution is observed as though its statements, as written in the source code, executed in order up to some line.</p> <p>Because in a <code>try</code> block an exception can be thrown (at any line in the try block! Some exceptions are thrown asynchronously, such as by calling <code>stop</code> on a Thread (which is deprecated), and even besides that OutOfMemoryError can happen almost anywhere) and yet it can be caught and code continue to execute afterwards in the same method, it is more difficult to reason about optimizations that can be made, so they are less likely to happen. (Someone would have to program the compiler to do them, reason about and guarantee correctness, etc. It'd be a big pain for something meant to be 'exceptional') But again, in practice you won't notice things like this.</p>
{ "question_id": 16451777, "question_date": "2013-05-08T23:16:40.290Z", "question_score": 211, "tags": "java|performance|try-catch", "answer_id": 16451908, "answer_date": "2013-05-08T23:30:21.907Z", "answer_score": 225 }
Please answer the following Stack Overflow question: Title: What are 'closures' in .NET? <p>What is a <em>closure</em>? Do we have them in .NET?</p> <p>If they do exist in .NET, could you please provide a code snippet (preferably in C#) explaining it?</p>
<p>I have <a href="http://csharpindepth.com/Articles/Chapter5/Closures.aspx" rel="noreferrer">an article on this very topic</a>. (It has lots of examples.)</p> <p>In essence, a closure is a block of code which can be executed at a later time, but which maintains the environment in which it was first created - i.e. it can still use the local variables etc of the method which created it, even after that method has finished executing.</p> <p>The general feature of closures is implemented in C# by anonymous methods and lambda expressions.</p> <p>Here's an example using an anonymous method:</p> <pre><code>using System; class Test { static void Main() { Action action = CreateAction(); action(); action(); } static Action CreateAction() { int counter = 0; return delegate { // Yes, it could be done in one statement; // but it is clearer like this. counter++; Console.WriteLine("counter={0}", counter); }; } } </code></pre> <p>Output:</p> <pre><code>counter=1 counter=2 </code></pre> <p>Here we can see that the action returned by CreateAction still has access to the counter variable, and can indeed increment it, even though CreateAction itself has finished.</p>
{ "question_id": 428617, "question_date": "2009-01-09T16:01:26.980Z", "question_score": 211, "tags": ".net|closures", "answer_id": 428624, "answer_date": "2009-01-09T16:04:44.463Z", "answer_score": 278 }
Please answer the following Stack Overflow question: Title: jQuery pitfalls to avoid <p>I am starting a project with jQuery.</p> <p>What pitfalls/errors/misconceptions/abuses/misuses did you have in your jQuery project?</p>
<p>Being unaware of the performance hit and overusing selectors instead of assigning them to local variables. For example:-</p> <pre><code>$('#button').click(function() { $('#label').method(); $('#label').method2(); $('#label').css('background-color', 'red'); }); </code></pre> <p>Rather than:-</p> <pre><code>$('#button').click(function() { var $label = $('#label'); $label.method(); $label.method2(); $label.css('background-color', 'red'); }); </code></pre> <p>Or <a href="http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip10" rel="noreferrer">even better with chaining</a>:-</p> <pre><code>$('#button').click(function() { $("#label").method().method2().css("background-color", "red"); }); </code></pre> <p>I found <a href="http://www.youtube.com/watch?v=mHtdZgou0qU" rel="noreferrer">this</a> the enlightening moment when I realized how the call stacks work.</p> <p>Edit: incorporated suggestions in comments.</p>
{ "question_id": 1229259, "question_date": "2009-08-04T18:52:37.020Z", "question_score": 211, "tags": "javascript|jquery", "answer_id": 1229339, "answer_date": "2009-08-04T19:07:42.607Z", "answer_score": 189 }
Please answer the following Stack Overflow question: Title: In-Place Radix Sort <p>This is a long text. Please bear with me. Boiled down, the question is: <strong>Is there a workable in-place radix sort algorithm</strong>?</p> <hr> <h2>Preliminary</h2> <p>I've got a huge number of <em>small fixed-length</em> strings that only use the letters “A”, “C”, “G” and “T” (yes, you've guessed it: <a href="https://en.wikipedia.org/wiki/DNA" rel="noreferrer">DNA</a>) that I want to sort.</p> <p>At the moment, I use <code>std::sort</code> which uses <a href="https://en.wikipedia.org/wiki/Introsort" rel="noreferrer">introsort</a> in all common implementations of the <a href="https://en.wikipedia.org/wiki/Standard_Template_Library" rel="noreferrer">STL</a>. This works quite well. However, I'm convinced that <a href="https://en.wikipedia.org/wiki/Radix_sort" rel="noreferrer">radix sort</a> fits my problem set perfectly and should work <strong>much</strong> better in practice.</p> <h2>Details</h2> <p>I've tested this assumption with a very naive implementation and for relatively small inputs (on the order of 10,000) this was true (well, at least more than twice as fast). However, runtime degrades abysmally when the problem size becomes larger (<em>N</em> > 5,000,000).</p> <p>The reason is obvious: radix sort requires copying the whole data (more than once in my naive implementation, actually). This means that I've put ~ 4 GiB into my main memory which obviously kills performance. Even if it didn't, I can't afford to use this much memory since the problem sizes actually become even larger.</p> <h2>Use Cases</h2> <p>Ideally, this algorithm should work with any string length between 2 and 100, for DNA as well as DNA5 (which allows an additional wildcard character “N”), or even DNA with <a href="https://en.wikipedia.org/wiki/International_Union_of_Pure_and_Applied_Chemistry" rel="noreferrer">IUPAC</a> <a href="https://en.wikipedia.org/wiki/Nucleic_acid_notation" rel="noreferrer">ambiguity codes</a> (resulting in 16 distinct values). However, I realize that all these cases cannot be covered, so I'm happy with any speed improvement I get. The code can decide dynamically which algorithm to dispatch to.</p> <h2>Research</h2> <p>Unfortunately, the <a href="https://en.wikipedia.org/wiki/Radix_sort" rel="noreferrer">Wikipedia article on radix sort</a> is useless. The section about an in-place variant is complete rubbish. The <a href="http://xlinux.nist.gov/dads/HTML/radixsort.html" rel="noreferrer">NIST-DADS section on radix sort</a> is next to nonexistent. There's a promising-sounding paper called <a href="https://www.mii.vu.lt/informatica/pdf/INFO562.pdf" rel="noreferrer">Efficient Adaptive In-Place Radix Sorting</a> which describes the algorithm “MSL”. Unfortunately, this paper, too, is disappointing.</p> <p>In particular, there are the following things.</p> <p>First, the algorithm contains several mistakes and leaves a lot unexplained. In particular, it doesn’t detail the recursion call (I simply assume that it increments or reduces some pointer to calculate the current shift and mask values). Also, it uses the functions <code>dest_group</code> and <code>dest_address</code> without giving definitions. I fail to see how to implement these efficiently (that is, in O(1); at least <code>dest_address</code> isn’t trivial).</p> <p>Last but not least, the algorithm achieves in-place-ness by swapping array indices with elements inside the input array. This obviously only works on numerical arrays. I need to use it on strings. Of course, I could just screw strong typing and go ahead assuming that the memory will tolerate my storing an index where it doesn’t belong. But this only works as long as I can squeeze my strings into 32 bits of memory (assuming 32 bit integers). That's only 16 characters (let's ignore for the moment that 16 > log(5,000,000)).</p> <p>Another paper by one of the authors gives no accurate description at all, but it gives MSL’s runtime as sub-linear which is flat out wrong.</p> <p><strong>To recap</strong>: Is there any hope of finding a working reference implementation or at least a good pseudocode/description of a working in-place radix sort that works on DNA strings?</p>
<p>Well, here's a simple implementation of an MSD radix sort for DNA. It's written in D because that's the language that I use most and therefore am least likely to make silly mistakes in, but it could easily be translated to some other language. It's in-place but requires <code>2 * seq.length</code> passes through the array.</p> <pre class="lang-cpp prettyprint-override"><code>void radixSort(string[] seqs, size_t base = 0) { if(seqs.length == 0) return; size_t TPos = seqs.length, APos = 0; size_t i = 0; while(i &lt; TPos) { if(seqs[i][base] == 'A') { swap(seqs[i], seqs[APos++]); i++; } else if(seqs[i][base] == 'T') { swap(seqs[i], seqs[--TPos]); } else i++; } i = APos; size_t CPos = APos; while(i &lt; TPos) { if(seqs[i][base] == 'C') { swap(seqs[i], seqs[CPos++]); } i++; } if(base &lt; seqs[0].length - 1) { radixSort(seqs[0..APos], base + 1); radixSort(seqs[APos..CPos], base + 1); radixSort(seqs[CPos..TPos], base + 1); radixSort(seqs[TPos..seqs.length], base + 1); } } </code></pre> <p>Obviously, this is kind of specific to DNA, as opposed to being general, but it should be fast.</p> <h1>Edit:</h1> <p>I got curious whether this code actually works, so I tested/debugged it while waiting for my own bioinformatics code to run. The version above now is actually tested and works. For 10 million sequences of 5 bases each, it's about 3x faster than an optimized introsort.</p>
{ "question_id": 463105, "question_date": "2009-01-20T21:04:06.667Z", "question_score": 211, "tags": "algorithm|language-agnostic|sorting|radix-sort|in-place", "answer_id": 463158, "answer_date": "2009-01-20T21:19:25.870Z", "answer_score": 62 }
Please answer the following Stack Overflow question: Title: What do <:<, <%<, and =:= mean in Scala 2.8, and where are they documented? <p>I can see in the API docs for <a href="https://scala-lang.org/files/archive/api/2.8.2/scala/Predef$.html" rel="noreferrer">Predef</a> that they're subclasses of a generic function type (From) => To, but that's all it says. Um, what? Maybe there's documentation somewhere, but search engines don't handle "names" like "&lt;:&lt;" very well, so I haven't been able to find it.</p> <p>Follow-up question: when should I use these funky symbols/classes, and why?</p>
<p>These are called <strong>generalized type constraints</strong>. They allow you, from within a type-parameterized class or trait, to <em>further constrain</em> one of its type parameters. Here's an example:</p> <pre><code>case class Foo[A](a:A) { // 'A' can be substituted with any type // getStringLength can only be used if this is a Foo[String] def getStringLength(implicit evidence: A =:= String) = a.length } </code></pre> <p>The implicit argument <code>evidence</code> is supplied by the compiler, iff <code>A</code> is <code>String</code>. You can think of it as a <em>proof</em> that <code>A</code> is <code>String</code>--the argument itself isn't important, only knowing that it exists. <em>[edit: well, technically it actually is important because it represents an implicit conversion from <code>A</code> to <code>String</code>, which is what allows you to call <code>a.length</code> and not have the compiler yell at you]</em></p> <p>Now I can use it like so:</p> <pre><code>scala&gt; Foo("blah").getStringLength res6: Int = 4 </code></pre> <p>But if I tried use it with a <code>Foo</code> containing something other than a <code>String</code>:</p> <pre><code>scala&gt; Foo(123).getStringLength &lt;console&gt;:9: error: could not find implicit value for parameter evidence: =:=[Int,String] </code></pre> <p>You can read that error as "could not find evidence that Int == String"... that's as it should be! <code>getStringLength</code> is imposing <em>further restrictions</em> on the type of <code>A</code> than what <code>Foo</code> in general requires; namely, you can only invoke <code>getStringLength</code> on a <code>Foo[String]</code>. This constraint is enforced at compile-time, which is cool!</p> <p><code>&lt;:&lt;</code> and <code>&lt;%&lt;</code> work similarly, but with slight variations:</p> <ul> <li><code>A =:= B</code> means A must be exactly B</li> <li><code>A &lt;:&lt; B</code> means A must be a subtype of B (analogous to the <em>simple</em> type constraint <code>&lt;:</code>)</li> <li><code>A &lt;%&lt; B</code> means A must be <em>viewable</em> as B, possibly via implicit conversion (analogous to the simple type constraint <code>&lt;%</code>)</li> </ul> <p><a href="http://gist.github.com/229163" rel="noreferrer">This snippet</a> by @retronym is a good explanation of how this sort of thing used to be accomplished and how generalized type constraints make it easier now.</p> <p><strong>ADDENDUM</strong></p> <p>To answer your follow-up question, admittedly the example I gave is pretty contrived and not obviously useful. But imagine using it to define something like a <code>List.sumInts</code> method, which adds up a list of integers. You don't want to allow this method to be invoked on any old <code>List</code>, just a <code>List[Int]</code>. However the <code>List</code> type constructor can't be so constrainted; you still want to be able to have lists of strings, foos, bars, and whatnots. So by placing a generalized type constraint on <code>sumInts</code>, you can ensure that <em>just that method</em> has an additional constraint that it can only be used on a <code>List[Int]</code>. Essentially you're writing special-case code for certain kinds of lists.</p>
{ "question_id": 3427345, "question_date": "2010-08-06T20:03:25.250Z", "question_score": 211, "tags": "scala|scala-2.8|type-constraints", "answer_id": 3427759, "answer_date": "2010-08-06T20:57:14.117Z", "answer_score": 232 }
Please answer the following Stack Overflow question: Title: Why does a Java class compile differently with a blank line? <p>I have the following Java class</p> <pre><code>public class HelloWorld { public static void main(String []args) { } } </code></pre> <p>When I compile this file and run a sha256 on the resulting class file I get </p> <pre class="lang-none prettyprint-override"><code>9c8d09e27ea78319ddb85fcf4f8085aa7762b0ab36dc5ba5fd000dccb63960ff HelloWorld.class </code></pre> <p>Next I modified the class and added a blank line like this: </p> <pre><code>public class HelloWorld { public static void main(String []args) { } } </code></pre> <p>Again I ran a sha256 on the output expecting to get the same result but instead I got </p> <pre class="lang-none prettyprint-override"><code>11f7ad3ad03eb9e0bb7bfa3b97bbe0f17d31194d8d92cc683cfbd7852e2d189f HelloWorld.class </code></pre> <p>I have read on <a href="https://www.tutorialspoint.com/java/java_basic_syntax.htm" rel="noreferrer">this TutorialsPoint article</a> that:</p> <blockquote> <p>A line containing only white space, possibly with a comment, is known as a blank line, and Java totally ignores it.</p> </blockquote> <p>So my question is, since Java ignores blank lines why is the compiled bytecode different for both programs?</p> <p>Namely the difference in that in <code>HelloWorld.class</code> a <code>0x03</code> byte is replaced by a <code>0x04</code> byte.</p>
<p>Basically, line numbers are kept for debugging, so if you change your source code the way you did, your method starts at a different line and the compiled class reflects the difference.</p>
{ "question_id": 52625161, "question_date": "2018-10-03T10:35:20.333Z", "question_score": 211, "tags": "java|compilation|javac|bytecode", "answer_id": 52625304, "answer_date": "2018-10-03T10:43:14.080Z", "answer_score": 336 }
Please answer the following Stack Overflow question: Title: Can modern C++ get you performance for free? <p>It is sometimes claimed that C++11/14 can get you a performance boost even when merely compiling C++98 code. The justification is usually along the lines of move semantics, as in some cases the rvalue constructors are automatically generated or now part of the STL. Now I'm wondering whether these cases were previously actually already handled by RVO or similar compiler optimizations. </p> <p>My question then is if you could give me an actual example of a piece of C++98 code that, without modification, runs faster using a compiler supporting the new language features. I do understand that a standard conforming compiler is not required to do the copy elision and just by that reason move semantics might bring about speed, but I'd like to see a less pathological case, if you will.</p> <p>EDIT: Just to be clear, I am not asking whether new compilers are faster than old compilers, but rather if there is code whereby adding -std=c++14 to my compiler flags it would run faster (avoid copies, but if you can come up with anything else besides move semantics, I'd be interested, too)</p>
<p>I am aware of 5 general categories where recompiling a C++03 compiler as C++11 can cause unbounded performance increases that are practically unrelated to quality of implementation. These are all variations of move semantics.</p> <h1><code>std::vector</code> reallocate</h1> <pre><code>struct bar{ std::vector&lt;int&gt; data; }; std::vector&lt;bar&gt; foo(1); foo.back().data.push_back(3); foo.reserve(10); // two allocations and a delete occur in C++03 </code></pre> <p>every time the <code>foo</code>'s buffer is reallocated in C++03 it copied every <code>vector</code> in <code>bar</code>.</p> <p>In C++11 it instead moves the <code>bar::data</code>s, which is basically free.</p> <p>In this case, this relies on optimizations inside the <code>std</code> container <code>vector</code>. In every case below, the use of <code>std</code> containers is just because they are C++ objects that have efficient <code>move</code> semantics in C++11 "automatically" when you upgrade your compiler. Objects that don't block it that contain a <code>std</code> container also inherit the automatic improved <code>move</code> constructors.</p> <h1>NRVO failure</h1> <p>When NRVO (named return value optimization) fails, in C++03 it falls back on copy, on C++11 it falls back on move. Failures of NRVO are easy:</p> <pre><code>std::vector&lt;int&gt; foo(int count){ std::vector&lt;int&gt; v; // oops if (count&lt;=0) return std::vector&lt;int&gt;(); v.reserve(count); for(int i=0;i&lt;count;++i) v.push_back(i); return v; } </code></pre> <p>or even:</p> <pre><code>std::vector&lt;int&gt; foo(bool which) { std::vector&lt;int&gt; a, b; // do work, filling a and b, using the other for calculations if (which) return a; else return b; } </code></pre> <p>We have three values -- the return value, and two different values within the function. Elision allows the values within the function to be 'merged' with the return value, but not with each other. They both cannot be merged with the return value without merging with each other.</p> <p>The basic issue is that NRVO elision is fragile, and code with changes not near the <code>return</code> site can suddenly have massive performance reductions at that spot with no diagnostic emitted. In most NRVO failure cases C++11 ends up with a <code>move</code>, while C++03 ends up with a copy.</p> <h1>Returning a function argument</h1> <p>Elision is also impossible here:</p> <pre><code>std::set&lt;int&gt; func(std::set&lt;int&gt; in){ return in; } </code></pre> <p>in C++11 this is cheap: in C++03 there is no way to avoid the copy. Arguments to functions cannot be elided with the return value, because the lifetime and location of the parameter and return value is managed by the calling code.</p> <p>However, C++11 can move from one to the other. (In a less toy example, something might be done to the <code>set</code>).</p> <h1><code>push_back</code> or <code>insert</code></h1> <p>Finally elision into containers does not happen: but C++11 overloads rvalue move insert operators, which saves copies.</p> <pre><code>struct whatever { std::string data; int count; whatever( std::string d, int c ):data(d), count(c) {} }; std::vector&lt;whatever&gt; v; v.push_back( whatever("some long string goes here", 3) ); </code></pre> <p>in C++03 a temporary <code>whatever</code> is created, then it is copied into the vector <code>v</code>. 2 <code>std::string</code> buffers are allocated, each with identical data, and one is discarded.</p> <p>In C++11 a temporary <code>whatever</code> is created. The <code>whatever&amp;&amp;</code> <code>push_back</code> overload then <code>move</code>s that temporary into the vector <code>v</code>. One <code>std::string</code> buffer is allocated, and moved into the vector. An empty <code>std::string</code> is discarded.</p> <h1>Assignment</h1> <p>Stolen from @Jarod42's answer below.</p> <p>Elision cannot occur with assignment, but move-from can.</p> <pre><code>std::set&lt;int&gt; some_function(); std::set&lt;int&gt; some_value; // code some_value = some_function(); </code></pre> <p>here <code>some_function</code> returns a candidate to elide from, but because it is not used to construct an object directly, it cannot be elided. In C++03, the above results in the contents of the temporary being copied into <code>some_value</code>. In C++11, it is moved into <code>some_value</code>, which basically is free.</p> <hr> <p>For the full effect of the above, you need a compiler that synthesizes move constructors and assignment for you.</p> <p>MSVC 2013 implements move constructors in <code>std</code> containers, but does not synthesize move constructors on your types.</p> <p>So types containing <code>std::vector</code>s and similar do not get such improvements in MSVC2013, but will start getting them in MSVC2015.</p> <p>clang and gcc have long since implemented implicit move constructors. Intel's 2013 compiler will support implicit generation of move constructors if you pass <code>-Qoption,cpp,--gen_move_operations</code> (they don't do it by default in an effort to be cross-compatible with MSVC2013).</p>
{ "question_id": 27595429, "question_date": "2014-12-22T01:03:48.597Z", "question_score": 211, "tags": "c++|performance|c++11|move-semantics|c++14", "answer_id": 27595550, "answer_date": "2014-12-22T01:33:05.037Z", "answer_score": 227 }
Please answer the following Stack Overflow question: Title: How do I delete a Discipline in EPF Composer 1.5? <p>I'm making a method combining Scrum with the OpenUP lifecycle and deliverables. I also want to keep the OpenUP disciplines apart from "Project Management". I can "hide" it so that it's not immediately obvious in my generated method site. But when you then navigate to the "Risk List" artefact for example the PM is still seen as contributing, and if you click on the link, you get taken to the PM Discipline page.</p> <p>How can I remove it completely from my method without deleting it from the OpenUP library which I'm consuming?</p>
<p>I've never used EPF Composer.</p> <p>I did a little bit of google searches and I understand what you are looking for can be done through Configurations (select OpenUP in your Library view) and published View definitions.</p> <p>See slide 83 and 84 of this PPT document. You should be able to take it from there.</p> <p><a href="http://www.google.com/url?sa=t&amp;rct=j&amp;q=%22epf%20composer%22%20%22standard%20categories%22&amp;source=web&amp;cd=9&amp;ved=0CFoQFjAI&amp;url=http://www.mountainview-itsm.com/Mountainview/downloads/An_Introduction_to_EPF.ppt&amp;ei=p9tVUfTwD4-i8gTFroEY&amp;usg=AFQjCNGlAoGW_ujO2uRyTa_h9jYwJq2YfA" rel="nofollow">An Introduction to the Eclipse Process Framework</a>.</p> <p>In case the link does not work, I searched for "EPF Composer" "Standard categories" on google and the document is at the bottom of the first results page.</p> <p>Good luck.</p>
{ "question_id": 71332, "question_date": "2008-09-16T11:20:20.620Z", "question_score": 211, "tags": "eclipse|agile-processes", "answer_id": 15709283, "answer_date": "2013-03-29T18:31:48.967Z", "answer_score": 2 }
Please answer the following Stack Overflow question: Title: Encode String to UTF-8 <p>I have a String with a "ñ" character and I have some problems with it. I need to encode this String to UTF-8 encoding. I have tried it by this way, but it doesn't work:</p> <pre><code>byte ptext[] = myString.getBytes(); String value = new String(ptext, "UTF-8"); </code></pre> <p>How do I encode that string to utf-8?</p>
<p><code>String</code> objects in Java use the UTF-16 encoding that can't be modified<sup>*</sup>.</p> <p>The only thing that can have a different encoding is a <code>byte[]</code>. So if you need UTF-8 data, then you need a <code>byte[]</code>. If you have a <code>String</code> that contains unexpected data, then the problem is at some earlier place that incorrectly converted some binary data to a <code>String</code> (i.e. it was using the wrong encoding).</p> <p><sup>* As a matter of implementation, <code>String</code> can <a href="https://openjdk.java.net/jeps/254" rel="noreferrer">internally use a ISO-8859-1 encoded <code>byte[]</code></a> when the range of characters fits it, but that is an implementation-specific optimization that isn't visible to users of <code>String</code> (i.e. you'll never notice unless you dig into the source code or use reflection to dig into a <code>String</code> object).</sup></p>
{ "question_id": 5729806, "question_date": "2011-04-20T11:55:42.943Z", "question_score": 210, "tags": "java|utf-8", "answer_id": 5729834, "answer_date": "2011-04-20T11:58:09.463Z", "answer_score": 154 }
Please answer the following Stack Overflow question: Title: Select arrow style change <p>I'm trying to replace the arrow of a select with a picture of my own. I'm including the select in a div with the same size, I set the background of the select as transparent and I'm including a picture(with the same size as the arrow) in the right top corner of the div as background. </p> <p>It only works in Chrome. </p> <p><img src="https://i.stack.imgur.com/o2JSU.png" alt="enter image description here"> </p> <p>How can I make it work in Firefox and IE9 where I'm getting this: </p> <p><img src="https://i.stack.imgur.com/EpxWl.png" alt="enter image description here"></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>.styled-select { width: 100px; height: 17px; overflow: hidden; overflow: -moz-hidden-unscrollable; background: url(images/downarrow_blue.png) no-repeat right white; border: 2px double red; display: inline-block; position: relative; } .styled-select select { background: transparent; -webkit-appearance: none; width: 100px; font-size: 11px; border: 0; height: 17px; position: absolute; left: 0; top: 0; } body { background-color: #333333; color: #FFFFFF; } .block label { color: white; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;HTML&gt; &lt;HEAD&gt; &lt;/HEAD&gt; &lt;BODY&gt; &lt;p/&gt; &lt;form action="/prepareUpdateCategoryList.do?forwardto=search"&gt; &lt;fieldset class="block" id="searchBlock"&gt; &lt;p&gt; &lt;label style="width:80px"&gt;Class&lt;/label&gt; &lt;div class="styled-select"&gt; &lt;select property="voucherCategoryClass"&gt; &lt;option value="0"&gt;Select &lt;/option&gt; &lt;option value="7382"&gt;steam &lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/p&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;/BODY&gt; &lt;/HTML&gt;</code></pre> </div> </div> </p>
<p>Have you tried something like this:</p> <pre><code>.styled-select select { -moz-appearance:none; /* Firefox */ -webkit-appearance:none; /* Safari and Chrome */ appearance:none; } </code></pre> <p>Haven't tested, but should work.</p> <p><strong>EDIT</strong>: It looks like Firefox doesn't support this feature up until version 35 (<a href="https://bugzilla.mozilla.org/show_bug.cgi?id=649849" rel="noreferrer">read more here</a>)</p> <p>There is a workaround <a href="https://stackoverflow.com/questions/4142619/how-to-make-select-element-be-transparent-in-chrome/">here</a>, take a look at <code>jsfiddle</code> on that post.</p>
{ "question_id": 14218307, "question_date": "2013-01-08T15:25:46.507Z", "question_score": 210, "tags": "css|select", "answer_id": 14218448, "answer_date": "2013-01-08T15:32:19.910Z", "answer_score": 188 }
Please answer the following Stack Overflow question: Title: How to reload page every 5 seconds? <p>I am converting one layout to html; once I make the changes in code/html/css, every time I have to hit F5. Is there any simple javascript/jQuery solution for this? I.e. after I add the script, reload the whole page every 5 seconds (or some other specific time).</p>
<pre><code> &lt;meta http-equiv="refresh" content="5; URL=http://www.yourdomain.com/yoursite.html"&gt; </code></pre> <p>If it has to be in the script use <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout" rel="noreferrer">setTimeout</a> like:</p> <pre><code>setTimeout(function(){ window.location.reload(1); }, 5000); </code></pre>
{ "question_id": 2787679, "question_date": "2010-05-07T10:00:34.790Z", "question_score": 210, "tags": "javascript|jquery", "answer_id": 2787691, "answer_date": "2010-05-07T10:03:28.057Z", "answer_score": 445 }
Please answer the following Stack Overflow question: Title: Creating a dictionary from a csv file? <p>I am trying to create a dictionary from a csv file. The first column of the csv file contains unique keys and the second column contains values. Each row of the csv file represents a unique key, value pair within the dictionary. I tried to use the <a href="https://docs.python.org/3/library/csv.html#csv.DictReader"><code>csv.DictReader</code></a> and <a href="https://docs.python.org/3/library/csv.html#csv.DictWriter"><code>csv.DictWriter</code></a> classes, but I could only figure out how to generate a new dictionary for each row. I want one dictionary. Here is the code I am trying to use:</p> <pre><code>import csv with open('coors.csv', mode='r') as infile: reader = csv.reader(infile) with open('coors_new.csv', mode='w') as outfile: writer = csv.writer(outfile) for rows in reader: k = rows[0] v = rows[1] mydict = {k:v for k, v in rows} print(mydict) </code></pre> <p>When I run the above code I get a <code>ValueError: too many values to unpack (expected 2)</code>. How do I create one dictionary from a csv file? Thanks.</p>
<p>I believe the syntax you were looking for is as follows:</p> <pre><code>import csv with open('coors.csv', mode='r') as infile: reader = csv.reader(infile) with open('coors_new.csv', mode='w') as outfile: writer = csv.writer(outfile) mydict = {rows[0]:rows[1] for rows in reader} </code></pre> <p>Alternately, for python &lt;= 2.7.1, you want:</p> <pre><code>mydict = dict((rows[0],rows[1]) for rows in reader) </code></pre>
{ "question_id": 6740918, "question_date": "2011-07-19T00:09:26.830Z", "question_score": 210, "tags": "python|csv|dictionary|list-comprehension", "answer_id": 6740968, "answer_date": "2011-07-19T00:16:44.390Z", "answer_score": 217 }
Please answer the following Stack Overflow question: Title: Unrecognized SSL message, plaintext connection? Exception <p>I have a java complied package to speak with the https server on net. Running the compilation gives the following exception:</p> <pre><code>javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection? at com.sun.net.ssl.internal.ssl.InputRecord.handleUnknownRecord(Unknown Source) at com.sun.net.ssl.internal.ssl.InputRecord.read(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source) at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source) at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source) at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source) at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(Unknown Source) </code></pre> <p>I think this is due to the connection established with the client machine is not secure. Is there any way to configure the local machine or ports in order to connect to the remote https server?</p>
<blockquote> <p>I think this is due to the connection established with the client machine is not secure.</p> </blockquote> <p>It is due to the fact that you are talking to an HTTP server, not an HTTPS server. Probably you didn't use the correct port number for HTTPS.</p>
{ "question_id": 6532273, "question_date": "2011-06-30T08:49:40.793Z", "question_score": 210, "tags": "java|https", "answer_id": 6533715, "answer_date": "2011-06-30T11:00:27.360Z", "answer_score": 289 }
Please answer the following Stack Overflow question: Title: CSS div element - how to show horizontal scroll bars only? <p>I have a div container and have defined its style as follows:</p> <pre><code>div#tbl-container { width: 600px; overflow: auto; scrollbar-base-color:#ffeaff } </code></pre> <p>This gives me both horizontal and vertical scroll bars automatically once I populate my table which is contained by this div. I just want only horizontal scroll bars to appear automatically. I will modify the height of the table programmatically.</p> <p>How do I do this?</p>
<p>You shouldn't get both horizontal and vertical scrollbars unless you make the content large enough to require them.</p> <p>However you typically do in IE due to a bug. Check in other browsers (Firefox etc.) to find out whether it is in fact only IE that is doing it.</p> <p>IE6-7 (amongst other browsers) supports the proposed CSS3 extension to set scrollbars independently, which you could use to suppress the vertical scrollbar:</p> <pre><code>overflow: auto; overflow-y: hidden; </code></pre> <p>You may also need to add for IE8:</p> <pre><code>-ms-overflow-y: hidden; </code></pre> <p>as Microsoft are threatening to move all pre-CR-standard properties into their own ‘-ms’ box in IE8 Standards Mode. (This would have made sense if they'd always done it that way, but is rather an inconvenience for everyone now.)</p> <p>On the other hand it's entirely possible IE8 will have fixed the bug anyway.</p>
{ "question_id": 258372, "question_date": "2008-11-03T11:24:57.160Z", "question_score": 210, "tags": "css|html", "answer_id": 258393, "answer_date": "2008-11-03T11:35:23.220Z", "answer_score": 287 }
Please answer the following Stack Overflow question: Title: jQuery - replace all instances of a character in a string <p>This does not work and I need it badly</p> <pre><code>$('some+multi+word+string').replace('+', ' ' ); </code></pre> <p>always gets</p> <pre><code>some multi+word+string </code></pre> <p>it's always replacing for the first instance only, but I need it to work for all + symbols.</p>
<p>You need to use a regular expression, so that you can specify the global (g) flag:</p> <pre><code>var s = 'some+multi+word+string'.replace(/\+/g, ' '); </code></pre> <p>(I removed the <code>$()</code> around the string, as <code>replace</code> is not a jQuery method, so that won't work at all.)</p>
{ "question_id": 13574980, "question_date": "2012-11-26T23:30:33.740Z", "question_score": 210, "tags": "jquery|string|replace", "answer_id": 13574989, "answer_date": "2012-11-26T23:31:36.760Z", "answer_score": 429 }
Please answer the following Stack Overflow question: Title: How to verify if a file exists in a batch file? <p>I have to create a <code>.BAT</code> file that does this:</p> <ol> <li>If <code>C:\myprogram\sync\data.handler</code> exists, exit;</li> <li>If <code>C:\myprogram\html\data.sql</code> does not exist, exit;</li> <li>In <code>C:\myprogram\sync\</code> delete all files and folders except (<code>test</code>, <code>test3</code> and <code>test2</code>)</li> <li>Copy <code>C:\myprogram\html\data.sql</code> to <code>C:\myprogram\sync\</code></li> <li>Call other batch file with option <code>sync.bat myprogram.ini</code>.</li> </ol> <p>If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.</p>
<p>You can use IF EXIST to check for a file:</p> <pre><code>IF EXIST "filename" ( REM Do one thing ) ELSE ( REM Do another thing ) </code></pre> <p>If you do not need an "else", you can do something like this:</p> <pre><code>set __myVariable= IF EXIST "C:\folder with space\myfile.txt" set __myVariable=C:\folder with space\myfile.txt IF EXIST "C:\some other folder with space\myfile.txt" set __myVariable=C:\some other folder with space\myfile.txt set __myVariable= </code></pre> <p>Here's a working example of searching for a file or a folder:</p> <pre><code>REM setup echo "some text" &gt; filename mkdir "foldername" REM finds file IF EXIST "filename" ( ECHO file filename exists ) ELSE ( ECHO file filename does not exist ) REM does not find file IF EXIST "filename2.txt" ( ECHO file filename2.txt exists ) ELSE ( ECHO file filename2.txt does not exist ) REM folders must have a trailing backslash REM finds folder IF EXIST "foldername\" ( ECHO folder foldername exists ) ELSE ( ECHO folder foldername does not exist ) REM does not find folder IF EXIST "filename\" ( ECHO folder filename exists ) ELSE ( ECHO folder filename does not exist ) </code></pre>
{ "question_id": 3022176, "question_date": "2010-06-11T11:03:24.460Z", "question_score": 210, "tags": "windows|batch-file|cmd", "answer_id": 3022193, "answer_date": "2010-06-11T11:05:55.107Z", "answer_score": 327 }
Please answer the following Stack Overflow question: Title: Importing variables from another file? <p>How can I import variables from one file to another?</p> <p>example: <code>file1</code> has the variables <code>x1</code> and <code>x2</code> how to pass them to <code>file2</code>?</p> <p>How can I import <strong>all</strong> of the variables from one to another?</p>
<pre><code>from file1 import * </code></pre> <p>will import all objects and methods in file1</p>
{ "question_id": 17255737, "question_date": "2013-06-22T22:04:40.330Z", "question_score": 210, "tags": "python|file|variables|import", "answer_id": 17255770, "answer_date": "2013-06-22T22:09:52.630Z", "answer_score": 220 }
Please answer the following Stack Overflow question: Title: Convert Python program to C/C++ code? <p>is it possible to convert a Python program to C/C++?</p> <p>I need to implement a couple of algorithms, and I'm not sure if the performance gap is big enough to justify all the pain I'd go through when doing it in C/C++ (which I'm not good at). I thought about writing one simple algorithm and benchmark it against such a converted solution. If that alone is significantly faster than the Python version, then I'll have no other choice than doing it in C/C++.</p>
<p>Yes. Look at <a href="http://cython.org/">Cython</a>. It does just that: Converts Python to C for speedups.</p>
{ "question_id": 4650243, "question_date": "2011-01-10T18:46:12.843Z", "question_score": 210, "tags": "c++|python|c|code-generation", "answer_id": 4650280, "answer_date": "2011-01-10T18:49:28.567Z", "answer_score": 146 }
Please answer the following Stack Overflow question: Title: Python json.loads shows ValueError: Extra data <p>I am getting some data from a JSON file &quot;new.json&quot;, and I want to filter some data and store it into a new JSON file. Here is my code:</p> <pre><code>import json with open('new.json') as infile: data = json.load(infile) for item in data: iden = item.get[&quot;id&quot;] a = item.get[&quot;a&quot;] b = item.get[&quot;b&quot;] c = item.get[&quot;c&quot;] if c == 'XYZ' or &quot;XYZ&quot; in data[&quot;text&quot;]: filename = 'abc.json' try: outfile = open(filename,'ab') except: outfile = open(filename,'wb') obj_json={} obj_json[&quot;ID&quot;] = iden obj_json[&quot;VAL_A&quot;] = a obj_json[&quot;VAL_B&quot;] = b </code></pre> <p>And I am getting an error, the traceback is:</p> <pre><code> File &quot;rtfav.py&quot;, line 3, in &lt;module&gt; data = json.load(infile) File &quot;/usr/lib64/python2.7/json/__init__.py&quot;, line 278, in load **kw) File &quot;/usr/lib64/python2.7/json/__init__.py&quot;, line 326, in loads return _default_decoder.decode(s) File &quot;/usr/lib64/python2.7/json/decoder.py&quot;, line 369, in decode raise ValueError(errmsg(&quot;Extra data&quot;, s, end, len(s))) ValueError: Extra data: line 88 column 2 - line 50607 column 2 (char 3077 - 1868399) </code></pre> <p>Here is a sample of the data in new.json, there are about 1500 more such dictionaries in the file</p> <pre><code>{ &quot;contributors&quot;: null, &quot;truncated&quot;: false, &quot;text&quot;: &quot;@HomeShop18 #DreamJob to professional rafter&quot;, &quot;in_reply_to_status_id&quot;: null, &quot;id&quot;: 421584490452893696, &quot;favorite_count&quot;: 0, &quot;source&quot;: &quot;&lt;a href=\&quot;https://mobile.twitter.com\&quot; rel=\&quot;nofollow\&quot;&gt;Mobile Web (M2)&lt;/a&gt;&quot;, &quot;retweeted&quot;: false, &quot;coordinates&quot;: null, &quot;entities&quot;: { &quot;symbols&quot;: [], &quot;user_mentions&quot;: [ { &quot;id&quot;: 183093247, &quot;indices&quot;: [ 0, 11 ], &quot;id_str&quot;: &quot;183093247&quot;, &quot;screen_name&quot;: &quot;HomeShop18&quot;, &quot;name&quot;: &quot;HomeShop18&quot; } ], &quot;hashtags&quot;: [ { &quot;indices&quot;: [ 12, 21 ], &quot;text&quot;: &quot;DreamJob&quot; } ], &quot;urls&quot;: [] }, &quot;in_reply_to_screen_name&quot;: &quot;HomeShop18&quot;, &quot;id_str&quot;: &quot;421584490452893696&quot;, &quot;retweet_count&quot;: 0, &quot;in_reply_to_user_id&quot;: 183093247, &quot;favorited&quot;: false, &quot;user&quot;: { &quot;follow_request_sent&quot;: null, &quot;profile_use_background_image&quot;: true, &quot;default_profile_image&quot;: false, &quot;id&quot;: 2254546045, &quot;verified&quot;: false, &quot;profile_image_url_https&quot;: &quot;https://pbs.twimg.com/profile_images/413952088880594944/rcdr59OY_normal.jpeg&quot;, &quot;profile_sidebar_fill_color&quot;: &quot;171106&quot;, &quot;profile_text_color&quot;: &quot;8A7302&quot;, &quot;followers_count&quot;: 87, &quot;profile_sidebar_border_color&quot;: &quot;BCB302&quot;, &quot;id_str&quot;: &quot;2254546045&quot;, &quot;profile_background_color&quot;: &quot;0F0A02&quot;, &quot;listed_count&quot;: 1, &quot;profile_background_image_url_https&quot;: &quot;https://abs.twimg.com/images/themes/theme1/bg.png&quot;, &quot;utc_offset&quot;: null, &quot;statuses_count&quot;: 9793, &quot;description&quot;: &quot;Rafter. Rafting is what I do. Me aur mera Tablet. Technocrat of Future&quot;, &quot;friends_count&quot;: 231, &quot;location&quot;: &quot;&quot;, &quot;profile_link_color&quot;: &quot;473623&quot;, &quot;profile_image_url&quot;: &quot;http://pbs.twimg.com/profile_images/413952088880594944/rcdr59OY_normal.jpeg&quot;, &quot;following&quot;: null, &quot;geo_enabled&quot;: false, &quot;profile_banner_url&quot;: &quot;https://pbs.twimg.com/profile_banners/2254546045/1388065343&quot;, &quot;profile_background_image_url&quot;: &quot;http://abs.twimg.com/images/themes/theme1/bg.png&quot;, &quot;name&quot;: &quot;Jayy&quot;, &quot;lang&quot;: &quot;en&quot;, &quot;profile_background_tile&quot;: false, &quot;favourites_count&quot;: 41, &quot;screen_name&quot;: &quot;JzayyPsingh&quot;, &quot;notifications&quot;: null, &quot;url&quot;: null, &quot;created_at&quot;: &quot;Fri Dec 20 05:46:00 +0000 2013&quot;, &quot;contributors_enabled&quot;: false, &quot;time_zone&quot;: null, &quot;protected&quot;: false, &quot;default_profile&quot;: false, &quot;is_translator&quot;: false }, &quot;geo&quot;: null, &quot;in_reply_to_user_id_str&quot;: &quot;183093247&quot;, &quot;lang&quot;: &quot;en&quot;, &quot;created_at&quot;: &quot;Fri Jan 10 10:09:09 +0000 2014&quot;, &quot;filter_level&quot;: &quot;medium&quot;, &quot;in_reply_to_status_id_str&quot;: null, &quot;place&quot;: null } </code></pre>
<p>As you can see in the following example, <code>json.loads</code> (and <code>json.load</code>) does not decode multiple json object.</p> <pre><code>&gt;&gt;&gt; json.loads('{}') {} &gt;&gt;&gt; json.loads('{}{}') # == json.loads(json.dumps({}) + json.dumps({})) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Python27\lib\json\__init__.py", line 338, in loads return _default_decoder.decode(s) File "C:\Python27\lib\json\decoder.py", line 368, in decode raise ValueError(errmsg("Extra data", s, end, len(s))) ValueError: Extra data: line 1 column 3 - line 1 column 5 (char 2 - 4) </code></pre> <p>If you want to dump multiple dictionaries, wrap them in a list, dump the list (instead of dumping dictionaries multiple times)</p> <pre><code>&gt;&gt;&gt; dict1 = {} &gt;&gt;&gt; dict2 = {} &gt;&gt;&gt; json.dumps([dict1, dict2]) '[{}, {}]' &gt;&gt;&gt; json.loads(json.dumps([dict1, dict2])) [{}, {}] </code></pre>
{ "question_id": 21058935, "question_date": "2014-01-11T05:36:42.617Z", "question_score": 210, "tags": "python|json", "answer_id": 21058946, "answer_date": "2014-01-11T05:39:19.917Z", "answer_score": 195 }
Please answer the following Stack Overflow question: Title: Convert XML String to Object <p>I am receiving XML strings over a socket, and would like to convert these to C# objects.</p> <p>The messages are of the form:</p> <pre><code>&lt;msg&gt; &lt;id&gt;1&lt;/id&gt; &lt;action&gt;stop&lt;/action&gt; &lt;/msg&gt; </code></pre> <p>How can this be done?</p>
<p>You need to use the <code>xsd.exe</code> tool which gets installed with the Windows SDK into a directory something similar to: </p> <pre><code>C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin </code></pre> <p>And on 64-bit computers:</p> <pre><code>C:\Program Files (x86)\Microsoft SDKs\Windows\v6.0A\bin </code></pre> <p>And on Windows 10 computers:</p> <pre><code>C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin </code></pre> <p>On the first run, you use <code>xsd.exe</code> and you convert your sample XML into a XSD file (XML schema file):</p> <pre><code>xsd yourfile.xml </code></pre> <p>This gives you <code>yourfile.xsd</code>, which in a second step, you can convert again using <code>xsd.exe</code> into a C# class:</p> <pre><code>xsd yourfile.xsd /c </code></pre> <p>This should give you a file <code>yourfile.cs</code> which will contain a C# class that you can use to deserialize the XML file you're getting - something like:</p> <pre><code>XmlSerializer serializer = new XmlSerializer(typeof(msg)); msg resultingMessage = (msg)serializer.Deserialize(new XmlTextReader("yourfile.xml")); </code></pre> <p>Should work pretty well for most cases.</p> <p><strong>Update:</strong> the XML serializer will take any stream as its input - either a file or a memory stream will be fine:</p> <pre><code>XmlSerializer serializer = new XmlSerializer(typeof(msg)); MemoryStream memStream = new MemoryStream(Encoding.UTF8.GetBytes(inputString)); msg resultingMessage = (msg)serializer.Deserialize(memStream); </code></pre> <p>or use a StringReader:</p> <pre><code>XmlSerializer serializer = new XmlSerializer(typeof(msg)); StringReader rdr = new StringReader(inputString); msg resultingMessage = (msg)serializer.Deserialize(rdr); </code></pre>
{ "question_id": 3187444, "question_date": "2010-07-06T15:04:49.827Z", "question_score": 210, "tags": "c#|xml|xml-parsing|xml-serialization", "answer_id": 3187489, "answer_date": "2010-07-06T15:09:03.217Z", "answer_score": 302 }
Please answer the following Stack Overflow question: Title: How to find all positions of the maximum value in a list? <p>I have a list:</p> <pre><code>a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50, 35, 41, 49, 37, 19, 40, 41, 31] </code></pre> <p>max element is 55 (two elements on position 9 and 12)</p> <p>I need to find on which position(s) the maximum value is situated. Please, help.</p>
<pre><code>&gt;&gt;&gt; m = max(a) &gt;&gt;&gt; [i for i, j in enumerate(a) if j == m] [9, 12] </code></pre>
{ "question_id": 3989016, "question_date": "2010-10-21T15:15:25.477Z", "question_score": 210, "tags": "python|list|indexing|max", "answer_id": 3989032, "answer_date": "2010-10-21T15:17:24.707Z", "answer_score": 253 }
Please answer the following Stack Overflow question: Title: PowerShell and the -contains operator <p>Consider the following snippet:</p> <pre><code>&quot;12-18&quot; -Contains &quot;-&quot; </code></pre> <p>You’d think this evaluates to <code>true</code>, but it doesn't. This will evaluate to <code>false</code> instead. I’m not sure why this happens, but it does.</p> <p>To avoid this, you can use this instead:</p> <pre><code>&quot;12-18&quot;.Contains(&quot;-&quot;) </code></pre> <p>Now the expression will evaluate to true.</p> <p>Why does the first code snippet behave like that? Is there something special about <code>-</code> that doesn't play nicely with <code>-Contains</code>? <a href="http://technet.microsoft.com/en-us/library/hh847759.aspx" rel="noreferrer">The documentation</a> doesn't mention anything about it.</p>
<p>The <code>-Contains</code> operator doesn't do substring comparisons and the match must be on a complete string and is used to search collections.</p> <p>From the documentation you linked to:</p> <blockquote> <p>-Contains Description: Containment operator. <strong>Tells whether a collection of reference values includes a single test value.</strong></p> </blockquote> <p>In the example you provided you're working with a collection containing just one string item.</p> <p>If you read the documentation you linked to you'll see an example that demonstrates this behaviour:</p> <p>Examples:</p> <pre><code>PS C:\&gt; "abc", "def" -Contains "def" True PS C:\&gt; "Windows", "PowerShell" -Contains "Shell" False #Not an exact match </code></pre> <p>I think what you want is the <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6#-match" rel="noreferrer"><code>-Match</code></a> operator:</p> <pre><code>"12-18" -Match "-" </code></pre> <p>Which returns <code>True</code>.</p> <p><strong>Important:</strong> As pointed out in the comments and in the <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_comparison_operators?view=powershell-6#-match" rel="noreferrer">linked documentation</a>, it should be noted that the <code>-Match</code> operator uses <a href="https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_regular_expressions?view=powershell-6" rel="noreferrer">regular expressions</a> to perform text matching.</p>
{ "question_id": 18877580, "question_date": "2013-09-18T16:31:11.420Z", "question_score": 210, "tags": "powershell|operators|string-matching", "answer_id": 18877724, "answer_date": "2013-09-18T16:38:32.840Z", "answer_score": 282 }
Please answer the following Stack Overflow question: Title: How can I run an EXE file from my C# code? <p>I have an EXE file reference in my C# project. How do I invoke that EXE file from my code?</p>
<pre><code>using System.Diagnostics; class Program { static void Main() { Process.Start("C:\\"); } } </code></pre> <p>If your application needs cmd arguments, use something like this:</p> <pre><code>using System.Diagnostics; class Program { static void Main() { LaunchCommandLineApp(); } /// &lt;summary&gt; /// Launch the application with some options set. /// &lt;/summary&gt; static void LaunchCommandLineApp() { // For the example const string ex1 = "C:\\"; const string ex2 = "C:\\Dir"; // Use ProcessStartInfo class ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = false; startInfo.UseShellExecute = false; startInfo.FileName = "dcm2jpg.exe"; startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2; try { // Start the process with the info we specified. // Call WaitForExit and then the using statement will close. using (Process exeProcess = Process.Start(startInfo)) { exeProcess.WaitForExit(); } } catch { // Log error. } } } </code></pre>
{ "question_id": 9679375, "question_date": "2012-03-13T06:35:57.360Z", "question_score": 210, "tags": "c#|.net", "answer_id": 9679614, "answer_date": "2012-03-13T07:00:57.840Z", "answer_score": 355 }
Please answer the following Stack Overflow question: Title: Android Left to Right slide animation <p>I have three activities whose launch modes are single instance.<br> Using <code>onfling()</code>, I swing them left and right. </p> <p>The problem is when I swipe right to left the slide transition is okay but when I swipe left to right, I get the transition of swiping right to left. </p> <p>I know why this is happening its because I am always sending new intents. But, now I need to change the animation of sliding left to right. </p> <p>I know there is a method named <code>overridingTransitionPending()</code>, but I do not know how to define my animation in XML.</p>
<p>Use this xml in <code>res/anim/</code></p> <p>This is for left to right animation:</p> <pre><code>&lt;set xmlns:android="http://schemas.android.com/apk/res/android" android:shareInterpolator="false"&gt; &lt;translate android:fromXDelta="-100%" android:toXDelta="0%" android:fromYDelta="0%" android:toYDelta="0%" android:duration="700"/&gt; &lt;/set&gt; </code></pre> <p>This is for right to left animation:</p> <pre><code>&lt;set xmlns:android="http://schemas.android.com/apk/res/android" android:shareInterpolator="false"&gt; &lt;translate android:fromXDelta="0%" android:toXDelta="100%" android:fromYDelta="0%" android:toYDelta="0%" android:duration="700" /&gt; &lt;/set&gt; </code></pre> <p>In your coding use intent like for left to right:</p> <pre><code>this.overridePendingTransition(R.anim.animation_enter, R.anim.animation_leave); </code></pre> <p>In your coding use intent like for right to left</p> <pre><code>this.overridePendingTransition(R.anim.animation_leave, R.anim.animation_enter); </code></pre>
{ "question_id": 5151591, "question_date": "2011-03-01T07:25:33.960Z", "question_score": 210, "tags": "android|animation", "answer_id": 5151774, "answer_date": "2011-03-01T07:50:03.807Z", "answer_score": 436 }
Please answer the following Stack Overflow question: Title: Parse date without timezone javascript <p>I want to parse a date without a timezone in JavaScript. I tried:</p> <pre><code>new Date(Date.parse(&quot;2005-07-08T00:00:00+0000&quot;)); </code></pre> <p>Which returned <code>Fri Jul 08 2005 02:00:00 GMT+0200</code> (Central European Daylight Time):</p> <pre><code>new Date(Date.parse(&quot;2005-07-08 00:00:00 GMT+0000&quot;)); </code></pre> <p>returns the same result and:</p> <pre><code>new Date(Date.parse(&quot;2005-07-08 00:00:00 GMT-0000&quot;)); </code></pre> <p>also returns the same result.</p> <p>I want to parse time:</p> <ol> <li>without time zone.</li> <li>without calling a constructor <code>Date.UTC</code> or new <code>Date(year, month, day)</code>.</li> <li>by simply passing a string into the Date constructor (without prototype approaches).</li> </ol> <p>I have to produce a Date object, not a String.</p>
<p>The date is parsed correctly, it's just <code>toString</code> that converts it to your local timezone:</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>let s = "2005-07-08T11:22:33+0000"; let d = new Date(Date.parse(s)); // this logs for me // "Fri Jul 08 2005 13:22:33 GMT+0200 (Central European Summer Time)" // and something else for you console.log(d.toString()) // this logs // Fri, 08 Jul 2005 11:22:33 GMT // for everyone console.log(d.toUTCString())</code></pre> </div> </div> </p> <p>Javascript Date object are timestamps - they merely contain a number of milliseconds since the epoch. There is no timezone info in a Date object. Which calendar date (day, minutes, seconds) this timestamp represents is a matter of the interpretation (one of <code>to...String</code> methods).</p> <p>The above example shows that the date is being parsed correctly - that is, it actually contains an amount of milliseconds corresponding to &quot;2005-07-08T11:22:33&quot; in GMT.</p>
{ "question_id": 17545708, "question_date": "2013-07-09T10:18:46.540Z", "question_score": 210, "tags": "javascript|date|timestamp-with-timezone", "answer_id": 17545854, "answer_date": "2013-07-09T10:26:26.583Z", "answer_score": 151 }
Please answer the following Stack Overflow question: Title: Store images in a MongoDB database <p>How can I store images in a MongoDB database rather than just text? Can I create an array of images in a MongoDB database? Will it be possible to do the same for videos?</p>
<p>Please see the <a href="http://www.mongodb.org/display/DOCS/GridFS" rel="noreferrer">GridFS</a> docs for details on storing such binary data.</p> <p>Support for your specific language should be linked to at the bottom of the screen.</p>
{ "question_id": 4796914, "question_date": "2011-01-25T17:38:30.287Z", "question_score": 210, "tags": "mongodb|database", "answer_id": 4800186, "answer_date": "2011-01-25T23:54:34.107Z", "answer_score": 134 }
Please answer the following Stack Overflow question: Title: Trigger a keypress/keydown/keyup event in JS/jQuery? <p>What is the best way to simulate a user entering text in a text input box in JS and/or jQuery?</p> <p>I <strong>don't</strong> want to actually put text in the input box, I just want to trigger all the event <strong>handlers</strong> that would normally get triggered by a user typing info into a input box. This means focus, keydown, keypress, keyup, and blur. I think. </p> <p>So how would one accomplish this?</p>
<p>You can trigger any of the events with a direct call to them, like this:</p> <pre><code>$(function() { $('item').keydown(); $('item').keypress(); $('item').keyup(); $('item').blur(); }); </code></pre> <p>Does that do what you're trying to do?</p> <p>You should probably also trigger <code>.focus()</code> and potentially <code>.change()</code></p> <p>If you want to trigger the key-events with specific keys, you can do so like this:</p> <pre><code>$(function() { var e = $.Event('keypress'); e.which = 65; // Character 'A' $('item').trigger(e); }); </code></pre> <p>There is some interesting discussion of the keypress events here: <a href="https://stackoverflow.com/questions/302122/jquery-event-keypress-which-key-was-pressed">jQuery Event Keypress: Which key was pressed?</a>, specifically regarding cross-browser compatability with the .which property.</p>
{ "question_id": 3368578, "question_date": "2010-07-30T03:43:41.993Z", "question_score": 210, "tags": "javascript|jquery|dom-events", "answer_id": 3368599, "answer_date": "2010-07-30T03:51:02.963Z", "answer_score": 265 }
Please answer the following Stack Overflow question: Title: Casting to string in JavaScript <p>I found three ways to cast a variable to <code>String</code> in JavaScript.<br> I searched for those three options in the jQuery source code, and <strong>they are all in use</strong>.<br> I would like to know if there are any differences between them:</p> <pre><code>value.toString() String(value) value + "" </code></pre> <p><strong><a href="http://jsfiddle.net/67NaT/">DEMO</a></strong></p> <p>They all produce the same output, but does one of them better than the others?<br> I would say the <code>+ ""</code> has an advantage that it saves some characters, but that's not that big advantage, anything else? </p>
<p>They do behave differently when the <code>value</code> is <code>null</code>.</p> <ul> <li><code>null.toString()</code> throws an error - <em>Cannot call method 'toString' of null</em></li> <li><code>String(null)</code> returns - <em>"null"</em></li> <li><code>null + ""</code> also returns - <em>"null"</em></li> </ul> <p>Very similar behaviour happens if <code>value</code> is <code>undefined</code> (see <a href="https://stackoverflow.com/a/11083457/369247">jbabey's answer</a>).</p> <p>Other than that, there is a negligible performance difference, which, unless you're using them in huge loops, isn't worth worrying about.</p>
{ "question_id": 11083254, "question_date": "2012-06-18T12:49:13.427Z", "question_score": 210, "tags": "javascript|string", "answer_id": 11083415, "answer_date": "2012-06-18T12:58:31.530Z", "answer_score": 247 }
Please answer the following Stack Overflow question: Title: Is there a replacement for unistd.h for Windows (Visual C)? <p>I'm porting a relatively simple console program written for Unix to the Windows platform (<a href="http://en.wikipedia.org/wiki/Visual_C++#32-bit_versions" rel="noreferrer">Visual C++ 8.0</a>). All the source files include "unistd.h", which doesn't exist. Removing it, I get complaints about misssing prototypes for 'srandom', 'random', and 'getopt'. I know I can replace the random functions, and I'm pretty sure I can find/hack-up a getopt implementation. </p> <p>But I'm sure others have run into the same challenge. My question is: is there a port of "unistd.h" to Windows? At least one containg those functions which do have a native Windows implementation - I don't need pipes or forking.</p> <p><strong>EDIT</strong>:</p> <p>I know I can create my very own "unistd.h" which contains replacements for the things I need - especially in this case, since it is a limited set. But since it seems like a common problem, I was wondering if someone had done the work already for a bigger subset of the functionality.</p> <p>Switching to a different compiler or environment isn't possible at work - I'm stuck with Visual Studio.</p>
<p>Since we can't find a version on the Internet, let's start one here.<br> Most ports to Windows probably only need a subset of the complete Unix file.<br> Here's a starting point. Please add definitions as needed.</p> <pre><code>#ifndef _UNISTD_H #define _UNISTD_H 1 /* This is intended as a drop-in replacement for unistd.h on Windows. * Please add functionality as neeeded. * https://stackoverflow.com/a/826027/1202830 */ #include &lt;stdlib.h&gt; #include &lt;io.h&gt; #include &lt;getopt.h&gt; /* getopt at: https://gist.github.com/ashelly/7776712 */ #include &lt;process.h&gt; /* for getpid() and the exec..() family */ #include &lt;direct.h&gt; /* for _getcwd() and _chdir() */ #define srandom srand #define random rand /* Values for the second argument to access. These may be OR'd together. */ #define R_OK 4 /* Test for read permission. */ #define W_OK 2 /* Test for write permission. */ //#define X_OK 1 /* execute permission - unsupported in windows*/ #define F_OK 0 /* Test for existence. */ #define access _access #define dup2 _dup2 #define execve _execve #define ftruncate _chsize #define unlink _unlink #define fileno _fileno #define getcwd _getcwd #define chdir _chdir #define isatty _isatty #define lseek _lseek /* read, write, and close are NOT being #defined here, because while there are file handle specific versions for Windows, they probably don't work for sockets. You need to look at your app and consider whether to call e.g. closesocket(). */ #ifdef _WIN64 #define ssize_t __int64 #else #define ssize_t long #endif #define STDIN_FILENO 0 #define STDOUT_FILENO 1 #define STDERR_FILENO 2 /* should be in some equivalent to &lt;sys/types.h&gt; */ typedef __int8 int8_t; typedef __int16 int16_t; typedef __int32 int32_t; typedef __int64 int64_t; typedef unsigned __int8 uint8_t; typedef unsigned __int16 uint16_t; typedef unsigned __int32 uint32_t; typedef unsigned __int64 uint64_t; #endif /* unistd.h */ </code></pre>
{ "question_id": 341817, "question_date": "2008-12-04T19:51:08.417Z", "question_score": 210, "tags": "c++|c|windows|portability|unistd.h", "answer_id": 826027, "answer_date": "2009-05-05T17:26:50.873Z", "answer_score": 213 }
Please answer the following Stack Overflow question: Title: Is there a good Valgrind substitute for Windows? <p>I was looking into Valgrind to help improve my C coding/debugging when I discovered it is only for Linux - I have no other need or interest in moving my OS to Linux so I was wondering if there is a equally good program for Windows.</p>
<p>Some more good commercial tools:</p> <ul> <li><a href="http://www-01.ibm.com/software/awdtools/purify/" rel="noreferrer">Purify</a></li> <li><a href="http://www.parasoft.com/jsp/products/home.jsp?product=Insure" rel="noreferrer">Insure++</a></li> </ul>
{ "question_id": 413477, "question_date": "2009-01-05T15:37:39.080Z", "question_score": 210, "tags": "c|windows|debugging|memory-leaks|valgrind", "answer_id": 413842, "answer_date": "2009-01-05T17:19:23.620Z", "answer_score": 29 }
Please answer the following Stack Overflow question: Title: Python extract pattern matches <p>I am trying to use a regular expression to extract words inside of a pattern.</p> <p>I have some string that looks like this</p> <pre class="lang-none prettyprint-override"><code>someline abc someother line name my_user_name is valid some more lines </code></pre> <p>I want to extract the word <code>my_user_name</code>. I do something like</p> <pre><code>import re s = #that big string p = re.compile(&quot;name .* is valid&quot;, re.flags) p.match(s) # this gives me &lt;_sre.SRE_Match object at 0x026B6838&gt; </code></pre> <p>How do I extract <code>my_user_name</code> now?</p>
<p>You need to capture from regex. <code>search</code> for the pattern, if found, retrieve the string using <code>group(index)</code>. Assuming valid checks are performed:</p> <pre><code>&gt;&gt;&gt; p = re.compile(&quot;name (.*) is valid&quot;) &gt;&gt;&gt; result = p.search(s) &gt;&gt;&gt; result &lt;_sre.SRE_Match object at 0x10555e738&gt; &gt;&gt;&gt; result.group(1) # group(1) will return the 1st capture (stuff within the brackets). # group(0) will returned the entire matched text. 'my_user_name' </code></pre>
{ "question_id": 15340582, "question_date": "2013-03-11T14:04:05.137Z", "question_score": 210, "tags": "python|regex", "answer_id": 15340694, "answer_date": "2013-03-11T14:09:16.213Z", "answer_score": 253 }
Please answer the following Stack Overflow question: Title: How to assign the output of a Bash command to a variable? <p>I have a problem putting the content of <code>pwd</code> command into a shell variable that I'll use later. </p> <p>Here is my shell code (the loop doesn't stop):</p> <pre><code>#!/bin/bash pwd= `pwd` until [ $pwd = "/" ] do echo $pwd ls &amp;&amp; cd .. &amp;&amp; ls $pwd= `pwd` done </code></pre> <p>Could you spot my mistake, please?</p>
<p>Try:</p> <pre><code>pwd=`pwd` </code></pre> <p>or</p> <pre><code>pwd=$(pwd) </code></pre> <blockquote> <p>Notice no spaces after the equals sign.</p> </blockquote> <p>Also as Mr. Weiss points out; you don't assign to <code>$pwd</code>, you assign to <code>pwd</code>.</p>
{ "question_id": 2314750, "question_date": "2010-02-22T22:25:31.210Z", "question_score": 210, "tags": "bash|shell", "answer_id": 2314765, "answer_date": "2010-02-22T22:27:15.240Z", "answer_score": 367 }