input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: Application auto build versioning
<p>Is it possible to increment a minor version number automatically each time a Go app is compiled?</p>
<p>I would like to set a version number inside my program, with an autoincrementing section:</p>
<pre><code>$ myapp -version
MyApp version 0.5.132
</code></pre>
<p>Being 0.5 the version number I set, and 132 a value that increments automatically each time the binary is compiled.</p>
<p>Is this possible in Go?</p> | <p>The Go linker (<a href="http://golang.org/cmd/link/" rel="noreferrer">go tool link</a>) has an option to set the value of an uninitialised string variable:</p>
<blockquote>
<pre><code>-X importpath.name=value
Set the value of the string variable in importpath named name to
</code></pre>
</blockquote>
<p>value.
Note that before Go 1.5 this option took two separate arguments.
Now it takes one argument split on the first = sign.</p>
<p>As part of your build process, you could set a version string variable using this. You can pass this through the <code>go</code> tool using <code>-ldflags</code>. For example, given the following source file:</p>
<pre><code>package main
import "fmt"
var xyz string
func main() {
fmt.Println(xyz)
}
</code></pre>
<p>Then:</p>
<pre><code>$ go run -ldflags "-X main.xyz=abc" main.go
abc
</code></pre>
<p>In order to set <code>main.minversion</code> to the build date and time when building:</p>
<pre><code>go build -ldflags "-X main.minversion=`date -u +.%Y%m%d.%H%M%S`" service.go
</code></pre>
<p>If you compile without initializing <code>main.minversion</code> in this way, it will contain the empty string.</p> | {
"question_id": 11354518,
"question_date": "2012-07-06T00:52:00.960Z",
"question_score": 225,
"tags": "go",
"answer_id": 11355611,
"answer_date": "2012-07-06T03:57:34.093Z",
"answer_score": 371
} |
Please answer the following Stack Overflow question:
Title: Difference between \A \z and ^ $ in Ruby regular expressions
<p>In the documentation I read:</p>
<blockquote>
<p>Use \A and \z to match the start and end of the string, ^ and $ match the start/end of a line.</p>
</blockquote>
<p>I am going to apply a regular expression to check username (or e-mail is the same) submitted by user. Which expression should I use with <code>validates_format_of</code> in model? I can't understand the difference: I've always used ^ and $ ...</p> | <p>If you're depending on the regular expression for validation, you always want to use <code>\A</code> and <code>\z</code>. <code>^</code> and <code>$</code> will only match up until a newline character, which means they could use an email like <code>[email protected]\n<script>dangerous_stuff();</script></code> and still have it validate, since the regex only sees everything before the <code>\n</code>.</p>
<p>My recommendation would just be completely stripping new lines from a username or email beforehand, since there's pretty much no legitimate reason for one. Then you can safely use EITHER <code>\A</code> <code>\z</code> or <code>^</code> <code>$</code>.</p> | {
"question_id": 577653,
"question_date": "2009-02-23T13:36:56.980Z",
"question_score": 225,
"tags": "ruby|regex",
"answer_id": 577675,
"answer_date": "2009-02-23T13:43:22.690Z",
"answer_score": 260
} |
Please answer the following Stack Overflow question:
Title: JavaScript variables declare outside or inside loop?
<p>In AS3 I believe you should initialise all variables outside loops for increased performance. Is this the case with JavaScript as well? Which is better / faster / best-practice?</p>
<pre><code>var value = 0;
for (var i = 0; i < 100; i++)
{
value = somearray[i];
}
</code></pre>
<p>or</p>
<pre><code>for (var i = 0 ; i < 100; i++)
{
var value = somearray[i];
}
</code></pre> | <p>There is <strong>absolutely no difference</strong> in meaning or performance, in JavaScript or ActionScript.</p>
<p><code>var</code> is a directive for the parser, and <em>not</em> a command executed at run-time. If a particular identifier has been declared <code>var</code> once or more anywhere in a function body(*), then all use of that identifier in the block will be referring to the local variable. It makes no difference whether <code>value</code> is declared to be <code>var</code> inside the loop, outside the loop, or both.</p>
<p>Consequently you should write whichever you find most readable. I disagree with Crockford that putting all the vars at the top of a function is always the best thing. For the case where a variable is used temporarily in a section of code, it's better to declare <code>var</code> in that section, so the section stands alone and can be copy-pasted. Otherwise, copy-paste a few lines of code to a new function during refactoring, without separately picking out and moving the associated <code>var</code>, and you've got yourself an accidental global.</p>
<p>In particular:</p>
<pre><code>for (var i; i<100; i++)
do something;
for (var i; i<100; i++)
do something else;
</code></pre>
<p>Crockford will recommend you remove the second <code>var</code> (or remove both <code>var</code>s and do <code>var i;</code> above), and jslint will whinge at you for this. But IMO it's more maintainable to keep both <code>var</code>s, keeping all the related code together, instead of having an extra, easily-forgotten bit of code at the top of the function.</p>
<p>Personally I tend to declare as <code>var</code> the first assignment of a variable in an independent section of code, whether or not there's another separate usage of the same variable name in some other part of the same function. For me, having to declare <code>var</code> at all is an undesirable JS wart (it would have been better to have variables default to local); I don't see it as my duty to duplicate the limitations of [an old revision of] ANSI C in JavaScript as well.</p>
<p>(*: other than in nested function bodies)</p> | {
"question_id": 3684923,
"question_date": "2010-09-10T13:25:53.527Z",
"question_score": 225,
"tags": "javascript|performance",
"answer_id": 3685090,
"answer_date": "2010-09-10T13:48:29.890Z",
"answer_score": 299
} |
Please answer the following Stack Overflow question:
Title: What is the difference D3 datum vs. data?
<p>Can someone please explain the difference between datum() and data() in D3.js? I see both being used and I am not sure why you should choose one over the other?</p> | <p>I found the correct answer here from Mike himself:</p>
<p><a href="https://stackoverflow.com/questions/10086167/d3-how-to-deal-with-json-data-structures">D3 - how to deal with JSON data structures?</a></p>
<p>If you want to bind your data to a single SVG element, use </p>
<pre><code>(...).data([data])
</code></pre>
<p>or</p>
<pre><code>(...).datum(data)
</code></pre>
<p>If you want to bind your data to multiple SVG elements</p>
<pre><code>(...).data(data).enter().append("svg")
</code></pre>
<p>.....</p> | {
"question_id": 13728402,
"question_date": "2012-12-05T16:57:25.907Z",
"question_score": 225,
"tags": "javascript|d3.js",
"answer_id": 13730996,
"answer_date": "2012-12-05T19:33:08.817Z",
"answer_score": 183
} |
Please answer the following Stack Overflow question:
Title: Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and <null>
<p>Why does this not compile?</p>
<pre><code>int? number = true ? 5 : null;
</code></pre>
<blockquote>
<p>Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and <null></p>
</blockquote> | <p>The spec (§7.14) says that for conditional expression <code>b ? x : y</code>, there are three possibilities, either <code>x</code> and <code>y</code> both have a type <em>and</em> certain <em>good conditions</em> are met, only one of <code>x</code> and <code>y</code> has a type <em>and</em> certain <em>good conditions</em> are met, or a compile-time error occurs. Here, "certain good conditions" means certain conversions are possible, which we will get into the details of below.</p>
<p>Now, let's turn to the germane part of the spec:</p>
<blockquote>
<p>If only one of <code>x</code> and <code>y</code> has a type, and both <code>x</code> and <code>y</code> are implicitly convertible to that type, then that is the type of the conditional expression.</p>
</blockquote>
<p>The issue here is that in</p>
<pre><code>int? number = true ? 5 : null;
</code></pre>
<p>only one of the conditional results has a type. Here <code>x</code> is an <code>int</code> literal, and <code>y</code> is <code>null</code> which does <em>not</em> have a type <strong>and <code>null</code> is not implicitly convertible to an <code>int</code></strong><sup>1</sup>. Therefore, "certain good conditions" aren't met, and a compile-time error occurs.</p>
<p>There <em>are</em> two ways around this:</p>
<pre><code>int? number = true ? (int?)5 : null;
</code></pre>
<p>Here we are still in the case where only one of <code>x</code> and <code>y</code> has a type. Note that <code>null</code> <em>still</em> does not have a type yet the compiler won't have any problem with this because <code>(int?)5</code> and <code>null</code> are both implicitly convertible to <code>int?</code> (§6.1.4 and §6.1.5).</p>
<p>The other way is obviously:</p>
<pre><code>int? number = true ? 5 : (int?)null;
</code></pre>
<p>but now we have to read a <em>different</em> clause in the spec to understand why this is okay:</p>
<blockquote>
<p>If <code>x</code> has type <code>X</code> and <code>y</code> has type <code>Y</code> then</p>
<ul>
<li><p>If an implicit conversion (§6.1) exists from <code>X</code> to <code>Y</code>, but not from <code>Y</code> to <code>X</code>, then <code>Y</code> is the type of the conditional expression.</p>
</li>
<li><p>If an implicit conversion (§6.1) exists from <code>Y</code> to <code>X</code>, but not from <code>X</code> to <code>Y</code>, then <code>X</code> is the type of the conditional expression.</p>
</li>
<li><p>Otherwise, no expression type can be determined, and a compile-time error occurs.</p>
</li>
</ul>
</blockquote>
<p>Here <code>x</code> is of type <code>int</code> and <code>y</code> is of type <code>int?</code>. There is no implicit conversion from <code>int?</code> to <code>int</code>, but there is an implicit conversion from <code>int</code> to <code>int?</code> so the type of the expression is <code>int?</code>.</p>
<p><sup>1</sup>: Note further that the type of the left-hand side is ignored in determining the type of the conditional expression, a common source of confusion here.</p> | {
"question_id": 18260528,
"question_date": "2013-08-15T19:45:06.743Z",
"question_score": 225,
"tags": "c#|nullable",
"answer_id": 18260915,
"answer_date": "2013-08-15T20:10:31.273Z",
"answer_score": 428
} |
Please answer the following Stack Overflow question:
Title: mmap() vs. reading blocks
<p>I'm working on a program that will be processing files that could potentially be 100GB or more in size. The files contain sets of variable length records. I've got a first implementation up and running and am now looking towards improving performance, particularly at doing I/O more efficiently since the input file gets scanned many times.</p>
<p>Is there a rule of thumb for using <code>mmap()</code> versus reading in blocks via C++'s <code>fstream</code> library? What I'd like to do is read large blocks from disk into a buffer, process complete records from the buffer, and then read more.</p>
<p>The <code>mmap()</code> code could potentially get very messy since <code>mmap</code>'d blocks need to lie on page sized boundaries (my understanding) and records could potentially lie across page boundaries. With <code>fstream</code>s, I can just seek to the start of a record and begin reading again, since we're not limited to reading blocks that lie on page sized boundaries.</p>
<p>How can I decide between these two options without actually writing up a complete implementation first? Any rules of thumb (e.g., <code>mmap()</code> is 2x faster) or simple tests?</p> | <p>I was trying to find the final word on mmap / read performance on Linux and I came across a nice post (<a href="http://marc.info/?l=linux-kernel&m=95496636207616&w=2" rel="noreferrer">link</a>) on the Linux kernel mailing list. It's from 2000, so there have been many improvements to IO and virtual memory in the kernel since then, but it nicely explains the reason why <code>mmap</code> or <code>read</code> might be faster or slower.</p>
<ul>
<li>A call to <code>mmap</code> has more overhead than <code>read</code> (just like <code>epoll</code> has more overhead than <code>poll</code>, which has more overhead than <code>read</code>). Changing virtual memory mappings is a quite expensive operation on some processors for the same reasons that switching between different processes is expensive.</li>
<li>The IO system can already use the disk cache, so if you read a file, you'll hit the cache or miss it no matter what method you use.</li>
</ul>
<p>However,</p>
<ul>
<li>Memory maps are generally faster for random access, especially if your access patterns are sparse and unpredictable.</li>
<li>Memory maps allow you to <em>keep</em> using pages from the cache until you are done. This means that if you use a file heavily for a long period of time, then close it and reopen it, the pages will still be cached. With <code>read</code>, your file may have been flushed from the cache ages ago. This does not apply if you use a file and immediately discard it. (If you try to <code>mlock</code> pages just to keep them in cache, you are trying to outsmart the disk cache and this kind of foolery rarely helps system performance).</li>
<li>Reading a file directly is very simple and fast.</li>
</ul>
<p>The discussion of mmap/read reminds me of two other performance discussions:</p>
<ul>
<li><p>Some Java programmers were shocked to discover that nonblocking I/O is often slower than blocking I/O, which made perfect sense if you know that nonblocking I/O requires making more syscalls.</p></li>
<li><p>Some other network programmers were shocked to learn that <code>epoll</code> is often slower than <code>poll</code>, which makes perfect sense if you know that managing <code>epoll</code> requires making more syscalls.</p></li>
</ul>
<p><strong>Conclusion:</strong> Use memory maps if you access data randomly, keep it around for a long time, or if you know you can share it with other processes (<code>MAP_SHARED</code> isn't very interesting if there is no actual sharing). Read files normally if you access data sequentially or discard it after reading. And if either method makes your program less complex, do <em>that</em>. For many real world cases there's no sure way to show one is faster without testing your actual application and NOT a benchmark.</p>
<p>(Sorry for necro'ing this question, but I was looking for an answer and this question kept coming up at the top of Google results.)</p> | {
"question_id": 45972,
"question_date": "2008-09-05T14:52:14.710Z",
"question_score": 225,
"tags": "c++|file-io|fstream|mmap",
"answer_id": 6383253,
"answer_date": "2011-06-17T08:33:01.077Z",
"answer_score": 250
} |
Please answer the following Stack Overflow question:
Title: How to set up a git project to use an external repo submodule?
<p>I'd like to create a repo which pulls in a remote repo.</p>
<p>For example, let's say jQuery as a submodule:</p>
<pre><code>git://github.com/jquery/jquery.git
</code></pre>
<p>What would be the process of creating a repo with jQuery as a submodule and adding my own external as a remote repo.</p>
<p>Also once this is setup, if I push / pull to my own remote, will the external remain intact?</p> | <ol>
<li>You have a project -- call it <strong>MyWebApp</strong> that already has a github repo</li>
<li>You want to use the <strong>jquery repository</strong> in your project</li>
<li>You want to pull the jquery repo into your project as a <strong>submodule</strong>.</li>
</ol>
<p>Submodules are really, really easy to reference and use. Assuming you already have MyWebApp set up as a repo, from terminal issue these commands:</p>
<pre><code>cd MyWebApp
git submodule add git://github.com/jquery/jquery.git externals/jquery
</code></pre>
<p>This will create a directory named <code>externals/jquery</code>* and link it to the github jquery repository. Now we just need to init the submodule and clone the code to it: </p>
<pre><code>git submodule update --init --recursive
</code></pre>
<p>You should now have all the latest code cloned into the submodule. If the jquery repo changes and you want to pull the latest code down, just issue the <code>submodule update</code> command again. Please note: I typically have a number of external repositories in my projects, so I always group the repos under an "externals" directory.</p>
<p>The online <a href="http://www.git-scm.com/book/en/Git-Tools-Submodules">Pro Git Book</a> has some good information on submodules (and git in general) presented in an easy-to-read fashion. Alternately, <code>git help submodule</code> will also give good information. Or take a look at the <a href="https://git.wiki.kernel.org/index.php/GitSubmoduleTutorial">Git Submodule Tutorial</a> on the git wiki.</p>
<p>I noticed this blog entry which talks about submodules and compares them to Subversion's svn:externals mechanism: <a href="http://speirs.org/blog/2009/5/11/understanding-git-submodules.html">http://speirs.org/blog/2009/5/11/understanding-git-submodules.html</a> </p>
<p><sub>* As a best practice, you should always place your submodules in their own directory, such as Externals. If you don't, your root project directory can become very cluttered very fast.</sub></p> | {
"question_id": 2140985,
"question_date": "2010-01-26T16:53:30.720Z",
"question_score": 225,
"tags": "git|github|external|git-submodules",
"answer_id": 5205785,
"answer_date": "2011-03-05T18:17:12.373Z",
"answer_score": 362
} |
Please answer the following Stack Overflow question:
Title: Does C# 8 support the .NET Framework?
<p>In Visual Studio 2019 Advanced Build settings, C# 8 does not appear to be available for a .NET Framework project, only (as in the picture below) for a .NET Core 3.0 project:</p>
<p><a href="https://i.stack.imgur.com/3P2rH.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3P2rH.png" alt="enter image description here"></a></p>
<p>Does C# 8 support the .NET Framework?</p> | <p><strong>Yes, C# 8 can be used with the .NET Framework</strong> and other targets older than .NET Core 3.0/.NET Standard 2.1 in Visual Studio 2019 (or older versions of Visual Studio if you <a href="https://stackoverflow.com/a/58190585/397817">install a NuGet package</a>).</p>
<p>The only thing required is to set language version to <code>8.0</code> in the csproj file. You can also do this in <a href="https://docs.microsoft.com/en-us/visualstudio/msbuild/customize-your-build?view=vs-2019#directorybuildprops-and-directorybuildtargets" rel="noreferrer">Directory.Build.props</a> to apply it to all projects in your solution. Read below for how to do this in Visual Studio 2019, version 16.3 and newer.</p>
<p>Most - but not all - features are available whichever framework is targeted.</p>
<hr />
<h2>Features that work</h2>
<p>The following features are syntax changes only; they work regardless of framework:</p>
<ul>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#static-local-functions" rel="noreferrer">Static local functions</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#using-declarations" rel="noreferrer">Using declarations</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#null-coalescing-assignment" rel="noreferrer">Null-coalescing assignment</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#readonly-members" rel="noreferrer">Readonly members</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#disposable-ref-structs" rel="noreferrer">Disposable ref structs</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#positional-patterns" rel="noreferrer">Positional patterns</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#tuple-patterns" rel="noreferrer">Tuple patterns</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#switch-expressions" rel="noreferrer">Switch expressions</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#nullable-reference-types" rel="noreferrer">Nullable reference types</a> are also supported, but the new <a href="http://docs.microsoft.com/en-us/dotnet/csharp/nullable-attributes" rel="noreferrer">nullable attributes</a> required to design the more complex nullable use cases are not. I cover this in more detail further down in the "gory details" section.</li>
</ul>
<h2>Features that can be made to work</h2>
<p>These require new types which are not in the .NET Framework. They can only be used in conjunction with "polyfill" NuGet packages or code files:</p>
<ul>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#asynchronous-streams" rel="noreferrer">Asynchronous streams</a> - <a href="https://www.nuget.org/packages/Microsoft.Bcl.AsyncInterfaces/" rel="noreferrer">Microsoft.Bcl.AsyncInterfaces</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#indices-and-ranges" rel="noreferrer">Indices and ranges</a></li>
</ul>
<h2>Default interface members - do not, cannot, and never will work</h2>
<p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8#default-interface-methods" rel="noreferrer">Default interface members</a> won't compile under .NET Framework and will never work because they require runtime changes in the CLR. The .NET CLR is now frozen as .NET Core is now the way forward.</p>
<p><em>For more information on what does and doesn't work, and on possible polyfills, see Stuart Lang's article, <a href="https://stu.dev/csharp8-doing-unsupported-things/" rel="noreferrer">C# 8.0 and .NET Standard 2.0 - Doing Unsupported Things</a>.</em></p>
<hr />
<h2>Code</h2>
<p>The following C# project targetting .NET Framework 4.8 and using C# 8 nullable reference types compiles in Visual Studio 16.2.0. I created it by choosing the .NET Standard Class Library template and then editing it to target .NET Framework instead:</p>
<p>.csproj:</p>
<pre><code><Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net48</TargetFrameworks>
<LangVersion>8.0</LangVersion>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
</code></pre>
<p>.cs:</p>
<pre><code>namespace ClassLibrary1
{
public class Class1
{
public string? NullableString { get; set; }
}
}
</code></pre>
<p>I then tried a .NET Framework 4.5.2 WinForms project, using a legacy <code>.csproj</code> format, and added the same nullable reference type property. I changed the language type in the Visual Studio Advanced Build settings dialog (disabled in 16.3) to <code>latest</code> and saved the project. Of course as this point it doesn't build. I opened the project file in a text editor and changed <code>latest</code> to <code>preview</code> in the build configuration <code>PropertyGroup</code>:</p>
<pre><code><PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<LangVersion>preview</LangVersion>
</code></pre>
<p>I then enabled support for nullable reference types by adding <code><Nullable>enable</Nullable></code> to the main <code>PropertyGroup</code>:</p>
<pre><code><PropertyGroup>
<Nullable>enable</Nullable>
</code></pre>
<p>I reloaded the project, and it builds.</p>
<hr />
<h2>Visual Studio 2019</h2>
<p>There has been a major change in the RTM version of Visual Studio 2019 version 16.3, the launch version for C# 8.0: the language selection dropdown has been disabled:</p>
<p><a href="https://i.stack.imgur.com/nAJfn.png" rel="noreferrer"><img src="https://i.stack.imgur.com/nAJfn.png" alt="enter image description here" /></a></p>
<p>Microsoft's <a href="https://github.com/dotnet/project-system/pull/4923/commits/fc1f7f691851670909ed38fdfc3b4a4ac79c5e4b" rel="noreferrer">rationale</a> for this is:</p>
<blockquote>
<p>Moving forward, ... each version of each framework will have a single
supported and default version, and we won't support arbitrary
versions. To reflect this change in support, this commit permanently
disables the language version combo box and adds a link to a document
explaining the change.</p>
</blockquote>
<p>The document which opens is <a href="https://docs.microsoft.com/en-gb/dotnet/csharp/language-reference/configure-language-version" rel="noreferrer">C# language versioning</a>. This lists C# 8.0 as the default language for .NET Core 3.x ONLY. It also confirms that <strong>each version of each framework will, going forward, have a single supported and default version</strong> and that the framework-agnosticism of the language can no longer be relied on.</p>
<p>The language version can still be forced to 8 for .NET Framework projects by editing the .csproj file.</p>
<hr />
<h2>The gory details</h2>
<p><em><strong>When this answer was first written, C# 8 was in preview and a lot of detective work was involved. I leave that information here for posterity. Feel free to skip it if you don't need to know all the gory details.</strong></em></p>
<p>The C# language has historically been <a href="https://stackoverflow.com/questions/247621/what-are-the-correct-version-numbers-for-c#comment54106872_247623">mostly framework neutral</a> - i.e. able to compile older versions of the Framework - although some features have required new types or CLR support.</p>
<p>Most C# enthusiasts will have read the blog entry <a href="https://devblogs.microsoft.com/dotnet/building-c-8-0/" rel="noreferrer">Building C# 8.0</a> by Mads Torgersen, which explains that certain features of C# 8 have platform dependencies:</p>
<blockquote>
<p>Async streams, indexers and ranges all rely on new framework types
that will be part of .NET Standard 2.1... .NET Core 3.0 as well as
Xamarin, Unity and Mono will all implement .NET Standard 2.1, but .NET
Framework 4.8 will not. This means that the types required to use
these features won’t be available on .NET Framework 4.8.</p>
</blockquote>
<p>This looks a bit like <a href="https://blogs.msdn.microsoft.com/mazhou/2017/05/26/c-7-series-part-1-value-tuples/" rel="noreferrer">Value Tuples</a> which were introduced in C# 7. That feature required new types - the <code>ValueTuple</code> structures - which were not available in NET Framework versions below 4.7 or .NET Standard older than 2.0. <strong>However</strong>, C# 7 could still be used in older versions of .NET, either without value tuples or with them by installing the <a href="https://www.nuget.org/packages/System.ValueTuple/" rel="noreferrer">System.ValueTuple Nuget package</a>. Visual Studio understood this, and all was fine with the world.</p>
<p>However, Mads also wrote:</p>
<blockquote>
<p>For this reason, using C# 8.0 is only supported on platforms that implement .NET Standard 2.1.</p>
</blockquote>
<p>...which if true would have ruled out using C# 8 with <em>any</em> version of the .NET Framework, and indeed even in .NET Standard 2.0 libraries which only recently we were encouraged to use as a baseline target for library code. You wouldn't even be able to use it with .NET Core versions older than 3.0 as they too only support .NET Standard 2.0.</p>
<p>The investigation was on! -</p>
<ul>
<li><p>Jon Skeet has an alpha version of Noda-Time using C# 8 <a href="https://github.com/nodatime/nodatime/blob/master/src/NodaTime/NodaTime.csproj" rel="noreferrer">ready to go</a> which targets .NET Standard 2.0 only. He is clearly expecting C# 8/.NET Standard 2.0 to support all frameworks in the .NET family. (See also Jon's blog post <a href="https://codeblog.jonskeet.uk/2018/04/21/first-steps-with-nullable-reference-types/" rel="noreferrer">"First steps with nullable reference types"</a>).</p>
</li>
<li><p>Microsoft employees have been discussing the Visual Studio UI for C# 8 nullable reference types <a href="https://github.com/dotnet/project-system/issues/4058" rel="noreferrer">on GitHub</a>, and it is stated that they intend to support the legacy <code>csproj</code> (pre-.NET Core SDK format <code>csproj</code>). This is a very strong indication that C# 8 will be usable with the .NET Framework. [I suspect they will backtrack on this now that the Visual Studio 2019 language version dropdown has been disabled and .NET has been tied to C# 7.3]</p>
</li>
<li><p>Shortly after the famous blog post, a <a href="https://github.com/dotnet/csharplang/issues/2002" rel="noreferrer">GitHub thread</a> discussed cross-platform support. An important point which emerged was that <a href="https://github.com/dotnet/standard/pull/1019" rel="noreferrer">.NET Standard 2.1 will include a marker that denotes that default implementations of interfaces is supported</a> - the feature requires a CLR change that will never be available to the .NET Framework. Here's the important bit, from Immo Landwerth, Program Manager on the .NET team at Microsoft:</p>
</li>
</ul>
<blockquote>
<p>Compilers (such as C#) are expected to use the presence of this field to decide whether or not to allow default interface implementations. If the field is present, the runtime is expected to be able to load & execute the resulting code.</p>
</blockquote>
<ul>
<li>This all pointed to "C# 8.0 is only supported on platforms that implement .NET Standard 2.1" being an oversimplification, and that C# 8 will support the .NET Framework but, as there is so much uncertainty, I <a href="https://github.com/dotnet/csharplang/issues/2651" rel="noreferrer">asked on GitHub</a> and HaloFour answered:</li>
</ul>
<blockquote>
<p>IIRC, the only feature that definitely won't appear on .NET Framework is DIM (default interface methods) as that requires runtime changes. The other features are driven by the shape of classes that might never be added to the .NET Framework but can be polyfilled through your own code or NuGet (ranges, indexes, async iterators, async disposal).</p>
</blockquote>
<ul>
<li><p><a href="https://stackoverflow.com/users/1949956/victor-derks">Victor Derks</a> commented that "The <a href="http://docs.microsoft.com/en-us/dotnet/csharp/nullable-attributes" rel="noreferrer">new nullable attributes</a> required to design the more complex nullable use cases are only available in System.Runtime.dll that ships with .NET Core 3.0 and .NET Standard 2.1... [and] incompatible with .NET Framework 4.8"</p>
</li>
<li><p>However, Immo Landwerth <a href="https://devblogs.microsoft.com/dotnet/try-out-nullable-reference-types/#comments-2653" rel="noreferrer">commented</a> that "The vast majority of our APIs didn't need any custom attributes as the types are either fully generic or not-null" under the article <a href="https://devblogs.microsoft.com/dotnet/try-out-nullable-reference-types/" rel="noreferrer">Try out Nullable Reference Types</a></p>
</li>
<li><p><a href="https://stackoverflow.com/users/6870582/ben-hall">Ben Hall</a> raised the issue <a href="https://github.com/dotnet/corefx/issues/40039" rel="noreferrer">Availability of nullable attributes outside of Core 3.0</a> on GitHub, with the following comments from Microsoft employees being of note:</p>
</li>
</ul>
<blockquote>
<p>C# 8 will be fully supported on .net core 3.0 and .net standard 2.1 only.
If you manually edit the project file to use C# 8 with .net core 2.1,
you are in unsupported territory. Some C# 8 features will happen to
work well, some C# 8 features will work not too well (e.g. poor
performance), some C# 8 features will work with extra hacks, and some
C# 8 features will not work at all. Very complex to explain. We do not
actively block it so the expert users who can navigate through it can
do so. I would not recommend this unsupported mix&match to be used
broadly.</p>
</blockquote>
<p>(Jan Kotas)</p>
<blockquote>
<p>People like you who are willing understand -- and work around them --
are free to use C# 8. The point is, not all language features will work
on down-level targets.</p>
</blockquote>
<p>(Immo Landwerth)</p>
<hr />
<h2>Caveat emptor</h2>
<p>The C# 8/.NET Framework combination is not officially supported by Microsoft. It is, they say, for experts only.</p> | {
"question_id": 56651472,
"question_date": "2019-06-18T14:31:05.273Z",
"question_score": 225,
"tags": "c#|.net|visual-studio|.net-standard|c#-8.0",
"answer_id": 57020770,
"answer_date": "2019-07-13T16:06:30.667Z",
"answer_score": 430
} |
Please answer the following Stack Overflow question:
Title: What does the "-U" option stand for in pip install -U
<p>Despite a ton of Googling, I can't find any docs for pip's command line options/arguments. What does <code>pip install -U</code> mean? Does anyone have a link to a list of pip's options and arguments?</p> | <p>Type <code>pip install -h</code> to list help:</p>
<blockquote>
<p>-U, --upgrade Upgrade all packages to the newest available version</p>
</blockquote>
<p>So, if you already <em>have</em> a package installed, it will upgrade the package for you. Without the -U switch it'll tell you the package is already installed and exit.</p>
<p>Each <code>pip</code> subcommand has its own help listing. <code>pip -h</code> shows you overall help, and <code>pip [subcommand] -h</code> gives you help for that sub command, such as <code>install</code>.</p>
<p>You can also find the <a href="https://pip.pypa.io/en/stable/reference/" rel="noreferrer">full reference documentation online</a>; the <a href="https://pip.pypa.io/en/stable/reference/pip/#general-options" rel="noreferrer"><em>General Options</em> section</a> covers switches available for every <code>pip</code> subcommand, while each subcommand has a separate <em>Options</em> section to cover subcommand-specific switches; see the <a href="https://pip.pypa.io/en/stable/reference/pip_install/#options" rel="noreferrer"><em><code>pip install</code> options</em> section</a>, for example.</p> | {
"question_id": 12435209,
"question_date": "2012-09-15T06:48:54.953Z",
"question_score": 225,
"tags": "python|command-line|pip",
"answer_id": 12435220,
"answer_date": "2012-09-15T06:50:25.240Z",
"answer_score": 258
} |
Please answer the following Stack Overflow question:
Title: "pip install --editable ./" vs "python setup.py develop"
<p>Is there any significant difference between</p>
<pre><code>pip install -e /path/to/mypackage
</code></pre>
<p>and the setuptools variant?</p>
<pre><code>python /path/to/mypackage/setup.py develop
</code></pre> | <p>Try to avoid calling <code>setup.py</code> directly, it will not properly tell pip that you've installed your package.</p>
<p>With <code>pip install -e</code>:</p>
<blockquote>
<p>For local projects, the “SomeProject.egg-info” directory is created
relative to the project path. This is one advantage over just using
<code>setup.py develop</code>, which creates the “egg-info” directly relative the
current working directory.</p>
</blockquote>
<p>More: <a href="https://pip.pypa.io/en/latest/cli/pip_install/#editable-installs" rel="noreferrer">docs</a></p>
<p>Also read the setuptools' <a href="http://setuptools.readthedocs.io/en/latest/setuptools.html?highlight=development%20mode#development-mode" rel="noreferrer">docs</a>.</p> | {
"question_id": 30306099,
"question_date": "2015-05-18T14:37:47.587Z",
"question_score": 225,
"tags": "python|pip|setuptools|python-packaging",
"answer_id": 30306403,
"answer_date": "2015-05-18T14:51:04.883Z",
"answer_score": 175
} |
Please answer the following Stack Overflow question:
Title: Forward an invocation of a variadic function in C
<p>In C, is it possible to forward the invocation of a variadic function? As in,</p>
<pre><code>int my_printf(char *fmt, ...) {
fprintf(stderr, "Calling printf with fmt %s", fmt);
return SOMEHOW_INVOKE_LIBC_PRINTF;
}
</code></pre>
<p>Forwarding the invocation in the manner above obviously isn't strictly necessary in this case (since you could log invocations in other ways, or use vfprintf), but the codebase I'm working on requires the wrapper to do some actual work, and doesn't have (and can't have added) a helper function akin to vfprintf.</p>
<p>[Update: there seems to be some confusion based on the answers that have been supplied so far. To phrase the question another way: in general, can you wrap some arbitrary variadic function <i>without modifying that function's definition</i>.]</p> | <p>If you don't have a function analogous to <code>vfprintf</code> that takes a <code>va_list</code> instead of a variable number of arguments, <strong>you can't do it</strong>. See <a href="http://c-faq.com/varargs/handoff.html" rel="noreferrer"><a href="http://c-faq.com/varargs/handoff.html" rel="noreferrer">http://c-faq.com/varargs/handoff.html</a></a>.</p>
<p>Example:</p>
<pre class="lang-c prettyprint-override"><code>void myfun(const char *fmt, va_list argp) {
vfprintf(stderr, fmt, argp);
}
</code></pre> | {
"question_id": 150543,
"question_date": "2008-09-29T20:41:15.087Z",
"question_score": 225,
"tags": "c|variadic",
"answer_id": 150616,
"answer_date": "2008-09-29T20:56:19Z",
"answer_score": 172
} |
Please answer the following Stack Overflow question:
Title: Difference between Control Template and DataTemplate in WPF
<p>What is difference between a <code>ControlTemplate</code> and a <code>DataTemplate</code> in WPF?</p> | <p>Typically a control is rendered for its own sake, and doesn't reflect underlying data. For example, a <code>Button</code> wouldn't be bound to a business object - it's there purely so it can be clicked on. A <code>ContentControl</code> or <code>ListBox</code>, however, generally appear so that they can present data for the user.</p>
<p>A <code>DataTemplate</code>, therefore, is used to provide visual structure for underlying data, while a <code>ControlTemplate</code> has nothing to do with underlying data and simply provides visual layout for the control itself.</p>
<p>A <code>ControlTemplate</code> will generally only contain <code>TemplateBinding</code> expressions, binding back to the properties on the control itself, while a <code>DataTemplate</code> will contain standard Binding expressions, binding to the properties of its <code>DataContext</code> (the business/domain object or view model).</p> | {
"question_id": 1340108,
"question_date": "2009-08-27T10:14:12.490Z",
"question_score": 225,
"tags": "wpf|datatemplate|controltemplate",
"answer_id": 1340138,
"answer_date": "2009-08-27T10:20:18.967Z",
"answer_score": 296
} |
Please answer the following Stack Overflow question:
Title: make_unique and perfect forwarding
<p>Why is there no <code>std::make_unique</code> function template in the standard C++11 library? I find</p>
<pre><code>std::unique_ptr<SomeUserDefinedType> p(new SomeUserDefinedType(1, 2, 3));
</code></pre>
<p>a bit verbose. Wouldn't the following be much nicer?</p>
<pre><code>auto p = std::make_unique<SomeUserDefinedType>(1, 2, 3);
</code></pre>
<p>This hides the <code>new</code> nicely and only mentions the type once.</p>
<p>Anyway, here is my attempt at an implementation of <code>make_unique</code>:</p>
<pre><code>template<typename T, typename... Args>
std::unique_ptr<T> make_unique(Args&&... args)
{
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
}
</code></pre>
<p>It took me quite a while to get the <code>std::forward</code> stuff to compile, but I'm not sure if it's correct. Is it? What exactly does <code>std::forward<Args>(args)...</code> mean? What does the compiler make of that?</p> | <p>Herb Sutter, chair of the C++ standardization committee, writes on his <a href="http://herbsutter.com/gotw/_102/">blog</a>:</p>
<blockquote>
<p>That C++11 doesn’t include <code>make_unique</code> is partly an oversight, and it will almost certainly be added in the future.</p>
</blockquote>
<p>He also gives an implementation that is identical with the one given by the OP.</p>
<p><strong>Edit:</strong> <code>std::make_unique</code> now is part of <a href="http://en.wikipedia.org/wiki/C++14#Smaller_library_features">C++14</a>.</p> | {
"question_id": 7038357,
"question_date": "2011-08-12T09:46:23.310Z",
"question_score": 225,
"tags": "c++|c++11|variadic-templates|unique-ptr|perfect-forwarding",
"answer_id": 9657991,
"answer_date": "2012-03-11T19:06:52.470Z",
"answer_score": 160
} |
Please answer the following Stack Overflow question:
Title: Python __str__ versus __unicode__
<p>Is there a python convention for when you should implement <code>__str__()</code> versus <code>__unicode__()</code>. I've seen classes override <code>__unicode__()</code> more frequently than <code>__str__()</code> but it doesn't appear to be consistent. Are there specific rules when it is better to implement one versus the other? Is it necessary/good practice to implement both?</p> | <p><code>__str__()</code> is the old method -- it returns bytes. <code>__unicode__()</code> is the new, preferred method -- it returns characters. The names are a bit confusing, but in 2.x we're stuck with them for compatibility reasons. Generally, you should put all your string formatting in <code>__unicode__()</code>, and create a stub <code>__str__()</code> method:</p>
<pre><code>def __str__(self):
return unicode(self).encode('utf-8')
</code></pre>
<p>In 3.0, <code>str</code> contains characters, so the same methods are named <code>__bytes__()</code> and <code>__str__()</code>. These behave as expected.</p> | {
"question_id": 1307014,
"question_date": "2009-08-20T15:34:07.537Z",
"question_score": 225,
"tags": "python|string|unicode|conventions",
"answer_id": 1307210,
"answer_date": "2009-08-20T16:04:34.463Z",
"answer_score": 269
} |
Please answer the following Stack Overflow question:
Title: Thou shalt not inherit from std::vector
<p>Ok, this is really difficult to confess, but I do have a strong temptation at the moment to inherit from <code>std::vector</code>. </p>
<p>I need about 10 customized algorithms for vector and I want them to be directly members of the vector. But naturally I want also to have the rest of <code>std::vector</code>'s interface. Well, my first idea, as a law-abiding citizen, was to have an <code>std::vector</code> member in <code>MyVector</code> class. But then I would have to manually reprovide all of the std::vector's interface. Too much to type. Next, I thought about private inheritance, so that instead of reproviding methods I would write a bunch of <code>using std::vector::member</code>'s in the public section. This is tedious too actually. </p>
<p>And here I am, I really do think that I can simply inherit publicly from <code>std::vector</code>, but provide a warning in the documentation that this class should not be used polymorphically. I think most developers are competent enough to understand that this shouldn't be used polymorphically anyway.</p>
<p>Is my decision absolutely unjustifiable? If so, why? Can you provide an alternative which would have the additional members <strong>actually</strong> members but would not involve retyping all of vector's interface? I doubt it, but if you can, I'll just be happy.</p>
<p>Also, apart from the fact that some idiot can write something like</p>
<pre><code>std::vector<int>* p = new MyVector
</code></pre>
<p>is there any other <strong><em>realistic</em></strong> peril in using MyVector? By saying realistic I discard things like imagine a function which takes a pointer to vector ...</p>
<p>Well, I've stated my case. I have sinned. Now it's up to you to forgive me or not :)</p> | <p>Actually, there is nothing wrong with public inheritance of <code>std::vector</code>. If you need this, just do that.</p>
<p>I would suggest doing that only if it is <strong>really</strong> necessary. Only if you can't do what you want with free functions (e.g. should keep some state).</p>
<p>The problem is that <code>MyVector</code> is a new entity. It means a new C++ developer should know what the hell it is before using it. What's the difference between <code>std::vector</code> and <code>MyVector</code>? Which one is better to use here and there? What if I need to move <code>std::vector</code> to <code>MyVector</code>? May I just use <code>swap()</code> or not?</p>
<p>Do not produce new entities just to make something to look better. These entities (especially, such common) aren't going to live in vacuum. They will live in mixed environment with constantly increased entropy.</p> | {
"question_id": 4353203,
"question_date": "2010-12-04T11:05:46.497Z",
"question_score": 225,
"tags": "c++|oop|inheritance|stl|vector",
"answer_id": 4353333,
"answer_date": "2010-12-04T11:44:18.977Z",
"answer_score": 175
} |
Please answer the following Stack Overflow question:
Title: Git: Correct way to change Active Branch in a bare repository?
<p>I have a bare repository that's used as the central store for my project. All the developers do <code>git clone <repo></code> to share with it. When they do the clone, they get a checkout of the master branch (unless they do <code>git clone -n</code>) because <code>repo.git/HEAD</code> contains <code>ref: refs/heads/master</code>, making this the <em>Active Branch</em>.</p>
<p>The question is, how do I change the <em>Active Branch</em> properly? I could simply hack the <code>repo.git/HEAD</code> file directly, but that seems nasty and, well, hacky.</p>
<p>I tried doing <code>git checkout <otherbranch></code> in the repo <code>.git</code> directory, but that failed because I wasn't in a work tree.</p>
<p>I tried <code>git update-ref HEAD refs/heads/otherbranch</code> but that just updated refs/heads/master to be the same as refs/heads/otherbranch (okay, I did that one in a dummy repository, not my production one!)</p>
<p>I tried <code>git update-ref --no-deref HEAD refs/heads/otherbranch</code> and that almost worked. It updated the <code>HEAD</code> file, but it set it to the SHA1 of the commit pointed to by <code>refs/heads/otherbranch</code>.</p>
<p>I'm testing with git version <code>1.7.0.2.msysgit.0</code>.</p>
<p>I'm guessing there's no way to do this through <code>git push</code>, as allowing all and sundry to change your default branch seems a bit unsafe (!), but surely there's a better way to do it in the repo <code>.git</code> directory than directly hacking the <code>HEAD</code> file.</p> | <p>If you have access to the remote bare repo, this <a href="http://feeding.cloud.geek.nz/2008/12/setting-default-git-branch-in-bare.html" rel="noreferrer">article suggests</a>:</p>
<pre><code>git symbolic-ref HEAD refs/heads/mybranch
</code></pre>
<blockquote>
<p>Which will update the HEAD file in your repository so that it contains:</p>
</blockquote>
<pre><code>ref: refs/heads/mybranch
</code></pre>
<p>as documented in the <a href="http://www.kernel.org/pub/software/scm/git/docs/git-symbolic-ref.html" rel="noreferrer"><code>git-symbolic-ref</code></a></p>
<hr>
<p>If you don't have access to the remote repo, see <a href="https://stackoverflow.com/questions/1485578/how-do-i-change-a-git-remote-head-to-point-to-something-besides-master/2962737">my previous answer</a>.</p>
<hr>
<p>Remember that a command like <a href="http://git-scm.com/docs/git-remote" rel="noreferrer"><code>git remote set-head</code></a>:</p>
<ul>
<li><p>doesn't change the default branch of the <em>remote</em> repo.<br>
It only changes a <strong>remote tracking branch</strong> stored in your <em>local</em> repo as <code>refs/remotes/<name>/HEAD</code></p></li>
<li><p>doesn't change <code>HEAD</code> itself (again, only <code>refs/remotes/<name>/HEAD</code>), hence the need for
<a href="http://git-scm.com/docs/git-symbolic-ref" rel="noreferrer"><code>git symbolic-ref</code></a>.</p></li>
</ul>
<p>So <code>git remote set-head</code> <strong>is not</strong> the answer here.<br>
<code>git symbolic-ref HEAD</code> is, if you have direct access to the remote repo.</p> | {
"question_id": 3301956,
"question_date": "2010-07-21T17:15:13.727Z",
"question_score": 225,
"tags": "git",
"answer_id": 3302018,
"answer_date": "2010-07-21T17:22:16.037Z",
"answer_score": 331
} |
Please answer the following Stack Overflow question:
Title: Best way to implement request throttling in ASP.NET MVC?
<p>We're experimenting with various ways to throttle user actions in a <strong>given time period</strong>:</p>
<ul>
<li>Limit question/answer posts</li>
<li>Limit edits</li>
<li>Limit feed retrievals</li>
</ul>
<p>For the time being, we're using the Cache to simply insert a record of user activity - if that record exists if/when the user does the same activity, we throttle.</p>
<p>Using the Cache automatically gives us stale data cleaning and sliding activity windows of users, but how it will scale could be a problem.</p>
<p>What are some other ways of ensuring that requests/user actions can be effectively throttled (emphasis on stability)?</p> | <p>Here's a generic version of what we've been using on Stack Overflow for the past year:</p>
<pre><code>/// <summary>
/// Decorates any MVC route that needs to have client requests limited by time.
/// </summary>
/// <remarks>
/// Uses the current System.Web.Caching.Cache to store each client request to the decorated route.
/// </remarks>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ThrottleAttribute : ActionFilterAttribute
{
/// <summary>
/// A unique name for this Throttle.
/// </summary>
/// <remarks>
/// We'll be inserting a Cache record based on this name and client IP, e.g. "Name-192.168.0.1"
/// </remarks>
public string Name { get; set; }
/// <summary>
/// The number of seconds clients must wait before executing this decorated route again.
/// </summary>
public int Seconds { get; set; }
/// <summary>
/// A text message that will be sent to the client upon throttling. You can include the token {n} to
/// show this.Seconds in the message, e.g. "Wait {n} seconds before trying again".
/// </summary>
public string Message { get; set; }
public override void OnActionExecuting(ActionExecutingContext c)
{
var key = string.Concat(Name, "-", c.HttpContext.Request.UserHostAddress);
var allowExecute = false;
if (HttpRuntime.Cache[key] == null)
{
HttpRuntime.Cache.Add(key,
true, // is this the smallest data we can have?
null, // no dependencies
DateTime.Now.AddSeconds(Seconds), // absolute expiration
Cache.NoSlidingExpiration,
CacheItemPriority.Low,
null); // no callback
allowExecute = true;
}
if (!allowExecute)
{
if (String.IsNullOrEmpty(Message))
Message = "You may only perform this action every {n} seconds.";
c.Result = new ContentResult { Content = Message.Replace("{n}", Seconds.ToString()) };
// see 409 - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
c.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
}
}
}
</code></pre>
<p>Sample usage:</p>
<pre><code>[Throttle(Name="TestThrottle", Message = "You must wait {n} seconds before accessing this url again.", Seconds = 5)]
public ActionResult TestThrottle()
{
return Content("TestThrottle executed");
}
</code></pre>
<p>The ASP.NET Cache works like a champ here - by using it, you get automatic clean-up of your throttle entries. And with our growing traffic, we're not seeing that this is an issue on the server.</p>
<p>Feel free to give feedback on this method; when we make Stack Overflow better, you get your <a href="https://stackoverflow.blog/2009/05/31/the-stack-overflow-trilogy/">Ewok fix</a> even faster :)</p> | {
"question_id": 33969,
"question_date": "2008-08-29T04:50:50.410Z",
"question_score": 225,
"tags": "asp.net-mvc|throttling",
"answer_id": 1318059,
"answer_date": "2009-08-23T08:21:56.053Z",
"answer_score": 255
} |
Please answer the following Stack Overflow question:
Title: What is the Haskell response to Node.js?
<p>I believe the Erlang community is not envious of Node.js as it does non-blocking I/O natively and has ways to scale deployments easily to more than one processor (something not even built-in in Node.js). More details at <a href="http://journal.dedasys.com/2010/04/29/erlang-vs-node-js" rel="noreferrer">http://journal.dedasys.com/2010/04/29/erlang-vs-node-js</a> and <a href="https://stackoverflow.com/questions/3011317/node-js-or-erlang">Node.js or Erlang</a></p>
<p>What about Haskell? Can Haskell provide some of the benefits of Node.js, namely a clean solution to avoid blocking I/O without having recourse to multi-thread programming?</p>
<hr>
<p>There are many things that are attractive with Node.js</p>
<ol>
<li>Events: No thread manipulation, the programmer only provides callbacks (as in Snap framework)</li>
<li>Callbacks are guaranteed to be run in a single thread: no race condition possible.</li>
<li>Nice and simple UNIX-friendly API. Bonus: Excellent HTTP support. DNS also available.</li>
<li>Every I/O is by default asynchronous. This makes it easier to avoid locks. However, too much CPU processing in a callback will impact other connections (in this case, the task should split into smaller sub-tasks and re-scheduled).</li>
<li>Same language for client-side and server-side. (I don't see too much value in this one, however. jQuery and Node.js share the event programming model but the rest is very different. I just can't see how sharing code between server-side and client-side could be useful in practice.)</li>
<li>All this packaged in a single product.</li>
</ol> | <p>Ok, so having watched a little of the <a href="http://www.youtube.com/watch?v=F6k8lTrAE2g" rel="noreferrer">node.js presentation</a> that @gawi pointed me at, I can say a bit more about how Haskell compares to node.js. In the presentation, Ryan describes some of the benefits of Green Threads, but then goes on to say that he doesn't find the lack of a thread abstraction to be a disadvantage. I'd disagree with his position, particularly in the context of Haskell: I think the abstractions that threads provide are essential for making server code easier to get right, and more robust. In particular:</p>
<ul>
<li><p>using one thread per connection lets you write code that expresses the communication with a single client, rather that writing code that deals with <em>all</em> the clients at the same time. Think of it like this: a server that handles multiple clients with threads looks almost the same as one that handles a single client; the main difference is there's a <code>fork</code> somewhere in the former. If the protocol you're implementing is at all complex, managing the state machine for multiple clients simultaneously gets quite tricky, whereas threads let you just script the communication with a single client. The code is easier to get right, and easier to understand and maintain.</p></li>
<li><p>callbacks on a single OS thread is cooperative multitasking, as opposed to preemptive multitasking, which is what you get with threads. The main disadvantage with cooperative multitasking is that the programmer is responsible for making sure that there's no starvation. It loses modularity: make a mistake in one place, and it can screw up the whole system. This is really something you don't want to have to worry about, and preemption is the simple solution. Moreover, communication between callbacks isn't possible (it would deadlock).</p></li>
<li><p>concurrency isn't hard in Haskell, because most code is pure and so is thread-safe by construction. There are simple communication primitives. It's much harder to shoot yourself in the foot with concurrency in Haskell than in a language with unrestricted side effects.</p></li>
</ul> | {
"question_id": 3847108,
"question_date": "2010-10-02T18:53:01.403Z",
"question_score": 225,
"tags": "multithreading|haskell|concurrency|node.js",
"answer_id": 3858684,
"answer_date": "2010-10-04T20:01:40.270Z",
"answer_score": 222
} |
Please answer the following Stack Overflow question:
Title: How often to commit changes to source control?
<p>How often should I commit changes to source control ? After every small feature, or only for large features ?</p>
<p>I'm working on a project and have a long-term feature to implement. Currently, I'm committing after every chunk of work, i.e. every sub-feature implemented and bug fixed. I even commit after I've added a new chunk of tests for some feature after discovering a bug.</p>
<p>However, I'm concerned about this pattern. In a productive day of work I might make 10 commits. Given that I'm using Subversion, these commits affect the whole repository, so I wonder if it indeed is a good practice to make so many ?</p> | <p>Anytime I complete a "full thought" of code that compiles and runs I check-in. This usually ends up being anywhere between 15-60 minutes. Sometimes it could be longer, but I always try to checkin if I have a lot of code changes that I wouldn't want to rewrite in case of failure. I also usually make sure my code compiles and I check-in at the end of the work day before I go home.</p>
<p>I wouldn't worry about making "too many" commits/check-ins. It really sucks when you have to rewrite something, and it's nice to be able to rollback in small increments just in case.</p> | {
"question_id": 107264,
"question_date": "2008-09-20T05:37:10.777Z",
"question_score": 225,
"tags": "version-control",
"answer_id": 107281,
"answer_date": "2008-09-20T05:43:06.347Z",
"answer_score": 216
} |
Please answer the following Stack Overflow question:
Title: How to use ThreeTenABP in Android Project
<p>I'm asking this question because I'm new to Java and Android and I searched for hours trying to figure this out. The answer came from a combination of related answers, so I figured I would document what I learned for anyone else who may be struggling. See answer.</p>
<p>I'm using Android Studio 2.1.2 and my Java setup is the following:</p>
<pre><code>>java -version
> openjdk version "1.8.0_91"
> OpenJDK Runtime Environment (build 1.8.0_91-8u91-b14-3ubuntu1~15.10.1-b14)
> OpenJDK 64-Bit Server VM (build 25.91-b14, mixed mode)
</code></pre> | <h1>Attention: This answer, while technically correct, is now out of date</h1>
<h3>Java 8+ API desugaring support now available via Android Gradle Plugin 4.0.0+</h3>
<p>(Also see <a href="https://stackoverflow.com/a/61603915/2065427">Basil Bourque's answer below</a>)</p>
<p>Development on the <a href="https://github.com/JakeWharton/ThreeTenABP" rel="noreferrer">ThreeTenABP Library</a> is winding down. Please consider switching to Android Gradle plugin 4.0, java.time.*, and its core library desugaring feature in the coming months.</p>
<p>To enable support for these language APIs on any version of the Android platform, update the <a href="https://developer.android.com/studio/write/java8-support#library-desugaring" rel="noreferrer">Android plugin to 4.0.0 (or higher)</a> and include the following in your module’s build.gradle file:</p>
<pre><code>android {
defaultConfig {
// Required when setting minSdkVersion to 20 or lower
multiDexEnabled true
}
compileOptions {
// Flag to enable support for the new language APIs
coreLibraryDesugaringEnabled true
// Sets Java compatibility to Java 8
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.0.5'
}
</code></pre>
<hr />
<h1>Original Answer</h1>
<h2>First Discovery: Why You Have To Use <em>ThreeTenABP</em> Instead of <em>java.time</em>, <em>ThreeTen-Backport</em>, or even <em>Joda-Time</em></h2>
<p>This is a really short version of the VERY LONG PROCESS of defining a new standard. All of these packages are pretty much the same thing: libraries that provide good, modern time handling functionality for Java. The differences are subtle but important.</p>
<p>The most obvious solution would be to use the built-in <a href="https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html" rel="noreferrer"><code>java.time</code></a> package, since this is the new standard way to deal with time and dates in Java. It is an implementation of <a href="https://jcp.org/en/jsr/detail?id=310" rel="noreferrer">JSR 310</a>, which was a new standard proposal for time handling based on the <a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-Time</a> library.</p>
<p>However, <code>java.time</code> was introduced in <a href="https://en.wikipedia.org/wiki/Java_version_history#Java_SE_8" rel="noreferrer">Java 8</a>. Android up to <a href="https://en.wikipedia.org/wiki/Android_Marshmallow" rel="noreferrer">Marshmallow</a> runs on Java 7 ("Android N" is the first version to introduce Java 8 language features). Thus, unless you're only targeting <a href="https://en.wikipedia.org/wiki/Android_Nougat" rel="noreferrer">Android N <em>Nougat</em></a> and above, you can't rely on Java 8 language features (I'm not actually sure this is 100% true, but this is how I understand it). So <code>java.time</code> is out.</p>
<p>The next option might be <a href="http://www.joda.org/joda-time/" rel="noreferrer"><em>Joda-Time</em></a>, since <a href="https://www.jcp.org/en/jsr/detail?id=310" rel="noreferrer">JSR 310</a> was based on Joda-Time. However, as the <a href="https://github.com/JakeWharton/ThreeTenABP#why-not-use-threetenbp" rel="noreferrer">ThreeTenABP readme</a> indicates, for a number of reasons, Joda-Time is not the best option.</p>
<p>Next is <a href="http://www.threeten.org/threetenbp/" rel="noreferrer"><em>ThreeTen-Backport</em></a>, which back-ports much (but not all) of the Java 8 <code>java.time</code> functionality to Java 7. This is fine for most use cases, but, as indicated in the <a href="https://github.com/JakeWharton/ThreeTenABP#why-not-use-threetenbp" rel="noreferrer">ThreeTenABP readme</a>, it has performance issues with Android.</p>
<p>So the last and seemingly correct option is <a href="https://github.com/JakeWharton/ThreeTenABP" rel="noreferrer"><em>ThreeTenABP</em></a>.</p>
<h2>Second Discovery: Build Tools and Dependency Management</h2>
<p>Since compiling a program -- especially one using a bunch of external libraries -- is complex, Java almost invariably uses a <a href="https://en.wikipedia.org/wiki/Build_automation" rel="noreferrer">"build tool"</a> to manage the process. <a href="https://en.wikipedia.org/wiki/Make_(software)" rel="noreferrer"><em>Make</em></a>, <a href="https://en.wikipedia.org/wiki/Apache_Ant" rel="noreferrer"><em>Apache Ant</em></a>, <a href="https://en.wikipedia.org/wiki/Apache_Maven" rel="noreferrer"><em>Apache Maven</em></a>, and <a href="https://en.wikipedia.org/wiki/Gradle" rel="noreferrer"><em>Gradle</em></a> are all build tools that are used with Java programs (see <a href="https://technologyconversations.com/2014/06/18/build-tools/" rel="noreferrer">this post</a> for comparisons). As noted further down, Gradle is the chosen build tool for Android projects.</p>
<p>These build tools include dependency management. Apache Maven appears to be the first to include a centralized package repository. Maven introduced the <a href="https://search.maven.org/" rel="noreferrer">Maven Central Repository</a>, which allows functionality equivalent to php's <code>composer</code> with Packagist and Ruby's <code>gem</code> with rubygems.org. In other words, the Maven Central Repository is to Maven (and Gradle) what Packagist is to composer -- a definitive and secure source for versioned packages.</p>
<h2>Third Discovery: Gradle Handles Dependencies in Android Projects</h2>
<p>High on my to-do list is to read the Gradle docs <a href="https://gradle.org/getting-started-gradle/" rel="noreferrer">here</a>, including their free eBooks. Had I read these weeks ago when I started learning Android, I would surely have known that Gradle can use the Maven Central Repository to manage dependencies in Android Projects. Furthermore, as detailed in <a href="https://stackoverflow.com/a/26630422/2065427">this</a> StackOverflow answer, as of Android Studio 0.8.9, Gradle uses Maven Central Repository implicitly through Bintray's JCenter, which means you don't have to do any extra config to set up the repo -- you just list the dependencies.</p>
<h2>Fourth Discovery: Project Dependencies Are Listed in [project dir]/app/build.gradle</h2>
<p>Again, obvious to those who have any experience using Gradle in Java, but it took me a while to figure this out. If you see people saying "Oh, just add <code>compile 'this-or-that.jar'</code>" or something similar, know that <code>compile</code> is a directive in that build.gradle file that indicates compile-time dependencies. <a href="https://docs.gradle.org/current/userguide/artifact_dependencies_tutorial.html" rel="noreferrer">Here's</a> the official Gradle page on dependency management.</p>
<h2>Fifth Discovery: ThreeTenABP Is Managed by Jake Wharton, not by ThreeTen</h2>
<p>Yet another issue I spent too much time figuring out. If you look for ThreeTen in Maven Central, you'll only see packages for <code>threetenbp</code>, not <code>threetenabp</code>. If you go to the <a href="https://github.com/JakeWharton/ThreeTenABP" rel="noreferrer">github repo for ThreeTenABP</a>, you'll see that infamous <code>compile 'this-or-that'</code> line under the Download section of the Readme.</p>
<p>When I first hit this github repo, I didn't know what that compile line meant, and I tried to run it in my terminal (with an obvious and predictable failure). Frustrated, I didn't return to it until long after I figured the rest out, and finally realized that it's a Maven Repo line pointing to the <code>com.jakewharton.threetenabp</code> repo, as opposed to the <code>org.threeten</code> repo. That's why I thought the ThreeTenABP package wasn't in the Maven repo.</p>
<h2>Summary: Making it work</h2>
<p>Now it all seems pretty easy. You can get modern time handling functions in an Android project by making sure your <code>[project folder]/app/build.gradle</code> file has the <code>implementation 'com.jakewharton.threetenabp:threetenabp:1.2.1'</code> line in its <code>dependencies</code> section:</p>
<pre><code>apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "me.ahuman.myapp"
minSdkVersion 11
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
testImplementation 'junit:junit:4.12'
implementation 'com.android.support:appcompat-v7:23.4.0'
implementation 'com.android.support:design:23.4.0'
implementation 'com.jakewharton.threetenabp:threetenabp:1.2.1'
}
</code></pre>
<p>Also add this to Application class:</p>
<pre><code>public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
AndroidThreeTen.init(this);
//...
}
}
</code></pre> | {
"question_id": 38922754,
"question_date": "2016-08-12T16:36:26.833Z",
"question_score": 225,
"tags": "android|datetime|android-gradle-plugin|threetenbp|threetenabp",
"answer_id": 38922755,
"answer_date": "2016-08-12T16:36:26.833Z",
"answer_score": 225
} |
Please answer the following Stack Overflow question:
Title: Good examples of Not a Functor/Functor/Applicative/Monad?
<p>While explaining to someone what a type class X is I struggle to find good examples of data structures which are exactly X.</p>
<p>So, I request examples for:</p>
<ul>
<li>A type constructor which is not a Functor.</li>
<li>A type constructor which is a Functor, but not Applicative.</li>
<li>A type constructor which is an Applicative, but is not a Monad.</li>
<li>A type constructor which is a Monad.</li>
</ul>
<p>I think there are plenty examples of Monad everywhere, but a good example of Monad with some relation to previous examples could complete the picture.</p>
<p>I look for examples which would be similar to each other, differing only in aspects important for belonging to the particular type class.</p>
<p>If one could manage to sneak up an example of Arrow somewhere in this hierarchy (is it between Applicative and Monad?), that would be great too!</p> | <p><strong>A type constructor which is not a Functor:</strong></p>
<pre><code>newtype T a = T (a -> Int)
</code></pre>
<p>You can make a contravariant functor out of it, but not a (covariant) functor. Try writing <code>fmap</code> and you'll fail. Note that the contravariant functor version is reversed:</p>
<pre><code>fmap :: Functor f => (a -> b) -> f a -> f b
contramap :: Contravariant f => (a -> b) -> f b -> f a
</code></pre>
<p><strong>A type constructor which is a functor, but not Applicative:</strong></p>
<p>I don't have a good example. There is <code>Const</code>, but ideally I'd like a concrete non-Monoid and I can't think of any. All types are basically numeric, enumerations, products, sums, or functions when you get down to it. You can see below pigworker and I disagreeing about whether <code>Data.Void</code> is a <code>Monoid</code>;</p>
<pre><code>instance Monoid Data.Void where
mempty = undefined
mappend _ _ = undefined
mconcat _ = undefined
</code></pre>
<p>Since <code>_|_</code> is a legal value in Haskell, and in fact the only legal value of <code>Data.Void</code>, this meets the Monoid rules. I am unsure what <code>unsafeCoerce</code> has to do with it, because your program is no longer guaranteed not to violate Haskell semantics as soon as you use any <code>unsafe</code> function.</p>
<p>See the Haskell Wiki for an article on bottom (<a href="http://www.haskell.org/haskellwiki/Bottom" rel="noreferrer">link</a>) or unsafe functions (<a href="http://www.haskell.org/haskellwiki/Unsafe" rel="noreferrer">link</a>).</p>
<p>I wonder if it is possible to create such a type constructor using a richer type system, such as Agda or Haskell with various extensions.</p>
<p><strong>A type constructor which is an Applicative, but not a Monad:</strong></p>
<pre><code>newtype T a = T {multidimensional array of a}
</code></pre>
<p>You can make an Applicative out of it, with something like:</p>
<pre><code>mkarray [(+10), (+100), id] <*> mkarray [1, 2]
== mkarray [[11, 101, 1], [12, 102, 2]]
</code></pre>
<p>But if you make it a monad, you could get a dimension mismatch. I suspect that examples like this are rare in practice.</p>
<p><strong>A type constructor which is a Monad:</strong></p>
<pre><code>[]
</code></pre>
<p><strong>About Arrows:</strong></p>
<p>Asking where an Arrow lies on this hierarchy is like asking what kind of shape "red" is. Note the kind mismatch:</p>
<pre><code>Functor :: * -> *
Applicative :: * -> *
Monad :: * -> *
</code></pre>
<p>but,</p>
<pre><code>Arrow :: * -> * -> *
</code></pre> | {
"question_id": 7220436,
"question_date": "2011-08-28T10:42:52.550Z",
"question_score": 225,
"tags": "haskell|monads|functor|applicative",
"answer_id": 7220548,
"answer_date": "2011-08-28T11:04:52.857Z",
"answer_score": 104
} |
Please answer the following Stack Overflow question:
Title: What makes the Visual Studio debugger stop evaluating a ToString override?
<p>Environment: Visual Studio 2015 RTM. (I haven't tried older versions.)</p>
<p>Recently, I've been debugging some of my <a href="http://nodatime.org">Noda Time</a> code, and I've noticed that when I've got a local variable of type <code>NodaTime.Instant</code> (one of the central <code>struct</code> types in Noda Time), the "Locals" and "Watch" windows don't appear to call its <code>ToString()</code> override. If I call <code>ToString()</code> explicitly in the watch window, I see the appropriate representation, but otherwise I just see:</p>
<pre><code>variableName {NodaTime.Instant}
</code></pre>
<p>which isn't very useful.</p>
<p>If I change the override to return a constant string, the string <em>is</em> displayed in the debugger, so it's clearly able to pick up that it's there - it just doesn't want to use it in its "normal" state.</p>
<p>I decided to reproduce this locally in a little demo app, and here's what I've come up with. (Note that in an early version of this post, <code>DemoStruct</code> was a class and <code>DemoClass</code> didn't exist at all - my fault, but it explains some comments which look odd now...)</p>
<pre><code>using System;
using System.Diagnostics;
using System.Threading;
public struct DemoStruct
{
public string Name { get; }
public DemoStruct(string name)
{
Name = name;
}
public override string ToString()
{
Thread.Sleep(1000); // Vary this to see different results
return $"Struct: {Name}";
}
}
public class DemoClass
{
public string Name { get; }
public DemoClass(string name)
{
Name = name;
}
public override string ToString()
{
Thread.Sleep(1000); // Vary this to see different results
return $"Class: {Name}";
}
}
public class Program
{
static void Main()
{
var demoClass = new DemoClass("Foo");
var demoStruct = new DemoStruct("Bar");
Debugger.Break();
}
}
</code></pre>
<p>In the debugger, I now see:</p>
<pre><code>demoClass {DemoClass}
demoStruct {Struct: Bar}
</code></pre>
<p>However, if I reduce the <code>Thread.Sleep</code> call down from 1 second to 900ms, there's still a short pause, but then I see <code>Class: Foo</code> as the value. It doesn't seem to matter how long the <code>Thread.Sleep</code> call is in <code>DemoStruct.ToString()</code>, it's always displayed properly - and the debugger displays the value before the sleep would have completed. (It's as if <code>Thread.Sleep</code> is disabled.)</p>
<p>Now <code>Instant.ToString()</code> in Noda Time does a fair amount of work, but it certainly doesn't take a whole second - so presumably there are more conditions that cause the debugger to give up evaluating a <code>ToString()</code> call. And of course it's a struct anyway.</p>
<p>I've tried recursing to see whether it's a stack limit, but that appears not to be the case.</p>
<p>So, how can I work out what's stopping VS from fully evaluating <code>Instant.ToString()</code>? As noted below, <code>DebuggerDisplayAttribute</code> appears to help, but without knowing <em>why</em>, I'm never going to be entirely confident in when I need it and when I don't.</p>
<p><strong>Update</strong></p>
<p>If I use <a href="https://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerdisplayattribute.debuggerdisplayattribute"><code>DebuggerDisplayAttribute</code></a>, things change:</p>
<pre><code>// For the sample code in the question...
[DebuggerDisplay("{ToString()}")]
public class DemoClass
</code></pre>
<p>gives me:</p>
<pre><code>demoClass Evaluation timed out
</code></pre>
<p>Whereas when I apply it in Noda Time:</p>
<pre><code>[DebuggerDisplay("{ToString()}")]
public struct Instant
</code></pre>
<p>a simple test app shows me the right result:</p>
<pre><code>instant "1970-01-01T00:00:00Z"
</code></pre>
<p>So presumably the problem in Noda Time is some condition that <code>DebuggerDisplayAttribute</code> <em>does</em> force through - even though it doesn't force through timeouts. (This would be in line with my expectation that <code>Instant.ToString</code> is easily fast enough to avoid a timeout.)</p>
<p>This <em>may</em> be a good enough solution - but I'd still like to know what's going on, and whether I can change the code simply to avoid having to put the attribute on all the various value types in Noda Time.</p>
<p><strong>Curiouser and curiouser</strong></p>
<p>Whatever is confusing the debugger only confuses it sometimes. Let's create a class which <em>holds</em> an <code>Instant</code> and uses it for its own <code>ToString()</code> method:</p>
<pre><code>using NodaTime;
using System.Diagnostics;
public class InstantWrapper
{
private readonly Instant instant;
public InstantWrapper(Instant instant)
{
this.instant = instant;
}
public override string ToString() => instant.ToString();
}
public class Program
{
static void Main()
{
var instant = NodaConstants.UnixEpoch;
var wrapper = new InstantWrapper(instant);
Debugger.Break();
}
}
</code></pre>
<p>Now I end up seeing:</p>
<pre><code>instant {NodaTime.Instant}
wrapper {1970-01-01T00:00:00Z}
</code></pre>
<p>However, at the suggestion of Eren in comments, if I change <code>InstantWrapper</code> to be a struct, I get:</p>
<pre><code>instant {NodaTime.Instant}
wrapper {InstantWrapper}
</code></pre>
<p>So it <em>can</em> evaluate <code>Instant.ToString()</code> - so long as that's invoked by another <code>ToString</code> method... which is within a class. The class/struct part seems to be important based on the type of the variable being displayed, not what code needs
to be executed in order to get the result.</p>
<p>As another example of this, if we use:</p>
<pre><code>object boxed = NodaConstants.UnixEpoch;
</code></pre>
<p>... then it works fine, displaying the right value. Colour me confused.</p> | <h1>Update:</h1>
<p>This bug has been fixed in Visual Studio 2015 Update 2. Let me know if you are still running into problems evaluating ToString on struct values using Update 2 or later.</p>
<h1>Original Answer:</h1>
<p>You are running into a known bug/design limitation with Visual Studio 2015 and calling ToString on struct types. This can also be observed when dealing with <code>System.DateTimeSpan</code>. <code>System.DateTimeSpan.ToString()</code> works in the evaluation windows with Visual Studio 2013, but does not always work in 2015.</p>
<p>If you are interested in the low level details, here's what's going on:</p>
<p>To evaluate <code>ToString</code>, the debugger does what's known as "function evaluation". In greatly simplified terms, the debugger suspends all threads in the process except the current thread, changes the context of the current thread to the <code>ToString</code> function, sets a hidden guard breakpoint, then allows the process to continue. When the guard breakpoint is hit, the debugger restores the process to its previous state and the return value of the function is used to populate the window.</p>
<p>To support lambda expressions, we had to completely rewrite the CLR Expression Evaluator in Visual Studio 2015. At a high level, the implementation is:</p>
<ol>
<li>Roslyn generates MSIL code for expressions/local variables to get the values to be displayed in the various inspection windows.</li>
<li>The debugger interprets the IL to get the result.</li>
<li>If there are any "call" instructions, the debugger executes a
function evaluation as described above.</li>
<li>The debugger/roslyn takes this result and formats it into the
tree-like view that's shown to the user.</li>
</ol>
<p>Because of the execution of IL, the debugger is always dealing with a complicated mix of "real" and "fake" values. Real values actually exist in the process being debugged. Fake values only exist in the debugger process. To implement proper struct semantics, the debugger always needs to make a copy of the value when pushing a struct value to the IL stack. The copied value is no longer a "real" value and now only exists in the debugger process. That means if we later need to perform function evaluation of <code>ToString</code>, we can't because the value doesn't exist in the process. To try and get the value we need to emulate execution of the <code>ToString</code> method. While we can emulate some things, there are many limitations. For example, we can't emulate native code and we can't execute calls to "real" delegate values or calls on reflection values.</p>
<p>With all of that in mind, here is what's causing the various behaviors you are seeing:</p>
<ol>
<li>The debugger isn't evaluating <code>NodaTime.Instant.ToString</code> -> This is
because it is struct type and the implementation of ToString can't
be emulated by the debugger as described above.</li>
<li><code>Thread.Sleep</code> seems to take zero time when called by <code>ToString</code> on a
struct -> This is because the emulator is executing <code>ToString</code>.
Thread.Sleep is a native method, but the emulator is aware
of it and just ignores the call. We do this to try and get a value
to show to the user. A delay wouldn't be helpful in this case.</li>
<li><code>DisplayAttibute("ToString()")</code> works. -> That is confusing. The only
difference between the implicit calling of <code>ToString</code> and
<code>DebuggerDisplay</code> is that any time-outs of the implicit <code>ToString</code>
evaluation will disable all implicit <code>ToString</code> evaluations for that
type until the next debug session. You may be observing that
behavior.</li>
</ol>
<p>In terms of the design problem/bug, this is something we are planning to address in a future release of Visual Studio.</p>
<p>Hopefully that clears things up. Let me know if you have more questions. :-)</p> | {
"question_id": 31562791,
"question_date": "2015-07-22T12:12:21.663Z",
"question_score": 225,
"tags": "c#|debugging|visual-studio-2015",
"answer_id": 31569625,
"answer_date": "2015-07-22T17:05:26.520Z",
"answer_score": 195
} |
Please answer the following Stack Overflow question:
Title: Pass array to ajax request in $.ajax()
<p>I want to send an array as an Ajax request:</p>
<pre><code>info[0] = 'hi';
info[1] = 'hello';
$.ajax({
type: "POST",
url: "index.php",
success: function(msg){
$('.answer').html(msg);
}
});
</code></pre>
<p>How can I do this?</p> | <pre><code>info = [];
info[0] = 'hi';
info[1] = 'hello';
$.ajax({
type: "POST",
data: {info:info},
url: "index.php",
success: function(msg){
$('.answer').html(msg);
}
});
</code></pre> | {
"question_id": 8890524,
"question_date": "2012-01-17T06:23:58.290Z",
"question_score": 224,
"tags": "jquery|ajax|arrays|json",
"answer_id": 8890787,
"answer_date": "2012-01-17T07:00:33.767Z",
"answer_score": 281
} |
Please answer the following Stack Overflow question:
Title: How to create a jQuery function (a new jQuery method or plugin)?
<p>I know that in JavaScript the syntax is as follows:</p>
<pre><code>function myfunction(param){
//some code
}
</code></pre>
<p>Is there a way to declare a function in jQuery that can be added to an element? For example:</p>
<pre><code>$('#my_div').myfunction()
</code></pre> | <p>From the <a href="http://docs.jquery.com/Plugins/Authoring" rel="noreferrer">Docs</a>:</p>
<pre><code>(function( $ ){
$.fn.myfunction = function() {
alert('hello world');
return this;
};
})( jQuery );
</code></pre>
<p>Then you do </p>
<pre><code>$('#my_div').myfunction();
</code></pre> | {
"question_id": 12093192,
"question_date": "2012-08-23T13:51:04.067Z",
"question_score": 224,
"tags": "javascript|jquery|function",
"answer_id": 12093389,
"answer_date": "2012-08-23T13:59:26.870Z",
"answer_score": 317
} |
Please answer the following Stack Overflow question:
Title: Where is SQL Server Management Studio 2012?
<p>I had SQL Server 2008 R2 and Visual Studio 2008 and 2010 on my laptop. I've installed SQL Server 2012 and have finally got SQL Server Data Tools to show up, so that I can create SSRS reports in Visual Studio 2010.</p>
<p>Although I've installed Management tools - <em>many times</em> - on two separate instances of SQL Server 2012, I can't find them in Programs and can't run them. The only SSMS program I can find runs SSMS 2008 R2.</p>
<p>I realise that common advice is to install SQL Server before Visual Studio, but I really don't want to uninstall Visual Studio, as this will bring a host of other problems. </p>
<p>How can I fix this problem?</p> | <p>You can get <a href="http://www.microsoft.com/en-us/download/details.aspx?id=43351" rel="nofollow noreferrer">SSMS Express tools from here</a> or full <a href="http://www.microsoft.com/betaexperience/pd/SQL2012EvalCTA/enus/default.aspx" rel="nofollow noreferrer">SQL Server Eval tools from here</a>. <a href="http://msdn.microsoft.com/subscriptions/downloads/default.aspx" rel="nofollow noreferrer">MSDN</a>/<a href="http://technet.microsoft.com/subscriptions/downloads/default.aspx" rel="nofollow noreferrer">TechNet</a> Downloads is currently the only place to get RTM versions (<em>non-eval</em>) of the SSMS 2012 toolset.</p>
<p>Note the first link now(dec 2017) points to 'Microsoft® SQL Server® 2012 Service Pack 2 (SP2) Express'. ssms 2014 and 2017 are still available.</p> | {
"question_id": 10452851,
"question_date": "2012-05-04T16:39:22.153Z",
"question_score": 224,
"tags": "ssms|sql-server-2012",
"answer_id": 10454865,
"answer_date": "2012-05-04T19:17:52.893Z",
"answer_score": 119
} |
Please answer the following Stack Overflow question:
Title: 'Conda' is not recognized as internal or external command
<p>I installed Anaconda3 4.4.0 (32 bit) on my Windows 7 Professional machine and imported NumPy and Pandas on Jupyter notebook so I assume Python was installed correctly. But when I type <code>conda list</code> and <code>conda --version</code> in command prompt, it says <code>conda is not recognized as internal or external command.</code></p>
<p>I have set environment variable for Anaconda3; <code>Variable Name: Path</code>, <code>Variable Value: C:\Users\dipanwita.neogy\Anaconda3</code></p>
<p>How do I make it work?</p> | <p>Although you were offered a good solution by others I think it is helpful to point out what is really happening. As per the Anaconda 4.4 changelog, <a href="https://docs.anaconda.com/anaconda/reference/release-notes/#what-s-new-in-anaconda-4-4" rel="noreferrer">https://docs.anaconda.com/anaconda/reference/release-notes/#what-s-new-in-anaconda-4-4</a>:</p>
<blockquote>
<p>On Windows, the PATH environment variable is no longer changed by default, as this can cause trouble with other software. The recommended approach is to instead use Anaconda Navigator or the Anaconda Command Prompt (located in the Start Menu under “Anaconda”) when you wish to use Anaconda software.</p>
</blockquote>
<p>(Note: recent Win 10 does not assume you have privileges to install or update. If the command fails, right-click on the Anaconda Command Prompt, choose "More", chose "Run as administrator")</p>
<p>This is a change from previous installations. It is suggested to use Navigator or the Anaconda Prompt although you can always add it to your PATH as well. During the install the box to add Anaconda to the PATH is now unchecked but you can select it.</p> | {
"question_id": 44515769,
"question_date": "2017-06-13T08:09:39.993Z",
"question_score": 224,
"tags": "python|anaconda|conda|data-science",
"answer_id": 44527943,
"answer_date": "2017-06-13T17:26:34.660Z",
"answer_score": 207
} |
Please answer the following Stack Overflow question:
Title: How to count occurrences of a column value efficiently in SQL?
<p>I have a table of students:</p>
<pre><code>id | age
--------
0 | 25
1 | 25
2 | 23
</code></pre>
<p>I want to query for all students, and an additional column that counts how many students are of the same age:</p>
<pre><code>id | age | count
----------------
0 | 25 | 2
1 | 25 | 2
2 | 23 | 1
</code></pre>
<p>What's the most efficient way of doing this? <strong>I fear that a sub-query will be slow, and I'm wondering if there's a better way</strong>. Is there?</p> | <p>This should work:</p>
<pre><code>SELECT age, count(age)
FROM Students
GROUP by age
</code></pre>
<p>If you need the id as well you could include the above as a sub query like so:</p>
<pre><code>SELECT S.id, S.age, C.cnt
FROM Students S
INNER JOIN (SELECT age, count(age) as cnt
FROM Students
GROUP BY age) C ON S.age = C.age
</code></pre> | {
"question_id": 1503959,
"question_date": "2009-10-01T13:27:26.927Z",
"question_score": 224,
"tags": "sql|performance",
"answer_id": 1503980,
"answer_date": "2009-10-01T13:30:05.830Z",
"answer_score": 327
} |
Please answer the following Stack Overflow question:
Title: What's the fastest way to delete a large folder in Windows?
<p>I want to delete a folder that contains thousands of files and folders. If I use Windows Explorer to delete the folder it can take 10-15 minutes (not always, but often). Is there a faster way in Windows to delete folders? </p>
<p>Other details:</p>
<ul>
<li>I don't care about the recycle bin.</li>
<li>It's an NTFS drive.</li>
</ul> | <h3>Using Windows Command Prompt:</h3>
<pre><code>rmdir /s /q folder
</code></pre>
<h3>Using Powershell:</h3>
<pre><code>powershell -Command "Remove-Item -LiteralPath 'folder' -Force -Recurse"
</code></pre>
<p>Note that in more cases <code>del</code> and <code>rmdir</code> wil leave you with leftover files, where Powershell manages to delete the files.</p> | {
"question_id": 186737,
"question_date": "2008-10-09T10:55:05.210Z",
"question_score": 224,
"tags": "windows|windows-xp|file-management",
"answer_id": 186748,
"answer_date": "2008-10-09T10:59:14.157Z",
"answer_score": 384
} |
Please answer the following Stack Overflow question:
Title: JPA : How to convert a native query result set to POJO class collection
<p>I am using JPA in my project.</p>
<p>I came to a query in which I need to make join operation on five tables. So I created a native query which returns five fields.</p>
<p>Now I want to convert the result object to java POJO class which contains the same five Strings.</p>
<p>Is there any way in JPA to directly cast that result to POJO object list ??</p>
<p>I came to the following solution ..</p>
<pre><code>@NamedNativeQueries({
@NamedNativeQuery(
name = "nativeSQL",
query = "SELECT * FROM Actors",
resultClass = db.Actor.class),
@NamedNativeQuery(
name = "nativeSQL2",
query = "SELECT COUNT(*) FROM Actors",
resultClass = XXXXX) // <--------------- problem
})
</code></pre>
<p>Now here in resultClass, do we need to provide a class which is actual JPA entity ?
OR
We can convert it to any JAVA POJO class which contains the same column names ?</p> | <p>JPA provides an <a href="http://docs.oracle.com/javaee/5/api/javax/persistence/SqlResultSetMapping.html" rel="noreferrer"><code>SqlResultSetMapping</code></a> that allows you to map whatever returns from your native query into an Entity <del>or a custom class</del>.</p>
<p><strong>EDIT</strong> JPA 1.0 does not allow mapping to non-entity classes. Only in JPA 2.1 a <a href="http://docs.oracle.com/javaee/7/api/javax/persistence/ConstructorResult.html" rel="noreferrer">ConstructorResult</a> has been added to map return values a java class.</p>
<p>Also, for OP's problem with getting count it should be enough to define a result set mapping with a single <a href="http://docs.oracle.com/javaee/7/api/javax/persistence/ColumnResult.html" rel="noreferrer"><code>ColumnResult</code></a></p> | {
"question_id": 13012584,
"question_date": "2012-10-22T13:34:05.400Z",
"question_score": 224,
"tags": "java|jpa",
"answer_id": 13013323,
"answer_date": "2012-10-22T14:16:00.527Z",
"answer_score": 118
} |
Please answer the following Stack Overflow question:
Title: How do you get the magnitude of a vector in Numpy?
<p>In keeping with the "There's only one obvious way to do it", how do you get the magnitude of a vector (1D array) in Numpy?</p>
<pre><code>def mag(x):
return math.sqrt(sum(i**2 for i in x))
</code></pre>
<p>The above works, but I <em>cannot believe</em> that I must specify such a trivial and core function myself.</p> | <p>The function you're after is <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.norm.html" rel="noreferrer"><code>numpy.linalg.norm</code></a>. (I reckon it should be in base numpy as a property of an array -- say <code>x.norm()</code> -- but oh well).</p>
<pre><code>import numpy as np
x = np.array([1,2,3,4,5])
np.linalg.norm(x)
</code></pre>
<p>You can also feed in an optional <code>ord</code> for the nth order norm you want. Say you wanted the 1-norm:</p>
<pre><code>np.linalg.norm(x,ord=1)
</code></pre>
<p>And so on.</p> | {
"question_id": 9171158,
"question_date": "2012-02-07T04:48:50.433Z",
"question_score": 224,
"tags": "python|numpy",
"answer_id": 9171196,
"answer_date": "2012-02-07T04:54:44.113Z",
"answer_score": 298
} |
Please answer the following Stack Overflow question:
Title: How to download files using axios
<p>I am using axios for basic http requests like GET and POST, and it works well. Now I need to be able to download Excel files too. Is this possible with axios? If so does anyone have some sample code? If not, what else can I use in a React application to do the same?</p> | <p>When response comes with a downloadable file, response headers will be something like</p>
<pre><code>Content-Disposition: "attachment;filename=report.xls"
Content-Type: "application/octet-stream" // or Content-type: "application/vnd.ms-excel"
</code></pre>
<p>What you can do is create a separate component, which will contain a hidden iframe.</p>
<pre><code> import * as React from 'react';
var MyIframe = React.createClass({
render: function() {
return (
<div style={{display: 'none'}}>
<iframe src={this.props.iframeSrc} />
</div>
);
}
});
</code></pre>
<p>Now, you can pass the url of the downloadable file as prop to this component, So when this component will receive prop, it will re-render and file will be downloaded.</p>
<p><strong>Edit:</strong> You can also use <a href="https://www.npmjs.com/package/js-file-download" rel="noreferrer">js-file-download</a> module. <a href="https://github.com/kennethjiang/js-file-download" rel="noreferrer">Link to Github repo</a></p>
<pre><code>const FileDownload = require('js-file-download');
Axios({
url: 'http://localhost/downloadFile',
method: 'GET',
responseType: 'blob', // Important
}).then((response) => {
FileDownload(response.data, 'report.csv');
});
</code></pre>
<p>Hope this helps :)</p> | {
"question_id": 41938718,
"question_date": "2017-01-30T14:47:03.560Z",
"question_score": 224,
"tags": "axios",
"answer_id": 41940307,
"answer_date": "2017-01-30T16:02:28.893Z",
"answer_score": 162
} |
Please answer the following Stack Overflow question:
Title: How to run cron once, daily at 10pm
<p>I had entered:</p>
<pre><code>* 22 * * * test > /dev/null
</code></pre>
<p>However, I am being notified via email that this is running every minute.
I am confused I guess because I thought this was correct for what I am wanting.</p> | <p>It's running every minute of the hour 22 I guess. Try the following to run it every first minute of the hour 22:</p>
<pre><code>0 22 * * * ....
</code></pre> | {
"question_id": 8938120,
"question_date": "2012-01-20T07:35:08.187Z",
"question_score": 224,
"tags": "bash|cron|system|scheduled-tasks",
"answer_id": 8938143,
"answer_date": "2012-01-20T07:37:05.237Z",
"answer_score": 429
} |
Please answer the following Stack Overflow question:
Title: Java integer to byte array
<p>I got an integer: <code>1695609641</code></p>
<p>when I use method: </p>
<pre><code>String hex = Integer.toHexString(1695609641);
system.out.println(hex);
</code></pre>
<p>gives:</p>
<pre><code>6510f329
</code></pre>
<p>but I want a byte array:</p>
<pre><code>byte[] bytearray = new byte[] { (byte) 0x65, (byte)0x10, (byte)0xf3, (byte)0x29};
</code></pre>
<p>How can I make this?</p> | <p>using Java NIO's <a href="http://java.sun.com/javase/6/docs/api/java/nio/ByteBuffer.html" rel="noreferrer">ByteBuffer</a> is very simple:</p>
<pre><code>byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
</code></pre>
<p>output:</p>
<pre>
0x65 0x10 0xf3 0x29
</pre> | {
"question_id": 2183240,
"question_date": "2010-02-02T10:17:46.033Z",
"question_score": 224,
"tags": "java|arrays|integer|byte",
"answer_id": 2183279,
"answer_date": "2010-02-02T10:23:33.757Z",
"answer_score": 334
} |
Please answer the following Stack Overflow question:
Title: How to combine date from one field with time from another field - MS SQL Server
<p>In an extract I am dealing with, I have 2 <code>datetime</code> columns. One column stores the dates and another the times as shown.</p>
<p>How can I query the table to combine these two fields into 1 column of type <code>datetime</code>?</p>
<p><strong>Dates</strong></p>
<pre><code>2009-03-12 00:00:00.000
2009-03-26 00:00:00.000
2009-03-26 00:00:00.000
</code></pre>
<p><strong>Times</strong></p>
<pre><code>1899-12-30 12:30:00.000
1899-12-30 10:00:00.000
1899-12-30 10:00:00.000
</code></pre> | <p>You can simply add the two.</p>
<ul>
<li><strong>if</strong> the <code>Time part</code> of your <code>Date</code> column is always zero </li>
<li><strong>and</strong> the <code>Date part</code> of your <code>Time</code> column is also always zero <em>(base date: January 1, 1900)</em></li>
</ul>
<p>Adding them returns the correct result.</p>
<pre><code>SELECT Combined = MyDate + MyTime FROM MyTable
</code></pre>
<h3>Rationale (kudos to ErikE/dnolan)</h3>
<blockquote>
<p>It works like this due to the way the date is stored as two 4-byte
<code>Integers</code> with the left 4-bytes being the <code>date</code> and the right
4-bytes being the <code>time</code>. Its like doing <code>$0001 0000 + $0000 0001 =
$0001 0001</code></p>
</blockquote>
<h3>Edit regarding new SQL Server 2008 types</h3>
<p><code>Date</code> and <code>Time</code> are types introduced in <code>SQL Server 2008</code>. If you insist on adding, you can use <code>Combined = CAST(MyDate AS DATETIME) + CAST(MyTime AS DATETIME)</code></p>
<h3>Edit2 regarding loss of precision in SQL Server 2008 and up (kudos to Martin Smith)</h3>
<p>Have a look at <a href="https://dba.stackexchange.com/questions/51440/how-to-combine-date-and-time-to-datetime2-in-sql-server">How to combine date and time to datetime2 in SQL Server?</a> to prevent loss of precision using SQL Server 2008 and up.</p> | {
"question_id": 700619,
"question_date": "2009-03-31T08:46:19.920Z",
"question_score": 224,
"tags": "sql|sql-server|datetime",
"answer_id": 700649,
"answer_date": "2009-03-31T08:54:02.677Z",
"answer_score": 270
} |
Please answer the following Stack Overflow question:
Title: Location of my.cnf file on macOS
<p>I'm trying to follow along <a href="http://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html" rel="noreferrer">this tutorial</a> to enable remote access to MySQL. The problem is, where should <code>my.cnf</code> file be located? I'm using Mac OS X Lion.</p> | <p><a href="http://forums.mysql.com/read.php?11,366143,376017#msg-376017" rel="noreferrer">This thread on the MySQL forum</a> says:</p>
<blockquote>
<p><em>By default, the OS X installation does not use a my.cnf, and MySQL just uses the default values. To set up your own my.cnf, you could just create a file straight in /etc.</em> </p>
</blockquote>
<p>OS X provides example configuration files at <code>/usr/local/mysql/support-files/</code>.</p>
<p>And if you can't find them there, MySQLWorkbench can create them for you by:</p>
<ol>
<li>Opening a connection</li>
<li>Selecting the 'Options File' under 'INSTANCE' in the menu.</li>
<li>MySQLWorkbench will search for my.cnf and if it can't find it, it'll create it for you</li>
</ol> | {
"question_id": 10757169,
"question_date": "2012-05-25T15:26:43.613Z",
"question_score": 224,
"tags": "mysql|database|macos",
"answer_id": 10757261,
"answer_date": "2012-05-25T15:32:44.327Z",
"answer_score": 267
} |
Please answer the following Stack Overflow question:
Title: Reset MySQL root password using ALTER USER statement after install on Mac
<p>I'm new to the whole Mac experience. I recently installed MySQL and it seems I have to reset the password after install. It won't let me do anything else.</p>
<p>Now I already reset the password the usual way: </p>
<pre><code>update user set password = password('XXX') where user = root;
</code></pre>
<p>(BTW: took me ages to work out that MySQL for some bizarre reason has renamed the field 'password' to 'authentication_string'. I am quite upset about changes like that.)</p>
<p>Unfortunately it seems I need to change the password a different way that is unknown to me. Maybe someone here has already come across that problem?</p> | <p>If this is <strong>NOT</strong> your <strong>first time</strong> setting up the password, try this method:</p>
<pre><code>mysql> UPDATE mysql.user SET Password=PASSWORD('your_new_password')
WHERE User='root';
</code></pre>
<p>And if you get the following error, there is a high chance that you have never set your password before:</p>
<pre><code>ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.
</code></pre>
<p>To set up your password for the <strong>first time</strong>:</p>
<pre><code>mysql> SET PASSWORD = PASSWORD('your_new_password');
Query OK, 0 rows affected, 1 warning (0.01 sec)
</code></pre>
<hr>
<p>Reference: <a href="https://dev.mysql.com/doc/refman/5.6/en/alter-user.html" rel="noreferrer">https://dev.mysql.com/doc/refman/5.6/en/alter-user.html</a></p> | {
"question_id": 33467337,
"question_date": "2015-11-01T21:18:19.697Z",
"question_score": 224,
"tags": "mysql|macos",
"answer_id": 33511149,
"answer_date": "2015-11-03T23:34:20.163Z",
"answer_score": 561
} |
Please answer the following Stack Overflow question:
Title: intellij incorrectly saying no beans of type found for autowired repository
<p>I have created a simple unit test but IntelliJ is incorrectly highlighting it red. marking it as an error</p>
<p>No beans?</p>
<p><img src="https://i.stack.imgur.com/4cCFH.png" alt="enter image description here"></p>
<p>As you can see below it passes the test? So it must be Autowired?</p>
<p><img src="https://i.stack.imgur.com/YFGln.png" alt="enter image description here"></p> | <p>I had this same issue when creating a <em>Spring Boot</em> application using their <code>@SpringBootApplication</code> annotation. This annotation represents <code>@Configuration</code>, <code>@EnableAutoConfiguration</code> and <code>@ComponentScan</code> according to the <a href="http://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-using-springbootapplication-annotation.html" rel="noreferrer">spring reference</a>.</p>
<p>As expected, the new annotation worked properly and my application ran smoothly but, <strong>Intellij</strong> kept complaining about unfulfilled <code>@Autowire</code> dependencies. As soon as I changed back to using <code>@Configuration</code>, <code>@EnableAutoConfiguration</code> and <code>@ComponentScan</code> separately, the errors ceased. It seems <strong>Intellij 14.0.3</strong> (and most likely, earlier versions too) is not yet configured to recognise the <code>@SpringBootApplication</code> annotation.</p>
<p>For now, if the errors disturb you that much, then revert back to those three separate annotations. Otherwise, ignore <strong>Intellij</strong>...your dependency resolution is correctly configured, since your test passes.</p>
<p>Always remember...</p>
<blockquote>
<p>Man is always greater than machine.</p>
</blockquote> | {
"question_id": 26889970,
"question_date": "2014-11-12T15:00:56.690Z",
"question_score": 224,
"tags": "java|spring|intellij-idea|annotations|autowired",
"answer_id": 31891805,
"answer_date": "2015-08-08T09:46:03.227Z",
"answer_score": 247
} |
Please answer the following Stack Overflow question:
Title: Delete a single record from Entity Framework?
<p>I have a SQL Server table in Entity Framework named <code>employ</code> with a single key column named <code>ID</code>.</p>
<p>How do I delete a single record from the table using Entity Framework?</p> | <p>It's not necessary to query the object first, you can attach it to the context by its id.
Like this:</p>
<pre><code>var employer = new Employ { Id = 1 };
ctx.Employ.Attach(employer);
ctx.Employ.Remove(employer);
ctx.SaveChanges();
</code></pre>
<p>Alternatively, you can set the attached entry's state to deleted :</p>
<pre><code>var employer = new Employ { Id = 1 };
ctx.Entry(employer).State = EntityState.Deleted;
ctx.SaveChanges();
</code></pre> | {
"question_id": 17723276,
"question_date": "2013-07-18T12:20:22.293Z",
"question_score": 224,
"tags": "c#|sql-server|entity-framework",
"answer_id": 17723658,
"answer_date": "2013-07-18T12:37:11.100Z",
"answer_score": 405
} |
Please answer the following Stack Overflow question:
Title: The type or namespace name does not exist in the namespace 'System.Web.Mvc'
<p>Buiding MVC3 solution went well but have got an error in browser:</p>
<p>Compiler Error Message: CS0234: The type or namespace name 'Html' does not exist in the namespace 'System.Web.Mvc' (are you missing an assembly reference?)</p>
<pre><code>Source Error:
Line 25: <add namespace="System.Web.Mvc" />
Line 26: <!--<add namespace="System.Web.Mvc.Ajax" />-->
Line 27: <add namespace="System.Web.Mvc.Html" />
Line 28: <add namespace="System.Web.Routing" />
Line 29: <add namespace="System.Web.WebPages" />
</code></pre>
<p>I have installed packets for the solution with <code>NuGet</code> and set up for all projects <code>MVC3</code>. Does <code>MVC3</code> include libraries <code>System.Web.Mvc.Ajax</code>, <code>System.Web.Mvc.Html</code> and others? Why am I getting the error?</p>
<hr>
<p>In References folder, I have System.Web.Mvc</p>
<p><code>Runtime version: v4.0.30319</code>,</p>
<pre><code>Version: 3.0.0.0
</code></pre>
<hr>
<p>Web.config</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=152368
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
<add key="webpages:Version" value="1.0.0.0" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
<httpRuntime targetFramework="4.5" encoderType="System.Web.Security.AntiXss.AntiXssEncoder, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<machineKey compatibilityMode="Framework45" />
<profile defaultProvider="DefaultProfileProvider">
<providers>
<add name="DefaultProfileProvider" type="System.Web.Providers.DefaultProfileProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</profile>
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<connectionStrings>
<add name="EFDbContext" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=SportStore;Integrated Security=True;Pooling=False;" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.aspx">MSDN</a> the System.Web.Mvc namespace</p>
<p>file <code>packages.config</code>:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="EntityFramework" version="5.0.0-rc" />
<package id="jQuery" version="1.7.2" />
<package id="jQuery.UI.Combined" version="1.8.11" />
<package id="jQuery.Validation" version="1.9" />
<package id="Microsoft.AspNet.Mvc" version="3.0.20105.1" />
<package id="Microsoft.AspNet.Providers.Core" version="1.0" />
<package id="Microsoft.AspNet.Providers.LocalDB" version="1.0" />
<package id="Microsoft.AspNet.Razor" version="1.0.20105.408" />
<package id="Microsoft.AspNet.WebPages" version="1.0.20105.408" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" />
<package id="Modernizr" version="2.0.6" />
<package id="Moq" version="4.0.10827" />
<package id="Ninject" version="3.0.1.10" />
</packages>
</code></pre> | <p>Clean your solution and then set the property of those files to <code>Copy Local = True</code>.</p>
<p>To set the Copy Local property to True or False</p>
<p>In Solution Explorer, click the Show All Files button to display the References node.</p>
<ul>
<li>Open the References node for the project.</li>
<li>Right-click a reference in the References list, and click Properties.
The properties associated with that reference appear in a list in the Properties window.</li>
<li>In the Properties window, change the Copy Local property to True or False.</li>
</ul> | {
"question_id": 11071392,
"question_date": "2012-06-17T12:46:41.703Z",
"question_score": 224,
"tags": "c#|asp.net-mvc-3",
"answer_id": 13149587,
"answer_date": "2012-10-31T00:31:50.523Z",
"answer_score": 428
} |
Please answer the following Stack Overflow question:
Title: 'Property does not exist on type 'never'
<p>This is similar to <a href="https://stackoverflow.com/questions/40796374/property-x-does-not-exist-on-type-never">#40796374</a> but that is around types, while I am using interfaces.</p>
<p>Given the code below:</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>interface Foo {
name: string;
}
function go() {
let instance: Foo | null = null;
let mutator = () => {
instance = {
name: 'string'
};
};
mutator();
if (instance == null) {
console.log('Instance is null or undefined');
} else {
console.log(instance.name);
}
}</code></pre>
</div>
</div>
</p>
<p>I have an error saying 'Property 'name' does not exist on type 'never'.</p>
<p>I don't understand how instance could ever be a 'never'. Can anyone shed some light on this?</p> | <p>Because you are assigning <code>instance</code> to <code>null</code>. The compiler infers that it can never be anything other than <code>null</code>. So it assumes that the else block should never be executed so <code>instance</code> is typed as <code>never</code> in the else block.</p>
<p>Now if you don't declare it as the literal value <code>null</code>, and get it by any other means (ex: <code>let instance: Foo | null = getFoo();</code>), you will see that <code>instance</code> will be <code>null</code> inside the if block and <code>Foo</code> inside the else block.</p>
<p>Never type documentation: <a href="https://www.typescriptlang.org/docs/handbook/basic-types.html#never" rel="noreferrer">https://www.typescriptlang.org/docs/handbook/basic-types.html#never</a></p>
<p><strong>Edit:</strong></p>
<p>The issue in the updated example is actually an open issue with the compiler.
See:</p>
<p><a href="https://github.com/Microsoft/TypeScript/issues/11498" rel="noreferrer">https://github.com/Microsoft/TypeScript/issues/11498</a>
<a href="https://github.com/Microsoft/TypeScript/issues/12176" rel="noreferrer">https://github.com/Microsoft/TypeScript/issues/12176</a></p> | {
"question_id": 44147937,
"question_date": "2017-05-24T02:26:21.360Z",
"question_score": 224,
"tags": "typescript",
"answer_id": 44147953,
"answer_date": "2017-05-24T02:29:08.663Z",
"answer_score": 112
} |
Please answer the following Stack Overflow question:
Title: Creating an index on a table variable
<p>Can you create an index on a table variable in SQL Server 2000?</p>
<p>i.e. </p>
<pre><code>DECLARE @TEMPTABLE TABLE (
[ID] [int] NOT NULL PRIMARY KEY
,[Name] [nvarchar] (255) COLLATE DATABASE_DEFAULT NULL
)
</code></pre>
<p>Can I create an index on <code>Name</code>?</p> | <p>The question is tagged SQL Server 2000 but for the benefit of people developing on the latest version I'll address that first.</p>
<p><strong>SQL Server 2014</strong></p>
<p>In addition to the methods of adding constraint based indexes discussed below SQL Server 2014 also allows non unique indexes to be specified directly with inline syntax on table variable declarations. </p>
<p>Example syntax for that is below.</p>
<pre><code>/*SQL Server 2014+ compatible inline index syntax*/
DECLARE @T TABLE (
C1 INT INDEX IX1 CLUSTERED, /*Single column indexes can be declared next to the column*/
C2 INT INDEX IX2 NONCLUSTERED,
INDEX IX3 NONCLUSTERED(C1,C2) /*Example composite index*/
);
</code></pre>
<p>Filtered indexes and indexes with included columns can not currently be declared with this syntax however <strong>SQL Server 2016</strong> relaxes this a bit further. From CTP 3.1 it is now possible to declare filtered indexes for table variables. By RTM it <em>may</em> be the case that included columns are also allowed but the current position is that they <a href="https://connect.microsoft.com/SQLServer/Feedback/Details/2079552" rel="noreferrer">"will likely not make it into SQL16 due to resource constraints"</a></p>
<pre><code>/*SQL Server 2016 allows filtered indexes*/
DECLARE @T TABLE
(
c1 INT NULL INDEX ix UNIQUE WHERE c1 IS NOT NULL /*Unique ignoring nulls*/
)
</code></pre>
<hr>
<p><strong>SQL Server 2000 - 2012</strong></p>
<blockquote>
<p>Can I create a index on Name?</p>
</blockquote>
<p>Short answer: Yes.</p>
<pre><code>DECLARE @TEMPTABLE TABLE (
[ID] [INT] NOT NULL PRIMARY KEY,
[Name] [NVARCHAR] (255) COLLATE DATABASE_DEFAULT NULL,
UNIQUE NONCLUSTERED ([Name], [ID])
)
</code></pre>
<p>A more detailed answer is below.</p>
<p>Traditional tables in SQL Server can either have a clustered index or are structured as <a href="http://msdn.microsoft.com/en-us/library/hh213609.aspx" rel="noreferrer">heaps</a>. </p>
<p>Clustered indexes can either be declared as unique to disallow duplicate key values or default to non unique. If not unique then SQL Server silently adds a <a href="http://msdn.microsoft.com/en-us/library/ms190639%28v=sql.105%29.aspx" rel="noreferrer">uniqueifier</a> to any duplicate keys to make them unique.</p>
<p>Non clustered indexes can also be explicitly declared as unique. Otherwise for the non unique case SQL Server <a href="http://sqlblog.com/blogs/kalen_delaney/archive/2010/03/07/more-about-nonclustered-index-keys.aspx" rel="noreferrer">adds the row locator</a> (clustered index key or <a href="http://technet.microsoft.com/en-us/library/ms190696%28v=sql.105%29.aspx" rel="noreferrer">RID</a> for a heap) to all index keys (not just duplicates) this again ensures they are unique.</p>
<p>In SQL Server 2000 - 2012 indexes on table variables can only be created implicitly by creating a <code>UNIQUE</code> or <code>PRIMARY KEY</code> constraint. The difference between these constraint types are that the primary key must be on non nullable column(s). The columns participating in a unique constraint may be nullable. (though SQL Server's implementation of unique constraints in the presence of <code>NULL</code>s is not per that specified in the SQL Standard). Also a table can only have one primary key but multiple unique constraints.</p>
<p>Both of these logical constraints are physically implemented with a unique index. If not explicitly specified otherwise the <code>PRIMARY KEY</code> will become the clustered index and unique constraints non clustered but this behavior can be overridden by specifying <code>CLUSTERED</code> or <code>NONCLUSTERED</code> explicitly with the constraint declaration (Example syntax)</p>
<pre><code>DECLARE @T TABLE
(
A INT NULL UNIQUE CLUSTERED,
B INT NOT NULL PRIMARY KEY NONCLUSTERED
)
</code></pre>
<p>As a result of the above the following indexes can be implicitly created on table variables in SQL Server 2000 - 2012.</p>
<pre><code>+-------------------------------------+-------------------------------------+
| Index Type | Can be created on a table variable? |
+-------------------------------------+-------------------------------------+
| Unique Clustered Index | Yes |
| Nonunique Clustered Index | |
| Unique NCI on a heap | Yes |
| Non Unique NCI on a heap | |
| Unique NCI on a clustered index | Yes |
| Non Unique NCI on a clustered index | Yes |
+-------------------------------------+-------------------------------------+
</code></pre>
<p>The last one requires a bit of explanation. In the table variable definition at the beginning of this answer the <strong>non unique</strong> non clustered index on <code>Name</code> is simulated by a <strong>unique</strong> index on <code>Name,Id</code> (recall that SQL Server would silently add the clustered index key to the non unique NCI key anyway).</p>
<p>A non unique clustered index can also be achieved by manually adding an <code>IDENTITY</code> column to act as a uniqueifier.</p>
<pre><code>DECLARE @T TABLE
(
A INT NULL,
B INT NULL,
C INT NULL,
Uniqueifier INT NOT NULL IDENTITY(1,1),
UNIQUE CLUSTERED (A,Uniqueifier)
)
</code></pre>
<p>But this is not an accurate simulation of how a non unique clustered index would normally actually be implemented in SQL Server as this adds the "Uniqueifier" to all rows. Not just those that require it.</p> | {
"question_id": 886050,
"question_date": "2009-05-20T03:46:17.267Z",
"question_score": 224,
"tags": "sql|sql-server|tsql|indexing|table-variable",
"answer_id": 17385085,
"answer_date": "2013-06-29T21:59:24.203Z",
"answer_score": 427
} |
Please answer the following Stack Overflow question:
Title: Display a decimal in scientific notation
<p>How can I display <code>Decimal('40800000000.00000000000000')</code> as <code>'4.08E+10'</code>?</p>
<p>I've tried this:</p>
<pre><code>>>> '%E' % Decimal('40800000000.00000000000000')
'4.080000E+10'
</code></pre>
<p>But it has those extra 0's.</p> | <pre><code>from decimal import Decimal
'%.2E' % Decimal('40800000000.00000000000000')
# returns '4.08E+10'
</code></pre>
<p>In your '40800000000.00000000000000' there are many more significant zeros that have the same meaning as any other digit. That's why you have to tell explicitly where you want to stop.</p>
<p>If you want to remove all trailing zeros automatically, you can try:</p>
<pre><code>def format_e(n):
a = '%E' % n
return a.split('E')[0].rstrip('0').rstrip('.') + 'E' + a.split('E')[1]
format_e(Decimal('40800000000.00000000000000'))
# '4.08E+10'
format_e(Decimal('40000000000.00000000000000'))
# '4E+10'
format_e(Decimal('40812300000.00000000000000'))
# '4.08123E+10'
</code></pre> | {
"question_id": 6913532,
"question_date": "2011-08-02T14:16:34.703Z",
"question_score": 224,
"tags": "python|string-formatting|number-formatting|scientific-notation",
"answer_id": 6913576,
"answer_date": "2011-08-02T14:19:57.293Z",
"answer_score": 199
} |
Please answer the following Stack Overflow question:
Title: How do I put variables inside javascript strings?
<pre><code>s = 'hello %s, how are you doing' % (my_name)
</code></pre>
<p>That's how you do it in python. How can you do that in javascript/node.js?</p> | <p>Note, from 2015 onwards, just use backticks for templating</p>
<p><a href="https://stackoverflow.com/a/37245773/294884">https://stackoverflow.com/a/37245773/294884</a></p>
<pre><code>let a = `hello ${name}` // NOTE!!!!!!!! ` not ' or "
</code></pre>
<p>Note that it is a <strong>backtick</strong>, not a quote.</p>
<hr />
<p>If you want to have something similar, you could create a function:</p>
<pre><code>function parse(str) {
var args = [].slice.call(arguments, 1),
i = 0;
return str.replace(/%s/g, () => args[i++]);
}
</code></pre>
<p>Usage:</p>
<pre><code>s = parse('hello %s, how are you doing', my_name);
</code></pre>
<p>This is only a simple example and does not take into account different kinds of data types (like <code>%i</code>, etc) or escaping of <code>%s</code>. But I hope it gives you some idea. I'm pretty sure there are also libraries out there which provide a function like this.</p> | {
"question_id": 7790811,
"question_date": "2011-10-17T07:53:18.150Z",
"question_score": 224,
"tags": "javascript|string|node.js",
"answer_id": 7790858,
"answer_date": "2011-10-17T07:58:13.437Z",
"answer_score": 167
} |
Please answer the following Stack Overflow question:
Title: Access Controller method from another controller in Laravel 5
<p>I have two controllers <code>SubmitPerformanceController</code> and <code>PrintReportController</code>.</p>
<p>In <code>PrintReportController</code> I have a method called <code>getPrintReport</code>.</p>
<p>How to access this method in <code>SubmitPerformanceController</code>?</p> | <p>You can access your controller method like this:
</p>
<pre class="lang-php prettyprint-override"><code>app('App\Http\Controllers\PrintReportController')->getPrintReport();
</code></pre>
<p>This will work, but it's bad in terms of code organisation (remember to use the right namespace for your <code>PrintReportController</code>)</p>
<p>You can extend the <code>PrintReportController</code> so <code>SubmitPerformanceController</code> will inherit that method</p>
<pre class="lang-php prettyprint-override"><code>class SubmitPerformanceController extends PrintReportController {
// ....
}
</code></pre>
<p>But this will also inherit all other methods from <code>PrintReportController</code>. </p>
<p>The best approach will be to create a <code>trait</code> (e.g. in <code>app/Traits</code>), implement the logic there and tell your controllers to use it:</p>
<pre class="lang-php prettyprint-override"><code>trait PrintReport {
public function getPrintReport() {
// .....
}
}
</code></pre>
<p>Tell your controllers to use this trait:</p>
<pre class="lang-php prettyprint-override"><code>class PrintReportController extends Controller {
use PrintReport;
}
class SubmitPerformanceController extends Controller {
use PrintReport;
}
</code></pre>
<p>Both solutions make <code>SubmitPerformanceController</code> to have <code>getPrintReport</code> method so you can call it with <code>$this->getPrintReport();</code> from within the controller or directly as a route (if you mapped it in the <code>routes.php</code>)</p>
<p>You can read more about traits <a href="https://php.net/manual/en/language.oop5.traits.php" rel="noreferrer">here</a>.</p> | {
"question_id": 30365169,
"question_date": "2015-05-21T05:21:18.640Z",
"question_score": 224,
"tags": "php|laravel|laravel-5|controller",
"answer_id": 30365349,
"answer_date": "2015-05-21T05:36:00.163Z",
"answer_score": 459
} |
Please answer the following Stack Overflow question:
Title: How to limit google autocomplete results to City and Country only
<p>I am using google autocomplete places javascript to return suggested results for my searchbox , what I need is to only show the city and the country related to the characters entered but google api will give a lot of general places results which I dont need , so how to limit the result to show only city and the country .</p>
<p>I am using the following Example:</p>
<pre><code><html>
<head>
<style type="text/css">
body {
font-family: sans-serif;
font-size: 14px;
}
</style>
<title>Google Maps JavaScript API v3 Example: Places Autocomplete</title>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div>
<input id="searchTextField" type="text" size="50" placeholder="Enter a location" autocomplete="on">
</div>
</body>
</html>
</code></pre> | <p>You can try the country restriction</p>
<pre><code>function initialize() {
var options = {
types: ['(cities)'],
componentRestrictions: {country: "us"}
};
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input, options);
}
</code></pre>
<h2>More info:</h2>
<p><strong><a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2" rel="noreferrer">ISO 3166-1 alpha-2</a></strong> can be used to restrict results to specific groups. Currently, you can use componentRestrictions to filter by country.<br /><br />
The country must be passed as as a two character, ISO 3166-1 Alpha-2 compatible country code.
<hr />
<a href="http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2" rel="noreferrer">Officially assigned country codes</a></p> | {
"question_id": 8282026,
"question_date": "2011-11-26T22:12:44.040Z",
"question_score": 224,
"tags": "javascript|autocomplete|google-maps-api-3",
"answer_id": 10170421,
"answer_date": "2012-04-16T07:52:41.170Z",
"answer_score": 420
} |
Please answer the following Stack Overflow question:
Title: How to use Java property files?
<p>I have a list of key/value pairs of configuration values I want to store as Java property files, and later load and iterate through.</p>
<p>Questions:</p>
<ul>
<li>Do I need to store the file in the same package as the class which will load them, or is there any specific location where it should be placed?</li>
<li>Does the file need to end in any specific extension or is <code>.txt</code> OK?</li>
<li>How can I load the file in the code</li>
<li>And how can I iterate through the values inside?</li>
</ul> | <p>You can pass an InputStream to the Property, so your file can pretty much be anywhere, and called anything.</p>
<pre><code>Properties properties = new Properties();
try {
properties.load(new FileInputStream("path/filename"));
} catch (IOException e) {
...
}
</code></pre>
<p>Iterate as:</p>
<pre><code>for(String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
System.out.println(key + " => " + value);
}
</code></pre> | {
"question_id": 1318347,
"question_date": "2009-08-23T11:31:48.430Z",
"question_score": 224,
"tags": "java|properties",
"answer_id": 1318391,
"answer_date": "2009-08-23T11:52:31.243Z",
"answer_score": 253
} |
Please answer the following Stack Overflow question:
Title: How to target only IE (any version) within a stylesheet?
<p>I have an inherited project and there are places where it's an utter mess. This is one of them. I need to target only IE (any version). </p>
<pre><code>#nav li {
float: left;
height: 54px;
background: #4f5151;
display: table;
border-left: 1px solid grey;
}
</code></pre>
<p>To be clear: <em>Inside</em> the embedded stylesheet and <em>without</em> adding ID's or classes to the tags in the html, I need to apply the border style <em>only</em> if the user is using IE. How can I do this? </p>
<p>Edit: found a solution for Firefox, editing question to reflect this.</p> | <p><strong>Internet Explorer 9 and lower :</strong>
You could use conditional comments to load an IE-specific stylesheet for any version (or combination of versions) that you wanted to specifically target.like below using external stylesheet.</p>
<pre><code><!--[if IE]>
<link rel="stylesheet" type="text/css" href="all-ie-only.css" />
<![endif]-->
</code></pre>
<p>However, beginning in version 10, conditional comments are no longer supported in IE.</p>
<p><strong>Internet Explorer 10 & 11 :</strong>
Create a media query using -ms-high-contrast, in which you place your IE 10 and 11-specific CSS styles. Because -ms-high-contrast is Microsoft-specific (and only available in IE 10+), it will only be parsed in Internet Explorer 10 and greater.</p>
<pre><code>@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
/* IE10+ CSS styles go here */
}
</code></pre>
<p><strong>Microsoft Edge 12 :</strong> Can use the @supports rule
<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/@supports">Here is a link with all the info about this rule</a></p>
<pre><code>@supports (-ms-accelerator:true) {
/* IE Edge 12+ CSS styles go here */
}
</code></pre>
<hr>
<p><em>Inline rule IE8 detection</em></p>
<p>I have 1 more option but it is only detect IE8 and below version.</p>
<pre><code> /* For IE css hack */
margin-top: 10px\9 /* apply to all ie from 8 and below */
*margin-top:10px; /* apply to ie 7 and below */
_margin-top:10px; /* apply to ie 6 and below */
</code></pre>
<p>As you specefied for embeded stylesheet. I think you need to use media query and condition comment for below version.</p> | {
"question_id": 28417056,
"question_date": "2015-02-09T18:48:51.387Z",
"question_score": 224,
"tags": "css",
"answer_id": 28419263,
"answer_date": "2015-02-09T21:00:39.040Z",
"answer_score": 487
} |
Please answer the following Stack Overflow question:
Title: python pandas: apply a function with arguments to a series
<p>I want to apply a function with arguments to a series in python pandas:</p>
<pre><code>x = my_series.apply(my_function, more_arguments_1)
y = my_series.apply(my_function, more_arguments_2)
...
</code></pre>
<p>The <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html" rel="noreferrer">documentation</a> describes support for an apply method, but it doesn't accept any arguments. Is there a different method that accepts arguments? Alternatively, am I missing a simple workaround?</p>
<p><strong>Update (October 2017):</strong> Note that since this question was originally asked that pandas <code>apply()</code> has been updated to handle positional and keyword arguments and the documentation link above now reflects that and shows how to include either type of argument.</p> | <p>Newer versions of pandas <em>do</em> allow you to pass extra arguments (see the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.apply.html#pandas.Series.apply" rel="noreferrer">new documentation</a>). So now you can do:</p>
<pre><code>my_series.apply(your_function, args=(2,3,4), extra_kw=1)
</code></pre>
<p>The positional arguments are added <em>after</em> the element of the series.</p>
<hr>
<p>For older version of pandas:</p>
<p>The documentation explains this clearly. The apply method accepts a python function which should have a single parameter. If you want to pass more parameters you should use <code>functools.partial</code> as suggested by Joel Cornett in his comment.</p>
<p>An example:</p>
<pre><code>>>> import functools
>>> import operator
>>> add_3 = functools.partial(operator.add,3)
>>> add_3(2)
5
>>> add_3(7)
10
</code></pre>
<p>You can also pass keyword arguments using <code>partial</code>.</p>
<p>Another way would be to create a lambda:</p>
<pre><code>my_series.apply((lambda x: your_func(a,b,c,d,...,x)))
</code></pre>
<p>But I think using <code>partial</code> is better.</p> | {
"question_id": 12182744,
"question_date": "2012-08-29T16:46:39.007Z",
"question_score": 224,
"tags": "python|pandas|apply",
"answer_id": 12183507,
"answer_date": "2012-08-29T17:36:10.973Z",
"answer_score": 245
} |
Please answer the following Stack Overflow question:
Title: How to make HTML Text unselectable
<p>I would like to add text to my webpage as a label and make it unselectable.</p>
<p>In other words, When the mouse cursor is over the text I would like it to not turn into a text selecting cursor at all.</p>
<p>A good example of what I'm trying to achieve is the buttons on this website (Questions,Tags,Users,...)</p> | <p>You can't do this with plain vanilla HTML, so JSF can't do much for you here as well.</p>
<p>If you're targeting <a href="http://caniuse.com/#feat=user-select-none" rel="noreferrer">decent browsers</a> only, then just make use of CSS3:</p>
<pre class="lang-css prettyprint-override"><code>.unselectable {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
</code></pre>
<pre class="lang-html prettyprint-override"><code><label class="unselectable">Unselectable label</label>
</code></pre>
<p>If you'd like to cover older browsers as well, then consider this JavaScript fallback:</p>
<pre><code><!doctype html>
<html lang="en">
<head>
<title>SO question 2310734</title>
<script>
window.onload = function() {
var labels = document.getElementsByTagName('label');
for (var i = 0; i < labels.length; i++) {
disableSelection(labels[i]);
}
};
function disableSelection(element) {
if (typeof element.onselectstart != 'undefined') {
element.onselectstart = function() { return false; };
} else if (typeof element.style.MozUserSelect != 'undefined') {
element.style.MozUserSelect = 'none';
} else {
element.onmousedown = function() { return false; };
}
}
</script>
</head>
<body>
<label>Try to select this</label>
</body>
</html>
</code></pre>
<p>If you're already using <a href="http://jquery.com" rel="noreferrer">jQuery</a>, then here's another example which adds a new function <code>disableSelection()</code> to jQuery so that you can use it anywhere in your jQuery code:</p>
<pre><code><!doctype html>
<html lang="en">
<head>
<title>SO question 2310734 with jQuery</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$.fn.extend({
disableSelection: function() {
this.each(function() {
if (typeof this.onselectstart != 'undefined') {
this.onselectstart = function() { return false; };
} else if (typeof this.style.MozUserSelect != 'undefined') {
this.style.MozUserSelect = 'none';
} else {
this.onmousedown = function() { return false; };
}
});
}
});
$(document).ready(function() {
$('label').disableSelection();
});
</script>
</head>
<body>
<label>Try to select this</label>
</body>
</html>
</code></pre> | {
"question_id": 2310734,
"question_date": "2010-02-22T12:12:23.317Z",
"question_score": 224,
"tags": "html|css|cross-browser|highlighting|textselection",
"answer_id": 2310809,
"answer_date": "2010-02-22T12:31:44.517Z",
"answer_score": 354
} |
Please answer the following Stack Overflow question:
Title: How can I save a base64-encoded image to disk?
<p>My Express app is receiving a base64-encoded PNG from the browser (generated from canvas with toDataURL() ) and writing it to a file. But the file isn't a valid image file, and the "file" utility simply identifies it as "data".</p>
<pre><code>var body = req.rawBody,
base64Data = body.replace(/^data:image\/png;base64,/,""),
binaryData = new Buffer(base64Data, 'base64').toString('binary');
require("fs").writeFile("out.png", binaryData, "binary", function(err) {
console.log(err); // writes out file without error, but it's not a valid image
});
</code></pre> | <p>I think you are converting the data a bit more than you need to. Once you create the buffer with the proper encoding, you just need to write the buffer to the file.</p>
<pre><code>var base64Data = req.rawBody.replace(/^data:image\/png;base64,/, "");
require("fs").writeFile("out.png", base64Data, 'base64', function(err) {
console.log(err);
});
</code></pre>
<p>new Buffer(..., 'base64') will convert the input string to a Buffer, which is just an array of bytes, by interpreting the input as a base64 encoded string. Then you can just write that byte array to the file.</p>
<h3>Update</h3>
<p>As mentioned in the comments, <code>req.rawBody</code> is no longer a thing. If you are using <code>express</code>/<code>connect</code> then you should use the <code>bodyParser()</code> middleware and use <code>req.body</code>, and if you are doing this using standard Node then you need to aggregate the incoming <code>data</code> event <code>Buffer</code> objects and do this image data parsing in the <code>end</code> callback.</p> | {
"question_id": 6926016,
"question_date": "2011-08-03T11:53:05.477Z",
"question_score": 224,
"tags": "image|node.js|base64|binaryfiles",
"answer_id": 6933413,
"answer_date": "2011-08-03T21:17:26.427Z",
"answer_score": 409
} |
Please answer the following Stack Overflow question:
Title: Test if something is not undefined in JavaScript
<p>I'm checking <code>if(response[0].title !== undefined)</code>, but I get the error:</p>
<blockquote>
<p>Uncaught TypeError: Cannot read property 'title' of undefined.</p>
</blockquote> | <p><code>response[0]</code> is not defined, check if it is defined and then check for its property title.</p>
<pre><code>if(typeof response[0] !== 'undefined' && typeof response[0].title !== 'undefined'){
//Do something
}
</code></pre> | {
"question_id": 7041123,
"question_date": "2011-08-12T13:56:27.347Z",
"question_score": 224,
"tags": "javascript|undefined",
"answer_id": 7041143,
"answer_date": "2011-08-12T13:58:08.387Z",
"answer_score": 344
} |
Please answer the following Stack Overflow question:
Title: Fastest way to check if string contains only digits in C#
<p>I know a few ways of how to check if a string contains only digits:<br />
RegEx, <code>int.parse</code>, <code>tryparse</code>, looping, etc.</p>
<p>Can anyone tell me what the <em>fastest</em> way to check is?</p>
<p>I need only to <strong>CHECK</strong> the value, no need to actually parse it.</p>
<p>By "digit" I mean specifically ASCII digits: <code>0 1 2 3 4 5 6 7 8 9</code>.</p>
<p>This is not the same question as <a href="https://stackoverflow.com/questions/894263/how-do-i-identify-if-a-string-is-a-number">Identify if a string is a number</a>, since this question is not only about how to identify, but also about what the <strong>fastest</strong> method for doing so is.</p> | <pre><code>bool IsDigitsOnly(string str)
{
foreach (char c in str)
{
if (c < '0' || c > '9')
return false;
}
return true;
}
</code></pre>
<p>Will probably be the fastest way to do it.</p> | {
"question_id": 7461080,
"question_date": "2011-09-18T11:10:50.240Z",
"question_score": 224,
"tags": "c#|string|performance",
"answer_id": 7461095,
"answer_date": "2011-09-18T11:13:54.673Z",
"answer_score": 316
} |
Please answer the following Stack Overflow question:
Title: Nginx 403 forbidden for all files
<p>I have nginx installed with PHP-FPM on a CentOS 5 box, but am struggling to get it to serve any of my files - whether PHP or not.</p>
<p>Nginx is running as www-data:www-data, and the default "Welcome to nginx on EPEL" site (owned by root:root with 644 permissions) loads fine.</p>
<p>The nginx configuration file has an include directive for <i>/etc/nginx/sites-enabled/*.conf,</i> and I have a configuration file <em>example.com.conf</em>, thus:</p>
<pre><code>server {
listen 80;
Virtual Host Name
server_name www.example.com example.com;
location / {
root /home/demo/sites/example.com/public_html;
index index.php index.htm index.html;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param PATH_INFO $fastcgi_script_name;
fastcgi_param SCRIPT_FILENAME /home/demo/sites/example.com/public_html$fastcgi_script_name;
include fastcgi_params;
}
}
</code></pre>
<p>Despite public_html being owned by www-data:www-data with 2777 file permissions, this site fails to serve any content -</p>
<pre><code> [error] 4167#0: *4 open() "/home/demo/sites/example.com/public_html/index.html" failed (13: Permission denied), client: XX.XXX.XXX.XX, server: www.example.com, request: "GET /index.html HTTP/1.1", host: "www.example.com"
</code></pre>
<p>I've found numerous other posts with users getting 403s from nginx, but most that I have seen involve either more complex setups with Ruby/Passenger (which in the past I've actually succeeded with) or are only receiving errors when the upstream PHP-FPM is involved, so they seem to be of little help.</p>
<p>Have I done something silly here?</p> | <p>One permission requirement that is often overlooked is a user needs x permissions in every parent directory of a file to access that file. Check the permissions on /, /home, /home/demo, etc. for www-data x access. My guess is that /home is probably 770 and www-data can't chdir through it to get to any subdir. If it is, try chmod o+x /home (or whatever dir is denying the request).</p>
<p>EDIT: To easily display all the permissions on a path, you can use <code>namei -om /path/to/check</code></p> | {
"question_id": 6795350,
"question_date": "2011-07-22T19:53:51.957Z",
"question_score": 224,
"tags": "nginx|centos|http-status-code-403|php",
"answer_id": 6796648,
"answer_date": "2011-07-22T22:11:38.937Z",
"answer_score": 371
} |
Please answer the following Stack Overflow question:
Title: Capture characters from standard input without waiting for enter to be pressed
<p>I can never remember how I do this because it comes up so infrequently for me. But in C or C++, what is the best way to read a character from standard input without waiting for a newline (press enter).</p>
<p>Also ideally it wouldn't echo the input character to the screen. I just want to capture keystrokes with out effecting the console screen.</p> | <p>That's not possible in a portable manner in pure C++, because it depends too much on the terminal used that may be connected with <code>stdin</code> (they are usually line buffered). You can, however use a library for that:</p>
<ol>
<li><p>conio available with Windows compilers. Use the <code>_getch()</code> function to give you a character without waiting for the Enter key. I'm not a frequent Windows developer, but I've seen my classmates just include <code><conio.h></code> and use it. See <a href="http://en.wikipedia.org/wiki/Conio.h" rel="noreferrer"><code>conio.h</code></a> at Wikipedia. It lists <code>getch()</code>, which is declared deprecated in Visual C++. </p></li>
<li><p>curses available for Linux. Compatible curses implementations are available for Windows too. It has also a <code>getch()</code> function. (try <code>man getch</code> to view its manpage). See <a href="http://en.wikipedia.org/wiki/Curses_%28programming_library%29" rel="noreferrer">Curses</a> at Wikipedia. </p></li>
</ol>
<p>I would recommend you to use curses if you aim for cross platform compatibility. That said, I'm sure there are functions that you can use to switch off line buffering (I believe that's called "raw mode", as opposed to "cooked mode" - look into <code>man stty</code>). Curses would handle that for you in a portable manner, if I'm not mistaken. </p> | {
"question_id": 421860,
"question_date": "2009-01-07T20:04:16.750Z",
"question_score": 224,
"tags": "c++|c|inputstream",
"answer_id": 421871,
"answer_date": "2009-01-07T20:08:54.710Z",
"answer_score": 124
} |
Please answer the following Stack Overflow question:
Title: Circle-Rectangle collision detection (intersection)
<p>How can I tell whether a circle and a rectangle intersect in 2D Euclidean space? (i.e. classic 2D geometry)</p> | <p>There are only two cases when the circle intersects with the rectangle:</p>
<ul>
<li>Either the circle's centre lies inside the rectangle, or</li>
<li>One of the edges of the rectangle has a point in the circle.</li>
</ul>
<p>Note that this does not require the rectangle to be axis-parallel. </p>
<p><a href="https://i.stack.imgur.com/fdDv1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/fdDv1.png" alt="Some different ways a circle and rectangle may intersect"></a></p>
<p>(One way to see this: if none of the edges has a point in the circle (if all the edges are completely "outside" the circle), then the only way the circle can still intersect the polygon is if it lies completely inside the polygon.)</p>
<p>With that insight, something like the following will work, where the circle has centre <code>P</code> and radius <code>R</code>, and the rectangle has vertices <code>A</code>, <code>B</code>, <code>C</code>, <code>D</code> in that order (not complete code):</p>
<pre class="lang-py prettyprint-override"><code>def intersect(Circle(P, R), Rectangle(A, B, C, D)):
S = Circle(P, R)
return (pointInRectangle(P, Rectangle(A, B, C, D)) or
intersectCircle(S, (A, B)) or
intersectCircle(S, (B, C)) or
intersectCircle(S, (C, D)) or
intersectCircle(S, (D, A)))
</code></pre>
<p>If you're writing any geometry you probably have the above functions in your library already. Otherwise, <code>pointInRectangle()</code> can be implemented in several ways; any of the general <a href="http://en.wikipedia.org/wiki/Point_in_polygon" rel="noreferrer">point in polygon</a> methods will work, but for a rectangle you can just check whether this works:</p>
<pre><code>0 ≤ AP·AB ≤ AB·AB and 0 ≤ AP·AD ≤ AD·AD
</code></pre>
<p>And <code>intersectCircle()</code> is easy to implement too: one way would be to check if the foot of the perpendicular from <code>P</code> to the line is close enough and between the endpoints, and check the endpoints otherwise.</p>
<p>The cool thing is that the <em>same</em> idea works not just for rectangles but for the intersection of a circle with any <a href="http://en.wikipedia.org/wiki/Simple_polygon" rel="noreferrer">simple polygon</a> — doesn't even have to be convex!</p> | {
"question_id": 401847,
"question_date": "2008-12-30T23:35:02.983Z",
"question_score": 224,
"tags": "geometry|collision-detection",
"answer_id": 402019,
"answer_date": "2008-12-31T01:17:13.433Z",
"answer_score": 220
} |
Please answer the following Stack Overflow question:
Title: How can I initialize a MySQL database with schema in a Docker container?
<p>I am trying to create a container with a MySQL database and add a schema to these database.</p>
<p>My current Dockerfile is:</p>
<pre><code>FROM mysql
MAINTAINER (me) <email>
# Copy the database schema to the /data directory
COPY files/epcis_schema.sql /data/epcis_schema.sql
# Change the working directory
WORKDIR data
CMD mysql -u $MYSQL_USER -p $MYSQL_PASSWORD $MYSQL_DATABASE < epcis_schema.sql
</code></pre>
<p>In order to create the container I am following the documentation provided on Docker and executing this command:</p>
<pre><code>docker run --name ${CONTAINER_NAME} -e MYSQL_ROOT_PASSWORD=${DB_ROOT_PASSWORD} -e MYSQL_USER=${DB_USER} -e MYSQL_PASSWORD=${DB_USER_PASSWORD} -e MYSQL_DATABASE=${DB_NAME} -d mvpgomes/epcisdb
</code></pre>
<p>But when I execute this command the Container is not created and in the Container status it is possible to see that the CMD was not executed successfully, in fact only the <code>mysql</code> command is executed.</p>
<p>Anyway, is there a way to initialize the database with the schema or do I need to perform these operations manually?</p> | <p>I am sorry for this super long answer, but, you have a little way to go to get where you want. I will say that normally you wouldn't put the storage for the database in the same container as the database itself, you would either mount a host volume so that the data persists on the docker host, or, perhaps a container could be used to hold the data (/var/lib/mysql). Also, I am new to mysql, so, this might not be super efficient. That said...</p>
<p>I think there may be a few issues here. The Dockerfile is used to create an image. You need to execute the build step. At a minimum, from the directory that contains the Dockerfile you would do something like :</p>
<pre><code>docker build .
</code></pre>
<p>The Dockerfile describes the image to create. I don't know much about mysql (I am a postgres fanboy), but, I did a search around the interwebs for 'how do i initialize a mysql docker container'. First I created a new directory to work in, I called it mdir, then I created a files directory which I deposited a epcis_schema.sql file which creates a database and a single table:</p>
<pre><code>create database test;
use test;
CREATE TABLE testtab
(
id INTEGER AUTO_INCREMENT,
name TEXT,
PRIMARY KEY (id)
) COMMENT='this is my test table';
</code></pre>
<p>Then I created a script called init_db in the files directory:</p>
<pre><code>#!/bin/bash
# Initialize MySQL database.
# ADD this file into the container via Dockerfile.
# Assuming you specify a VOLUME ["/var/lib/mysql"] or `-v /var/lib/mysql` on the `docker run` command…
# Once built, do e.g. `docker run your_image /path/to/docker-mysql-initialize.sh`
# Again, make sure MySQL is persisting data outside the container for this to have any effect.
set -e
set -x
mysql_install_db
# Start the MySQL daemon in the background.
/usr/sbin/mysqld &
mysql_pid=$!
until mysqladmin ping >/dev/null 2>&1; do
echo -n "."; sleep 0.2
done
# Permit root login without password from outside container.
mysql -e "GRANT ALL ON *.* TO root@'%' IDENTIFIED BY '' WITH GRANT OPTION"
# create the default database from the ADDed file.
mysql < /tmp/epcis_schema.sql
# Tell the MySQL daemon to shutdown.
mysqladmin shutdown
# Wait for the MySQL daemon to exit.
wait $mysql_pid
# create a tar file with the database as it currently exists
tar czvf default_mysql.tar.gz /var/lib/mysql
# the tarfile contains the initialized state of the database.
# when the container is started, if the database is empty (/var/lib/mysql)
# then it is unpacked from default_mysql.tar.gz from
# the ENTRYPOINT /tmp/run_db script
</code></pre>
<p>(most of this script was lifted from here: <a href="https://gist.github.com/pda/9697520">https://gist.github.com/pda/9697520</a>)</p>
<p>Here is the files/run_db script I created:</p>
<pre><code># start db
set -e
set -x
# first, if the /var/lib/mysql directory is empty, unpack it from our predefined db
[ "$(ls -A /var/lib/mysql)" ] && echo "Running with existing database in /var/lib/mysql" || ( echo 'Populate initial db'; tar xpzvf default_mysql.tar.gz )
/usr/sbin/mysqld
</code></pre>
<p>Finally, the Dockerfile to bind them all:</p>
<pre><code>FROM mysql
MAINTAINER (me) <email>
# Copy the database schema to the /data directory
ADD files/run_db files/init_db files/epcis_schema.sql /tmp/
# init_db will create the default
# database from epcis_schema.sql, then
# stop mysqld, and finally copy the /var/lib/mysql directory
# to default_mysql_db.tar.gz
RUN /tmp/init_db
# run_db starts mysqld, but first it checks
# to see if the /var/lib/mysql directory is empty, if
# it is it is seeded with default_mysql_db.tar.gz before
# the mysql is fired up
ENTRYPOINT "/tmp/run_db"
</code></pre>
<p>So, I cd'ed to my mdir directory (which has the Dockerfile along with the files directory). I then run the command:</p>
<pre><code>docker build --no-cache .
</code></pre>
<p>You should see output like this:</p>
<pre><code>Sending build context to Docker daemon 7.168 kB
Sending build context to Docker daemon
Step 0 : FROM mysql
---> 461d07d927e6
Step 1 : MAINTAINER (me) <email>
---> Running in 963e8de55299
---> 2fd67c825c34
Removing intermediate container 963e8de55299
Step 2 : ADD files/run_db files/init_db files/epcis_schema.sql /tmp/
---> 81871189374b
Removing intermediate container 3221afd8695a
Step 3 : RUN /tmp/init_db
---> Running in 8dbdf74b2a79
+ mysql_install_db
2015-03-19 16:40:39 12 [Note] InnoDB: Using atomics to ref count buffer pool pages
...
/var/lib/mysql/ib_logfile0
---> 885ec2f1a7d5
Removing intermediate container 8dbdf74b2a79
Step 4 : ENTRYPOINT "/tmp/run_db"
---> Running in 717ed52ba665
---> 7f6d5215fe8d
Removing intermediate container 717ed52ba665
Successfully built 7f6d5215fe8d
</code></pre>
<p>You now have an image '7f6d5215fe8d'. I could run this image:</p>
<pre><code>docker run -d 7f6d5215fe8d
</code></pre>
<p>and the image starts, I see an instance string:</p>
<pre><code>4b377ac7397ff5880bc9218abe6d7eadd49505d50efb5063d6fab796ee157bd3
</code></pre>
<p>I could then 'stop' it, and restart it.</p>
<pre><code>docker stop 4b377
docker start 4b377
</code></pre>
<p>If you look at the logs, the first line will contain:</p>
<pre><code>docker logs 4b377
Populate initial db
var/lib/mysql/
...
</code></pre>
<p>Then, at the end of the logs:</p>
<pre><code>Running with existing database in /var/lib/mysql
</code></pre>
<p>These are the messages from the /tmp/run_db script, the first one indicates that the database was unpacked from the saved (initial) version, the second one indicates that the database was already there, so the existing copy was used.</p>
<p>Here is a ls -lR of the directory structure I describe above. Note that the init_db and run_db are scripts with the execute bit set:</p>
<pre><code>gregs-air:~ gfausak$ ls -Rl mdir
total 8
-rw-r--r-- 1 gfausak wheel 534 Mar 19 11:13 Dockerfile
drwxr-xr-x 5 gfausak staff 170 Mar 19 11:24 files
mdir/files:
total 24
-rw-r--r-- 1 gfausak staff 126 Mar 19 11:14 epcis_schema.sql
-rwxr-xr-x 1 gfausak staff 1226 Mar 19 11:16 init_db
-rwxr-xr-x 1 gfausak staff 284 Mar 19 11:23 run_db
</code></pre> | {
"question_id": 29145370,
"question_date": "2015-03-19T13:04:44.693Z",
"question_score": 224,
"tags": "mysql|docker|database-schema",
"answer_id": 29150538,
"answer_date": "2015-03-19T16:54:30.590Z",
"answer_score": 122
} |
Please answer the following Stack Overflow question:
Title: Simpler way to create dictionary of separate variables?
<p>I would like to be able to get the name of a variable as a string but I don't know if Python has that much introspection capabilities. Something like:</p>
<pre><code>>>> print(my_var.__name__)
'my_var'
</code></pre>
<p>I want to do that because I have a bunch of variables I'd like to turn into a dictionary like :</p>
<pre><code>bar = True
foo = False
>>> my_dict = dict(bar=bar, foo=foo)
>>> print my_dict
{'foo': False, 'bar': True}
</code></pre>
<p>But I'd like something more automatic than that.</p>
<p>Python have <code>locals()</code> and <code>vars()</code>, so I guess there is a way.</p> | <p>Are you trying to do this?</p>
<pre><code>dict( (name,eval(name)) for name in ['some','list','of','vars'] )
</code></pre>
<p>Example </p>
<pre><code>>>> some= 1
>>> list= 2
>>> of= 3
>>> vars= 4
>>> dict( (name,eval(name)) for name in ['some','list','of','vars'] )
{'list': 2, 'some': 1, 'vars': 4, 'of': 3}
</code></pre> | {
"question_id": 2553354,
"question_date": "2010-03-31T13:39:10.733Z",
"question_score": 224,
"tags": "python|string|variables",
"answer_id": 2553532,
"answer_date": "2010-03-31T13:59:54.990Z",
"answer_score": 47
} |
Please answer the following Stack Overflow question:
Title: For a boolean field, what is the naming convention for its getter/setter?
<p>Eg.</p>
<pre><code>boolean isCurrent = false;
</code></pre>
<p>What do you name its getter and setter?</p> | <p>Suppose you have </p>
<pre><code>boolean active;
</code></pre>
<p>Accessors method would be</p>
<pre><code>public boolean isActive(){return this.active;}
public void setActive(boolean active){this.active = active;}
</code></pre>
<hr>
<p><strong>See Also</strong></p>
<ul>
<li><a href="http://en.wikibooks.org/wiki/Java_Programming/Java_Beans" rel="noreferrer">Java Programming/Java Beans</a></li>
<li><a href="http://www.oracle.com/technetwork/java/codeconvtoc-136057.html" rel="noreferrer">Code Conventions for the Java Programming Language</a></li>
</ul> | {
"question_id": 5322648,
"question_date": "2011-03-16T08:26:40.893Z",
"question_score": 224,
"tags": "java|coding-style|naming-conventions|javabeans",
"answer_id": 5322666,
"answer_date": "2011-03-16T08:27:51.393Z",
"answer_score": 312
} |
Please answer the following Stack Overflow question:
Title: Can't access RabbitMQ web management interface after fresh install
<p>I've installed the latest RabbitMQ server (rabbitmq-server-3.3.0-1.noarch.rpm) on a fresh Centos 5.10 VM according to <a href="http://www.rabbitmq.com/install-rpm.html">the instructions on the official site.</a></p>
<p>I've done this many times before during development and never had any issues. However, this time I cannot log into the management web interface using the default guest/guest user.</p>
<p>In the logs, I see the following:</p>
<pre><code>=ERROR REPORT==== 4-Apr-2014::00:55:15 ===
webmachine error: path="api/whoami"
"Unauthorized"
</code></pre>
<p>What could be causing this?</p> | <p>It's new features since the version 3.3.0
<a href="http://www.rabbitmq.com/release-notes/README-3.3.0.txt" rel="noreferrer">http://www.rabbitmq.com/release-notes/README-3.3.0.txt</a></p>
<pre><code>server
------
...
25603 prevent access using the default guest/guest credentials except via
localhost.
</code></pre>
<p>If you want enable the guest user read <a href="http://www.rabbitmq.com/access-control.html" rel="noreferrer">this</a> or this <a href="https://stackoverflow.com/questions/23669780/rabbitmq-3-3-1-can-not-login-with-guest-guest">RabbitMQ 3.3.1 can not login with guest/guest</a> </p>
<pre><code># remove guest from loopback_users in rabbitmq.config like this
[{rabbit, [{loopback_users, []}]}].
# It is danger for default user and default password for remote access
# better to change password
rabbitmqctl change_password guest NEWPASSWORD
</code></pre>
<p>If you want create a new user with admin grants:</p>
<pre><code>rabbitmqctl add_user test test
rabbitmqctl set_user_tags test administrator
rabbitmqctl set_permissions -p / test ".*" ".*" ".*"
</code></pre>
<p>Now you can access using test test.</p> | {
"question_id": 22850546,
"question_date": "2014-04-03T23:01:09Z",
"question_score": 224,
"tags": "rabbitmq",
"answer_id": 22854222,
"answer_date": "2014-04-04T05:24:11.593Z",
"answer_score": 575
} |
Please answer the following Stack Overflow question:
Title: How to select multiple rows filled with constants?
<p>Selecting constants without referring to a table is perfectly legal in an SQL statement:</p>
<pre><code>SELECT 1, 2, 3
</code></pre>
<p>The result set that the latter returns is a single row containing the values. I was wondering if there is a way to select multiple rows at once using a constant expression, something kind of:</p>
<pre><code>SELECT ((1, 2, 3), (4, 5, 6), (7, 8, 9))
</code></pre>
<p>I would want something like the above that works and returns a result set with 3 rows and 3 columns.</p> | <pre><code>SELECT 1, 2, 3
UNION ALL SELECT 4, 5, 6
UNION ALL SELECT 7, 8, 9
</code></pre> | {
"question_id": 2201170,
"question_date": "2010-02-04T16:11:41.803Z",
"question_score": 224,
"tags": "sql|select|constants",
"answer_id": 2201212,
"answer_date": "2010-02-04T16:15:49.627Z",
"answer_score": 247
} |
Please answer the following Stack Overflow question:
Title: Remove trailing zeros
<p>I have some fields returned by a collection as</p>
<pre><code>2.4200
2.0044
2.0000
</code></pre>
<p>I want results like</p>
<pre><code>2.42
2.0044
2
</code></pre>
<p>I tried with <code>String.Format</code>, but it returns <code>2.0000</code> and setting it to <code>N0</code> rounds the other values as well.</p> | <p>Is it not as simple as this, if the input IS a string? You can use one of these:</p>
<pre><code>string.Format("{0:G29}", decimal.Parse("2.0044"))
decimal.Parse("2.0044").ToString("G29")
2.0m.ToString("G29")
</code></pre>
<p>This should work for all input.</p>
<p><strong>Update</strong> Check out the <a href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx#GFormatString" rel="noreferrer">Standard Numeric Formats</a> I've had to explicitly set the precision specifier to 29 as the docs clearly state:</p>
<blockquote>
<p>However, if the number is a Decimal and the precision specifier is omitted, fixed-point notation is always used and trailing zeros are preserved</p>
</blockquote>
<p><strong>Update</strong> <a href="https://stackoverflow.com/users/116691/konrad">Konrad</a> <a href="https://stackoverflow.com/questions/4525854/remove-trailing-zeros/4525896#comment-8733932">pointed out</a> in the comments:</p>
<blockquote>
<p>Watch out for values like 0.000001. G29 format will present them in the shortest possible way so it will switch to the exponential notation. <code>string.Format("{0:G29}", decimal.Parse("0.00000001",System.Globalization.CultureInfo.GetCultureInfo("en-US")))</code> will give "1E-08" as the result.</p>
</blockquote> | {
"question_id": 4525854,
"question_date": "2010-12-24T10:48:22.893Z",
"question_score": 224,
"tags": "c#|.net|decimal",
"answer_id": 4525983,
"answer_date": "2010-12-24T11:14:35.703Z",
"answer_score": 197
} |
Please answer the following Stack Overflow question:
Title: Perform an action in every sub-directory using Bash
<p>I am working on a script that needs to perform an action in every sub-directory of a specific folder.</p>
<p>What is the most efficient way to write that?</p> | <pre><code>for D in `find . -type d`
do
//Do whatever you need with D
done
</code></pre> | {
"question_id": 4000613,
"question_date": "2010-10-22T20:15:06.167Z",
"question_score": 224,
"tags": "bash|command|directory-traversal",
"answer_id": 4000707,
"answer_date": "2010-10-22T20:29:20.957Z",
"answer_score": 187
} |
Please answer the following Stack Overflow question:
Title: How to ignore ansible SSH authenticity checking?
<p>Is there a way to ignore the SSH authenticity checking made by Ansible? For example when I've just setup a new server I have to answer yes to this question:</p>
<pre><code>GATHERING FACTS ***************************************************************
The authenticity of host 'xxx.xxx.xxx.xxx (xxx.xxx.xxx.xxx)' can't be established.
RSA key fingerprint is xx:yy:zz:....
Are you sure you want to continue connecting (yes/no)?
</code></pre>
<p>I know that this is generally a bad idea but I'm incorporating this in a script that first creates a new virtual server at my cloud provider and then automatically calls my ansible playbook to configure it. I want to avoid any human intervention in the middle of the script execution.</p> | <p>Two options - the first, as you said in your own answer, is setting the environment variable <code>ANSIBLE_HOST_KEY_CHECKING</code> to False.</p>
<p>The second way to set it is to put it in an ansible.cfg file, and that's a really useful option because you can either set that globally (at system or user level, in <code>/etc/ansible/ansible.cfg</code> or <code>~/.ansible.cfg</code>), or in an config file in the same directory as the playbook you are running.</p>
<p>To do that, make an <code>ansible.cfg</code> file in one of those locations, and include this:</p>
<pre><code>[defaults]
host_key_checking = False
</code></pre>
<p>You can also set a lot of other handy defaults there, like whether or not to gather facts at the start of a play, whether to merge hashes declared in multiple places or replace one with another, and so on. There's a whole big list of options <a href="http://docs.ansible.com/ansible/intro_configuration.html" rel="noreferrer">here</a> in the Ansible docs.</p>
<hr />
<p>Edit: a note on security.</p>
<p>SSH host key validation is a meaningful security layer for <em>persistent hosts</em> - if you are connecting to the same machine many times, it's valuable to accept the host key locally.</p>
<p>For longer-lived EC2 instances, it would make sense to accept the host key with a task run <em>only once</em> on initial creation of the instance:</p>
<pre class="lang-yaml prettyprint-override"><code>- name: Write the new ec2 instance host key to known hosts
connection: local
shell: "ssh-keyscan -H {{ inventory_hostname }} >> ~/.ssh/known_hosts"
</code></pre>
<p>There's no security value for checking host keys on instances that you stand up dynamically and remove right after playbook execution, but there is security value in checking host keys for persistent machines. So you should manage host key checking differently per logical environment.</p>
<ul>
<li>Leave checking enabled by default (in <code>~/.ansible.cfg</code>)</li>
<li>Disable host key checking in the working directory for playbooks you run against ephemeral instances (<code>./ansible.cfg</code> alongside the playbook for unit tests against vagrant VMs, automation for short-lived ec2 instances)</li>
</ul> | {
"question_id": 32297456,
"question_date": "2015-08-30T14:13:33.127Z",
"question_score": 224,
"tags": "ssh|ansible",
"answer_id": 32338480,
"answer_date": "2015-09-01T18:22:50.620Z",
"answer_score": 325
} |
Please answer the following Stack Overflow question:
Title: Unfinished Stubbing Detected in Mockito
<p>I am getting following exception while running the tests. I am using Mockito for mocking. The hints mentioned by Mockito library are not helping.</p>
<pre class="lang-none prettyprint-override"><code>org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at com.a.b.DomainTestFactory.myTest(DomainTestFactory.java:355)
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer!
at a.b.DomainTestFactory.myTest(DomainTestFactory.java:276)
..........
</code></pre>
<p>Test Code from <code>DomainTestFactory</code>. When I run the following test, I see the exception.</p>
<pre><code>@Test
public myTest(){
MyMainModel mainModel = Mockito.mock(MyMainModel.class);
Mockito.when(mainModel.getList()).thenReturn(getSomeList()); // Line 355
}
private List<SomeModel> getSomeList() {
SomeModel model = Mockito.mock(SomeModel.class);
Mockito.when(model.getName()).thenReturn("SomeName"); // Line 276
Mockito.when(model.getAddress()).thenReturn("Address");
return Arrays.asList(model);
}
public class SomeModel extends SomeInputModel{
protected String address;
protected List<SomeClass> properties;
public SomeModel() {
this.Properties = new java.util.ArrayList<SomeClass>();
}
public String getAddress() {
return this.address;
}
}
public class SomeInputModel{
public NetworkInputModel() {
this.Properties = new java.util.ArrayList<SomeClass>();
}
protected String Name;
protected List<SomeClass> properties;
public String getName() {
return this.Name;
}
public void setName(String value) {
this.Name = value;
}
}
</code></pre> | <p>You're nesting mocking inside of mocking. You're calling <code>getSomeList()</code>, which does some mocking, before you've finished the mocking for <code>MyMainModel</code>. Mockito doesn't like it when you do this.</p>
<p>Replace</p>
<pre><code>@Test
public myTest(){
MyMainModel mainModel = Mockito.mock(MyMainModel.class);
Mockito.when(mainModel.getList()).thenReturn(getSomeList()); --> Line 355
}
</code></pre>
<p>with</p>
<pre><code>@Test
public myTest(){
MyMainModel mainModel = Mockito.mock(MyMainModel.class);
List<SomeModel> someModelList = getSomeList();
Mockito.when(mainModel.getList()).thenReturn(someModelList);
}
</code></pre>
<p>To understand why this causes a problem, you need to know a little about how Mockito works, and also be aware in what order expressions and statements are evaluated in Java.</p>
<p>Mockito can't read your source code, so in order to figure out what you are asking it to do, it relies a lot on static state. When you call a method on a mock object, Mockito records the details of the call in an internal list of invocations. The <code>when</code> method reads the last of these invocations off the list and records this invocation in the <code>OngoingStubbing</code> object it returns.</p>
<p>The line</p>
<pre><code>Mockito.when(mainModel.getList()).thenReturn(someModelList);
</code></pre>
<p>causes the following interactions with Mockito:</p>
<ul>
<li>Mock method <code>mainModel.getList()</code> is called,</li>
<li>Static method <code>when</code> is called,</li>
<li>Method <code>thenReturn</code> is called on the <code>OngoingStubbing</code> object returned by the <code>when</code> method.</li>
</ul>
<p>The <code>thenReturn</code> method can then instruct the mock it received via the <code>OngoingStubbing</code> method to handle any suitable call to the <code>getList</code> method to return <code>someModelList</code>.</p>
<p>In fact, as Mockito can't see your code, you can also write your mocking as follows:</p>
<pre><code>mainModel.getList();
Mockito.when((List<SomeModel>)null).thenReturn(someModelList);
</code></pre>
<p>This style is somewhat less clear to read, especially since in this case the <code>null</code> has to be casted, but it generates the same sequence of interactions with Mockito and will achieve the same result as the line above.</p>
<p>However, the line </p>
<pre><code>Mockito.when(mainModel.getList()).thenReturn(getSomeList());
</code></pre>
<p>causes the following interactions with Mockito:</p>
<ol>
<li>Mock method <code>mainModel.getList()</code> is called,</li>
<li>Static method <code>when</code> is called,</li>
<li>A new <code>mock</code> of <code>SomeModel</code> is created (inside <code>getSomeList()</code>),</li>
<li>Mock method <code>model.getName()</code> is called,</li>
</ol>
<p>At this point Mockito gets confused. It thought you were mocking <code>mainModel.getList()</code>, but now you're telling it you want to mock the <code>model.getName()</code> method. To Mockito, it looks like you're doing the following:</p>
<pre><code>when(mainModel.getList());
// ...
when(model.getName()).thenReturn(...);
</code></pre>
<p>This looks silly to <code>Mockito</code> as it can't be sure what you're doing with <code>mainModel.getList()</code>.</p>
<p>Note that we did not get to the <code>thenReturn</code> method call, as the JVM needs to evaluate the parameters to this method before it can call the method. In this case, this means calling the <code>getSomeList()</code> method.</p>
<p>Generally it is a bad design decision to rely on static state, as Mockito does, because it can lead to cases where the Principle of Least Astonishment is violated. However, Mockito's design does make for clear and expressive mocking, even if it leads to astonishment sometimes.</p>
<p>Finally, recent versions of Mockito add an extra line to the error message above. This extra line indicates you may be in the same situation as this question:</p>
<blockquote>
<p>3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed</p>
</blockquote> | {
"question_id": 26318569,
"question_date": "2014-10-11T19:42:19.947Z",
"question_score": 224,
"tags": "java|mocking|mockito",
"answer_id": 26319364,
"answer_date": "2014-10-11T21:19:16.397Z",
"answer_score": 489
} |
Please answer the following Stack Overflow question:
Title: Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia
<p>I opened a webcam by using the following JavaScript code:</p>
<pre class="lang-js prettyprint-override"><code>const stream = await navigator.mediaDevices.getUserMedia({ /* ... */ });
</code></pre>
<p>Is there any JavaScript code to stop or close the webcam? Thanks everyone.</p> | <p><strong>EDIT</strong></p>
<p>Since this answer has been originally posted the browser API has changed.
<code>.stop()</code> is no longer available on the stream that gets passed to the callback.
The developer will have to access the tracks that make up the stream (audio or video) and stop each of them individually.</p>
<p>More info here: <a href="https://developers.google.com/web/updates/2015/07/mediastream-deprecations?hl=en#stop-ended-and-active" rel="noreferrer">https://developers.google.com/web/updates/2015/07/mediastream-deprecations?hl=en#stop-ended-and-active</a></p>
<p>Example (from the link above):</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>stream.getTracks().forEach(function(track) {
track.stop();
});</code></pre>
</div>
</div>
</p>
<p>Browser support may differ.</p>
<p><strong>Original answer</strong></p>
<p><code>navigator.getUserMedia</code> provides you with a stream in the success callback, you can call <code>.stop()</code> on that stream to stop the recording (at least in Chrome, seems FF doesn't like it)</p> | {
"question_id": 11642926,
"question_date": "2012-07-25T04:51:11.187Z",
"question_score": 224,
"tags": "javascript|html|html5-video|webrtc|getusermedia",
"answer_id": 12436772,
"answer_date": "2012-09-15T10:54:38.753Z",
"answer_score": 308
} |
Please answer the following Stack Overflow question:
Title: How to check if object has any properties in JavaScript?
<p>Assuming I declare </p>
<pre><code>var ad = {};
</code></pre>
<p>How can I check whether this object will contain any user-defined properties?</p> | <p>You can loop over the properties of your object as follows:</p>
<pre><code>for(var prop in ad) {
if (ad.hasOwnProperty(prop)) {
// handle prop as required
}
}
</code></pre>
<p>It is important to use the <a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/hasOwnProperty" rel="noreferrer"><code>hasOwnProperty()</code></a> method, to determine whether the object has the specified property as a direct property, and not inherited from the object's prototype chain.</p>
<h2>Edit</h2>
<p><strong>From the comments:</strong> <em>You can put that code in a function, and make it return false as soon as it reaches the part where there is the comment</em></p> | {
"question_id": 2673121,
"question_date": "2010-04-20T06:44:17.380Z",
"question_score": 224,
"tags": "javascript",
"answer_id": 2673141,
"answer_date": "2010-04-20T06:49:28.207Z",
"answer_score": 98
} |
Please answer the following Stack Overflow question:
Title: Where can I find "make" program for Mac OS X Lion?
<p>Just upgraded my computer to Mac OS X Lion and went to terminal and typed "make" but it says:
-bash: make: command not found</p>
<p>Where did the "make" command go?</p> | <p>Have you installed Xcode and the developer tools? I think make, along with gcc and friends, is installed with that and not before. Xcode 4.1 for Lion is free.</p> | {
"question_id": 6767481,
"question_date": "2011-07-20T19:38:23.067Z",
"question_score": 224,
"tags": "macos|makefile|osx-lion",
"answer_id": 6767540,
"answer_date": "2011-07-20T19:43:28.013Z",
"answer_score": 49
} |
Please answer the following Stack Overflow question:
Title: How to divide flask app into multiple py files?
<p>My flask application currently consists of a single <code>test.py</code> file with multiple routes and the <code>main()</code> route defined. Is there some way I could create a <code>test2.py</code> file that contains routes that were not handled in <code>test.py</code>?</p>
<pre><code>@app.route('/somepath')
def somehandler():
# Handler code here
</code></pre>
<p>I am concerned that there are too many routes in <code>test.py</code> and would like to make it such that I can run <code>python test.py</code>, which will also pick up the routes on <code>test.py</code> as if it were part of the same file. What changes to I have to make in <code>test.py</code> and/or include in <code>test2.py</code> to get this to work?</p> | <p>You can use the usual Python package structure to divide your App into multiple modules, <a href="http://flask.pocoo.org/docs/patterns/packages/">see the Flask docs.</a></p>
<p>However,</p>
<blockquote>
<p>Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications.</p>
</blockquote>
<p>You can create a sub-component of your app as a Blueprint in a separate file:</p>
<pre><code>simple_page = Blueprint('simple_page', __name__, template_folder='templates')
@simple_page.route('/<page>')
def show(page):
# stuff
</code></pre>
<p>And then use it in the main part:</p>
<pre><code>from yourapplication.simple_page import simple_page
app = Flask(__name__)
app.register_blueprint(simple_page)
</code></pre>
<p>Blueprints can also bundle specific resources: templates or static files. Please refer to the <a href="http://flask.pocoo.org/docs/blueprints/#blueprints">Flask docs</a> for all the details.</p> | {
"question_id": 11994325,
"question_date": "2012-08-16T19:43:25.563Z",
"question_score": 224,
"tags": "python|flask",
"answer_id": 11994728,
"answer_date": "2012-08-16T20:09:37.557Z",
"answer_score": 213
} |
Please answer the following Stack Overflow question:
Title: How can I get the current screen orientation?
<p>I just want to set some flags when my orientation is in landscape so that when the activity is recreated in onCreate() i can toggle between what to load in portrait vs. landscape. I already have a layout-land xml that is handling my layout.</p>
<pre><code>public void onConfigurationChanged(Configuration _newConfig) {
if (_newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
this.loadURLData = false;
}
if (_newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
this.loadURLData = true;
}
super.onConfigurationChanged(_newConfig);
}
</code></pre>
<p>Over-riding onConfigurationChanged will prevent my layout-land xml from loading in landscape orientation.</p>
<p>I just want to get the current orientation of my device in onCreate(). How can I get this?</p> | <pre><code>Activity.getResources().getConfiguration().orientation
</code></pre> | {
"question_id": 3663665,
"question_date": "2010-09-08T00:15:47.650Z",
"question_score": 224,
"tags": "java|android|configuration|orientation",
"answer_id": 3663693,
"answer_date": "2010-09-08T00:22:28.677Z",
"answer_score": 517
} |
Please answer the following Stack Overflow question:
Title: .Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned
<p>I am in a situation where when I get an HTTP 400 code from the server, it is a completely legal way of the server telling me what was wrong with my request (using a message in the HTTP response content)</p>
<p>However, the .NET HttpWebRequest raises an exception when the status code is 400. </p>
<p>How do I handle this? For me a 400 is completely legal, and rather helpful. The HTTP content has some important information but the exception throws me off my path.</p> | <p>It would be nice if there were some way of turning off "throw on non-success code" but if you catch WebException you can at least use the response:</p>
<pre><code>using System;
using System.IO;
using System.Web;
using System.Net;
public class Test
{
static void Main()
{
WebRequest request = WebRequest.Create("http://csharpindepth.com/asd");
try
{
using (WebResponse response = request.GetResponse())
{
Console.WriteLine("Won't get here");
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse) response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
Console.WriteLine(text);
}
}
}
}
}
</code></pre>
<p>You might like to encapsulate the "get me a response even if it's not a success code" bit in a separate method. (I'd suggest you still throw if there isn't a response, e.g. if you couldn't connect.)</p>
<p>If the error response may be large (which is unusual) you may want to tweak <a href="https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.defaultmaximumerrorresponselength" rel="noreferrer"><code>HttpWebRequest.DefaultMaximumErrorResponseLength</code></a> to make sure you get the whole error.</p> | {
"question_id": 692342,
"question_date": "2009-03-28T06:40:02.650Z",
"question_score": 224,
"tags": ".net|httpwebrequest",
"answer_id": 692369,
"answer_date": "2009-03-28T07:07:08.280Z",
"answer_score": 389
} |
Please answer the following Stack Overflow question:
Title: How do I create an average from a Ruby array?
<p>How would get find an average from an array?</p>
<p>If I have the array:</p>
<pre><code>[0,4,8,2,5,0,2,6]
</code></pre>
<p>Averaging would give me 3.375.</p> | <p>Try this:</p>
<pre><code>arr = [5, 6, 7, 8]
arr.inject{ |sum, el| sum + el }.to_f / arr.size
=> 6.5
</code></pre>
<p>Note the <code>.to_f</code>, which you'll want for avoiding any problems from integer division. You can also do:</p>
<pre><code>arr = [5, 6, 7, 8]
arr.inject(0.0) { |sum, el| sum + el } / arr.size
=> 6.5
</code></pre>
<p>You can define it as part of <code>Array</code> as another commenter has suggested, but you need to avoid integer division or your results will be wrong. Also, this isn't generally applicable to every possible element type (obviously, an average only makes sense for things that can be averaged). But if you want to go that route, use this:</p>
<pre><code>class Array
def sum
inject(0.0) { |result, el| result + el }
end
def mean
sum / size
end
end
</code></pre>
<p>If you haven't seen <code>inject</code> before, it's not as magical as it might appear. It iterates over each element and then applies an accumulator value to it. The accumulator is then handed to the next element. In this case, our accumulator is simply an integer that reflects the sum of all the previous elements.</p>
<p><strong>Edit:</strong> Commenter Dave Ray proposed a nice improvement.</p>
<p><strong>Edit:</strong> Commenter Glenn Jackman's proposal, using <code>arr.inject(:+).to_f</code>, is nice too but perhaps a bit too clever if you don't know what's going on. The <code>:+</code> is a symbol; when passed to inject, it applies the method named by the symbol (in this case, the addition operation) to each element against the accumulator value.</p> | {
"question_id": 1341271,
"question_date": "2009-08-27T13:54:25.243Z",
"question_score": 224,
"tags": "ruby-on-rails|ruby",
"answer_id": 1341318,
"answer_date": "2009-08-27T14:00:49.930Z",
"answer_score": 268
} |
Please answer the following Stack Overflow question:
Title: How to concatenate strings in django templates?
<p>I want to concatenate a string in a Django template tag, like:</p>
<pre><code>{% extend shop/shop_name/base.html %}
</code></pre>
<p>Here <code>shop_name</code> is my variable and I want to concatenate this with rest of path.</p>
<p>Suppose I have <code>shop_name=example.com</code> and I want result to extend <code>shop/example.com/base.html</code>.</p> | <p>Use with:</p>
<pre><code>{% with "shop/"|add:shop_name|add:"/base.html" as template %}
{% include template %}
{% endwith %}
</code></pre> | {
"question_id": 4386168,
"question_date": "2010-12-08T09:58:14.450Z",
"question_score": 224,
"tags": "django|django-templates",
"answer_id": 4524851,
"answer_date": "2010-12-24T07:20:21.953Z",
"answer_score": 421
} |
Please answer the following Stack Overflow question:
Title: Style child element when hover on parent
<p>How to change the style of child element when there is hover on parent element. I would prefer a CSS solution for this if possible. Is there any solution possible through :hover CSS selectors. Actually I need to change color of options bar inside a panel when there is an hover on the panel.</p>
<p><em>Looking to support all major browsers.</em></p> | <p>Yes, you can definitely do this. Just use something like</p>
<pre class="lang-css prettyprint-override"><code>.parent:hover .child {
/* ... */
}
</code></pre>
<p>According to <a href="http://www.quirksmode.org/css/contents.html" rel="noreferrer">this page</a> it's supported by all major browsers.</p> | {
"question_id": 7217244,
"question_date": "2011-08-27T20:46:45.313Z",
"question_score": 224,
"tags": "css|css-selectors",
"answer_id": 7217397,
"answer_date": "2011-08-27T21:16:00.847Z",
"answer_score": 414
} |
Please answer the following Stack Overflow question:
Title: Nesting await in Parallel.ForEach
<p>In a metro app, I need to execute a number of WCF calls. There are a significant number of calls to be made, so I need to do them in a parallel loop. The problem is that the parallel loop exits before the WCF calls are all complete.</p>
<p>How would you refactor this to work as expected?</p>
<pre><code>var ids = new List<string>() { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
var customers = new System.Collections.Concurrent.BlockingCollection<Customer>();
Parallel.ForEach(ids, async i =>
{
ICustomerRepo repo = new CustomerRepo();
var cust = await repo.GetCustomer(i);
customers.Add(cust);
});
foreach ( var customer in customers )
{
Console.WriteLine(customer.ID);
}
Console.ReadKey();
</code></pre> | <p>The whole idea behind <code>Parallel.ForEach()</code> is that you have a set of threads and each thread processes part of the collection. As you noticed, this doesn't work with <code>async</code>-<code>await</code>, where you want to release the thread for the duration of the async call.</p>
<p>You could “fix” that by blocking the <code>ForEach()</code> threads, but that defeats the whole point of <code>async</code>-<code>await</code>.</p>
<p>What you could do is to use <a href="https://docs.microsoft.com/dotnet/standard/parallel-programming/dataflow-task-parallel-library" rel="nofollow noreferrer">TPL Dataflow</a> instead of <code>Parallel.ForEach()</code>, which supports asynchronous <code>Task</code>s well.</p>
<p>Specifically, your code could be written using a <code>TransformBlock</code> that transforms each id into a <code>Customer</code> using the <code>async</code> lambda. This block can be configured to execute in parallel. You would link that block to an <code>ActionBlock</code> that writes each <code>Customer</code> to the console.
After you set up the block network, you can <code>Post()</code> each id to the <code>TransformBlock</code>.</p>
<p>In code:</p>
<pre><code>var ids = new List<string> { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
var getCustomerBlock = new TransformBlock<string, Customer>(
async i =>
{
ICustomerRepo repo = new CustomerRepo();
return await repo.GetCustomer(i);
}, new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded
});
var writeCustomerBlock = new ActionBlock<Customer>(c => Console.WriteLine(c.ID));
getCustomerBlock.LinkTo(
writeCustomerBlock, new DataflowLinkOptions
{
PropagateCompletion = true
});
foreach (var id in ids)
getCustomerBlock.Post(id);
getCustomerBlock.Complete();
writeCustomerBlock.Completion.Wait();
</code></pre>
<p>Although you probably want to limit the parallelism of the <code>TransformBlock</code> to some small constant. Also, you could limit the capacity of the <code>TransformBlock</code> and add the items to it asynchronously using <code>SendAsync()</code>, for example if the collection is too big.</p>
<p>As an added benefit when compared to your code (if it worked) is that the writing will start as soon as a single item is finished, and not wait until all of the processing is finished.</p> | {
"question_id": 11564506,
"question_date": "2012-07-19T15:47:16.623Z",
"question_score": 224,
"tags": "c#|wcf|async-await|task-parallel-library|parallel.foreach",
"answer_id": 11565317,
"answer_date": "2012-07-19T16:32:41.523Z",
"answer_score": 196
} |
Please answer the following Stack Overflow question:
Title: What is the intended use-case for git stash?
<p>If I work on branch A and suddenly need to work on branch B before being ready with a commit on branch A, I stash my changes on A, checkout B, do my work there, then checkout A and apply the stash.</p>
<p>If I work on A and I want to stop working for the day, should I stash my work and then apply it the next day (when I resume my work), or should I just leave things as they are—uncommitted modified files in the working directory? I don't see why I would need to use stash in this case, except if there is some security benefit.</p>
<p>Also, another scenario: I work both at work and at home. If I am not ready with a commit when I want to go home, can I stash my work, push it to GitHub and then pull that stash at home?</p> | <p>Stash is just a convenience method. Since branches are so cheap and easy to manage in git, I personally almost always prefer creating a new temporary branch than stashing, but it's a matter of taste mostly.</p>
<p>The one place I do like stashing is if I discover I forgot something in my last commit and have already started working on the next one in the same branch:</p>
<pre class="lang-bash prettyprint-override"><code># Assume the latest commit was already done
# start working on the next patch, and discovered I was missing something
# stash away the current mess I made
git stash save
# some changes in the working dir
# and now add them to the last commit:
git add -u
git commit --amend
# back to work!
git stash pop
</code></pre> | {
"question_id": 20537223,
"question_date": "2013-12-12T07:15:04.333Z",
"question_score": 224,
"tags": "git|git-stash",
"answer_id": 20537356,
"answer_date": "2013-12-12T07:22:10.173Z",
"answer_score": 265
} |
Please answer the following Stack Overflow question:
Title: Break when a value changes using the Visual Studio debugger
<p>Is there a way to place a watch on variable and only have Visual Studio break when that value changes?</p>
<p>It would make it so much easier to find tricky state issues.</p>
<p>Can this be done?</p>
<p>Breakpoint conditions still need a breakpoint set, and I'd rather set a watch and let Visual Studio set the breakpoints at state changes.</p> | <p>In the Visual Studio 2005 menu:</p>
<p><em>Debug</em> -> <em>New Breakpoint</em> -> <em>New Data Breakpoint</em></p>
<p>Enter:</p>
<pre><code>&myVariable
</code></pre> | {
"question_id": 160045,
"question_date": "2008-10-01T22:26:50.963Z",
"question_score": 224,
"tags": "visual-studio|debugging|breakpoints|conditional-breakpoint",
"answer_id": 160074,
"answer_date": "2008-10-01T22:36:30.443Z",
"answer_score": 144
} |
Please answer the following Stack Overflow question:
Title: How do I declare class-level properties in Objective-C?
<p>Maybe this is obvious, but I don't know how to declare class properties in Objective-C.</p>
<p>I need to cache per-class a dictionary and wonder how put it in the class.</p> | <p>properties have a specific meaning in Objective-C, but I think you mean something that's equivalent to a static variable? E.g. only one instance for all types of Foo?</p>
<p>To declare class functions in Objective-C you use the + prefix instead of - so your implementation would look something like:</p>
<pre><code>// Foo.h
@interface Foo {
}
+ (NSDictionary *)dictionary;
// Foo.m
+ (NSDictionary *)dictionary {
static NSDictionary *fooDict = nil;
if (fooDict == nil) {
// create dict
}
return fooDict;
}
</code></pre> | {
"question_id": 695980,
"question_date": "2009-03-30T04:09:04.977Z",
"question_score": 224,
"tags": "objective-c|cocoa|oop",
"answer_id": 696024,
"answer_date": "2009-03-30T04:50:41.273Z",
"answer_score": 203
} |
Please answer the following Stack Overflow question:
Title: Transposing a 2D-array in JavaScript
<p>I've got an array of arrays, something like:</p>
<pre><code>[
[1,2,3],
[1,2,3],
[1,2,3],
]
</code></pre>
<p>I would like to transpose it to get the following array:</p>
<pre><code>[
[1,1,1],
[2,2,2],
[3,3,3],
]
</code></pre>
<p>It's not difficult to programmatically do so using loops:</p>
<pre><code>function transposeArray(array, arrayLength){
var newArray = [];
for(var i = 0; i < array.length; i++){
newArray.push([]);
};
for(var i = 0; i < array.length; i++){
for(var j = 0; j < arrayLength; j++){
newArray[j].push(array[i][j]);
};
};
return newArray;
}
</code></pre>
<p>This, however, seems bulky, and I feel like there should be an easier way to do it. Is there?</p> | <pre><code>output = array[0].map((_, colIndex) => array.map(row => row[colIndex]));
</code></pre>
<blockquote>
<p><code>map</code> calls a provided <code>callback</code> function once for each element in an array, in order, and constructs a new array from the results. <code>callback</code> is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.</p>
</blockquote>
<blockquote>
<p><code>callback</code> is invoked with three arguments: the value of the element, the index of the element, and the Array object being traversed.<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" rel="noreferrer"> [source]</a></p>
</blockquote> | {
"question_id": 17428587,
"question_date": "2013-07-02T14:43:06.480Z",
"question_score": 224,
"tags": "javascript|arrays|matrix|transpose",
"answer_id": 17428705,
"answer_date": "2013-07-02T14:48:17.927Z",
"answer_score": 284
} |
Please answer the following Stack Overflow question:
Title: Getting All Variables In Scope
<p>Is there a way to get all variables that are currently in scope in javascript?</p> | <p>No. "In scope" variables are determined by the "scope chain", which is not accessible programmatically.</p>
<p>For detail (quite a lot of it), check out the ECMAScript (JavaScript) specification. <a href="http://www.ecma-international.org/publications/standards/Ecma-262.htm" rel="noreferrer">Here's a link</a> to the official page where you can download the canonical spec (a PDF), and <a href="http://www.ecma-international.org/ecma-262/5.1/" rel="noreferrer">here's one</a> to the official, linkable HTML version.</p>
<p><strong>Update based on your comment to Camsoft</strong></p>
<p>The variables <em>in scope</em> for your event function are determined by where you define your event function, not how they call it. <strong>But</strong>, you may find useful information about what's available to your function via <code>this</code> and arguments by doing something along the lines of what KennyTM pointed out (<code>for (var propName in ____)</code>) since that will tell you what's available on various objects provided to you (<code>this</code> and arguments; if you're not sure what arguments they give you, you can find out via the <code>arguments</code> variable that's implicitly defined for every function).</p>
<p>So in addition to whatever's in-scope because of where you define your function, you can find out what else is available by other means by doing:</p>
<pre><code>var n, arg, name;
alert("typeof this = " + typeof this);
for (name in this) {
alert("this[" + name + "]=" + this[name]);
}
for (n = 0; n < arguments.length; ++n) {
arg = arguments[n];
alert("typeof arguments[" + n + "] = " + typeof arg);
for (name in arg) {
alert("arguments[" + n + "][" + name + "]=" + arg[name]);
}
}
</code></pre>
<p>(You can expand on that to get more useful information.)</p>
<p>Instead of that, though, I'd probably use a debugger like Chrome's dev tools (even if you don't normally use Chrome for development) or <a href="http://getfirebug.com/" rel="noreferrer">Firebug</a> (even if you don't normally use Firefox for development), or Dragonfly on Opera, or "F12 Developer Tools" on IE. And read through whatever JavaScript files they provide you. And beat them over the head for proper docs. :-)</p> | {
"question_id": 2051678,
"question_date": "2010-01-12T19:20:53.607Z",
"question_score": 224,
"tags": "javascript",
"answer_id": 2051693,
"answer_date": "2010-01-12T19:23:34.690Z",
"answer_score": 89
} |
Please answer the following Stack Overflow question:
Title: uppercase first character in a variable with bash
<p>I want to uppercase just the first character in my string with bash.</p>
<pre><code>foo="bar";
//uppercase first character
echo $foo;
</code></pre>
<p>should print "Bar";</p> | <pre><code>foo="$(tr '[:lower:]' '[:upper:]' <<< ${foo:0:1})${foo:1}"
</code></pre> | {
"question_id": 12487424,
"question_date": "2012-09-19T01:35:37.280Z",
"question_score": 224,
"tags": "bash",
"answer_id": 12487465,
"answer_date": "2012-09-19T01:41:50.087Z",
"answer_score": 205
} |
Please answer the following Stack Overflow question:
Title: What HTTP status code should be used for wrong input
<p>What is optimal HTTP response Code when not reporting 200 (everything OK) but error in input?</p>
<p>Like, you submit some data to server, and it will response that your data is wrong</p>
<p>using <code>500</code> looks more like Server Issue<br>
using <code>200</code> with warning/error response text is bad (allowing caching and everything is not OK)<br>
using <code>204</code> and returning nothing, is maybe good (but well supported?)<br>
using <code>404</code> is wrong if requested path (script) is available and in proper place</p> | <p>We had the same problem when making our API as well. We were looking for an HTTP status code equivalent to an <code>InvalidArgumentException</code>. After reading the source article below, we ended up using <code>422 Unprocessable Entity</code> which states:</p>
<blockquote>
<p>The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415 (Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.</p>
</blockquote>
<p>source: <a href="https://www.bennadel.com/blog/2434-http-status-codes-for-invalid-data-400-vs-422.htm" rel="noreferrer">https://www.bennadel.com/blog/2434-http-status-codes-for-invalid-data-400-vs-422.htm</a></p> | {
"question_id": 7939137,
"question_date": "2011-10-29T13:18:05.203Z",
"question_score": 224,
"tags": "validation|http",
"answer_id": 42171674,
"answer_date": "2017-02-11T02:56:36.360Z",
"answer_score": 293
} |
Please answer the following Stack Overflow question:
Title: Why does flexbox stretch my image rather than retaining aspect ratio?
<p>Flexbox has this behaviour where it stretches images to their natural height. In other words, if I have a flexbox container with a child image, and I resize the width of that image, the height doesn't resize at all and the image gets stretched.</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>div {
display: flex;
flex-wrap: wrap;
}
img {
width: 50%
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
<img src="https://i.imgur.com/KAthy7g.jpg" >
<h1>Heading</h1>
<p>Paragraph</p>
</div></code></pre>
</div>
</div>
</p>
<p>What causes this?</p> | <p>It is stretching because <code>align-self</code> default value is <code>stretch</code>.
Set <code>align-self</code> to <code>center</code>.</p>
<pre class="lang-css prettyprint-override"><code>align-self: center;
</code></pre>
<p>See documentation here:
<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/align-self" rel="noreferrer">align-self</a></p> | {
"question_id": 37609642,
"question_date": "2016-06-03T08:33:29.760Z",
"question_score": 224,
"tags": "html|css|flexbox",
"answer_id": 37610279,
"answer_date": "2016-06-03T09:07:36.687Z",
"answer_score": 482
} |
Please answer the following Stack Overflow question:
Title: Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87
<p>referencing the play-services via gradle stopped working for me - boiled it down - even the sample I used as a reference in the first place stopped working:
<a href="https://plus.google.com/+AndroidDevelopers/posts/4Yhpn6p9icf">https://plus.google.com/+AndroidDevelopers/posts/4Yhpn6p9icf</a></p>
<pre><code>FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring project ':auth'.
> Failed to notify project evaluation listener.
> Could not resolve all dependencies for configuration ':auth:compile'.
> Could not find com.google.android.gms:play-services:3.1.36.
Required by:
gpsdemos:auth:unspecified
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 3.577 secs
</code></pre>
<p>I fear that just the version increased but that raises 2 questions:
#1) what is the new one?
#2) why is the old version gone?</p> | <p>Check if you also installed the "Google Repository". If not, you also have to install the "Google Repository" in your SDK Manager.</p>
<p>Also be aware that there might be 2 SDK installations - one coming from AndroidStudio and one you might have installed. Better consolidate this to one installation - this is a common pitfall - that you have it installed in one installation but it fails when you build with the other installation.</p>
<p><a href="https://i.stack.imgur.com/jPqsW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jPqsW.png" alt="Example of how to access SDK Manager for Google Repository"></a></p> | {
"question_id": 17155475,
"question_date": "2013-06-17T19:41:41.150Z",
"question_score": 224,
"tags": "android|gradle|google-play-services",
"answer_id": 17157227,
"answer_date": "2013-06-17T21:32:12.113Z",
"answer_score": 465
} |
Please answer the following Stack Overflow question:
Title: Is it necessary to write HEAD, BODY and HTML tags?
<p>Is it necessary to write <code><html></code>, <code><head></code> and <code><body></code> tags?</p>
<p>For example, I can make such a page:</p>
<pre><code><!DOCTYPE html>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Page Title</title>
<link rel="stylesheet" type="text/css" href="css/reset.css">
<script src="js/head_script.js"></script><!-- this script will be in head //-->
<div>Some html</div> <!-- here body starts //-->
<script src="js/body_script.js"></script>
</code></pre>
<p>And <a href="https://en.wikipedia.org/wiki/Firebug_%28software%29" rel="noreferrer">Firebug</a> correctly separates head and body:</p>
<p><img src="https://i.stack.imgur.com/7xVux.png" alt="Enter image description here" /></p>
<p>The <a href="https://en.wikipedia.org/wiki/W3C_Markup_Validation_Service" rel="noreferrer">W3C validator</a> says it's valid.</p>
<p>But I rarely see this practice on the web.</p>
<p>Is there a reason to write these tags?</p> | <p>Omitting the <code>html</code>, <code>head</code>, and <code>body</code> <em>tags</em> is certainly allowed by the HTML specifications. The underlying reason is that browsers have always sought to be consistent with existing web pages, and the very early versions of HTML didn't define those elements. When HTML first did, it was done in a way that the tags would be inferred when missing.</p>
<p>I often find it convenient to omit the tags when prototyping and especially when writing test cases as it helps keep the markup focused on the test in question. The inference process <em>should</em> create the elements in exactly the manner that you see in Firebug, and browsers are pretty consistent in doing that.</p>
<p>But...</p>
<p><a href="https://en.wikipedia.org/wiki/Internet_Explorer" rel="nofollow noreferrer">Internet Explorer</a> has at least one known bug in this area. Even <a href="https://en.wikipedia.org/wiki/Internet_Explorer_9" rel="nofollow noreferrer">Internet Explorer 9</a> exhibits this. Suppose the markup is this:</p>
<pre><code><!DOCTYPE html>
<title>Test case</title>
<form action='#'>
<input name="var1">
</form>
</code></pre>
<p>You should (and do in other browsers) get a <a href="https://en.wikipedia.org/wiki/Document_Object_Model" rel="nofollow noreferrer">DOM</a> that looks like this:</p>
<pre><code>HTML
HEAD
TITLE
BODY
FORM action="#"
INPUT name="var1"
</code></pre>
<p>But in Internet Explorer you get this:</p>
<pre><code>HTML
HEAD
TITLE
FORM action="#"
BODY
INPUT name="var1"
BODY
</code></pre>
<p><a href="http://software.hixie.ch/utilities/js/live-dom-viewer/?%3C!DOCTYPE%20html%3E%0D%0A%3Ctitle%3ETest%20case%3C%2Ftitle%3E%0D%0A%3Cform%20action%3D%22%23%22%3E%0D%0A%3Cinput%20name%3D%22var1%22%3E%0D%0A%3C%2Fform%3E%0D%0A" rel="nofollow noreferrer">See it for yourself.</a></p>
<p>This bug seems limited to the <code>form</code> start tag preceding any text content and any <code>body</code> start tag.</p> | {
"question_id": 5641997,
"question_date": "2011-04-12T21:46:03.740Z",
"question_score": 224,
"tags": "html|tags",
"answer_id": 5642982,
"answer_date": "2011-04-12T23:57:38.520Z",
"answer_score": 164
} |
Please answer the following Stack Overflow question:
Title: Android Center text on canvas
<p>I'm trying to display a text using the code below.
The problem is that the text is not centered horizontally.
When I set the coordinates for <code>drawText</code>, it sets the bottom of the text at this position. I would like the text to be drawn so that the text is centered also horizontally.</p>
<p>This is a picture to display my problem further:</p>
<p><a href="https://i.stack.imgur.com/vEJNb.png"><img src="https://i.stack.imgur.com/vEJNbm.png" alt="Screenshot"></a></p>
<pre><code>@Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
//canvas.drawRGB(2, 2, 200);
Paint textPaint = new Paint();
textPaint.setARGB(200, 254, 0, 0);
textPaint.setTextAlign(Align.CENTER);
textPaint.setTypeface(font);
textPaint.setTextSize(300);
canvas.drawText("Hello", canvas.getWidth()/2, canvas.getHeight()/2 , textPaint);
}
</code></pre> | <p>Try the following:</p>
<pre><code> Paint textPaint = new Paint();
textPaint.setTextAlign(Paint.Align.CENTER);
int xPos = (canvas.getWidth() / 2);
int yPos = (int) ((canvas.getHeight() / 2) - ((textPaint.descent() + textPaint.ascent()) / 2)) ;
//((textPaint.descent() + textPaint.ascent()) / 2) is the distance from the baseline to the center.
canvas.drawText("Hello", xPos, yPos, textPaint);
</code></pre> | {
"question_id": 11120392,
"question_date": "2012-06-20T13:13:15.967Z",
"question_score": 224,
"tags": "java|android|android-activity|android-canvas|drawtext",
"answer_id": 11121873,
"answer_date": "2012-06-20T14:31:44.823Z",
"answer_score": 425
} |
Please answer the following Stack Overflow question:
Title: How do I copy a hash in Ruby?
<p>I'll admit that I'm a bit of a ruby newbie (writing rake scripts, now). In most languages, copy constructors are easy to find. Half an hour of searching didn't find it in ruby. I want to create a copy of the hash so that I can modify it without affecting the original instance. </p>
<p>Some expected methods that don't work as intended:</p>
<pre><code>h0 = { "John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
h1=Hash.new(h0)
h2=h1.to_hash
</code></pre>
<p>In the meantime, I've resorted to this inelegant workaround</p>
<pre><code>def copyhash(inputhash)
h = Hash.new
inputhash.each do |pair|
h.store(pair[0], pair[1])
end
return h
end
</code></pre> | <p>The <a href="http://ruby-doc.org/core/classes/Object.html#M000351" rel="nofollow noreferrer"><code>clone</code></a> method is Ruby's standard, built-in way to do a <a href="http://en.wikipedia.org/wiki/Object_copy#Shallow_copy" rel="nofollow noreferrer">shallow-copy</a>:</p>
<pre><code>h0 = {"John" => "Adams", "Thomas" => "Jefferson"}
# => {"John"=>"Adams", "Thomas"=>"Jefferson"}
h1 = h0.clone
# => {"John"=>"Adams", "Thomas"=>"Jefferson"}
h1["John"] = "Smith"
# => "Smith"
h1
# => {"John"=>"Smith", "Thomas"=>"Jefferson"}
h0
# => {"John"=>"Adams", "Thomas"=>"Jefferson"}
</code></pre>
<p>Note that the behavior may be overridden:</p>
<blockquote>
<p>This method may have class-specific behavior. If so, that behavior will be documented under the <code>#initialize_copy</code> method of the class.</p>
</blockquote> | {
"question_id": 4157399,
"question_date": "2010-11-11T17:36:59.953Z",
"question_score": 224,
"tags": "ruby|serialization|hashmap|copy|deep-copy",
"answer_id": 4157438,
"answer_date": "2010-11-11T17:41:06.470Z",
"answer_score": 249
} |
Please answer the following Stack Overflow question:
Title: Printing a variable memory address in swift
<p>Is there anyway to simulate the <code>[NSString stringWithFormat:@"%p", myVar]</code>, from Objective-C, in the new Swift language?</p>
<p>For example:</p>
<pre><code>let str = "A String"
println(" str value \(str) has address: ?")
</code></pre> | <h1>Swift 2</h1>
<p>This is now part of the standard library: <code>unsafeAddressOf</code>. </p>
<pre><code>/// Return an UnsafePointer to the storage used for `object`. There's
/// not much you can do with this other than use it to identify the
/// object
</code></pre>
<h1>Swift 3</h1>
<p>For Swift 3, use <code>withUnsafePointer</code>:</p>
<pre><code>var str = "A String"
withUnsafePointer(to: &str) {
print(" str value \(str) has address: \($0)")
}
</code></pre> | {
"question_id": 24058906,
"question_date": "2014-06-05T11:22:32.893Z",
"question_score": 224,
"tags": "swift|debugging|memory-address",
"answer_id": 29741007,
"answer_date": "2015-04-20T06:50:09.543Z",
"answer_score": 131
} |
Please answer the following Stack Overflow question:
Title: How can I trigger a Kubernetes Scheduled Job manually?
<p>I've created a <a href="https://kubernetes.io/docs/user-guide/cron-jobs/" rel="noreferrer">Kubernetes Scheduled Job</a>, which runs twice a day according to its schedule. However, I would like to trigger it manually for testing purposes. How can I do this?</p> | <p>The issue <a href="https://github.com/kubernetes/kubernetes/issues/47538" rel="noreferrer">#47538</a> that <a href="https://stackoverflow.com/a/46062397/2884309">@jdf mentioned</a> is now closed and this is now possible. The original implementation can be found <a href="https://github.com/kubernetes/kubernetes/commit/5b57c2db0067c8a16681fe9ec57ace3ad0342c8f" rel="noreferrer">here</a> but the syntax has changed.</p>
<p>With kubectl v1.10.1+ the command is:</p>
<p><code>kubectl create job --from=cronjob/<cronjob-name> <job-name></code></p>
<p>It seems to be backwardly compatible with older clusters as it worked for me on v0.8.x.</p> | {
"question_id": 40401795,
"question_date": "2016-11-03T12:42:10.327Z",
"question_score": 224,
"tags": "scheduled-tasks|kubernetes|google-kubernetes-engine",
"answer_id": 50041304,
"answer_date": "2018-04-26T11:02:21.917Z",
"answer_score": 346
} |
Please answer the following Stack Overflow question:
Title: Explanation of BASE terminology
<p>The <strong>BASE</strong> acronym is used to describe the properties of certain databases, usually NoSQL databases. It's often referred to as the opposite of <a href="http://en.wikipedia.org/wiki/ACID" rel="noreferrer">ACID</a>.</p>
<p>There are only few articles that touch upon the details of BASE, whereas ACID has plenty of articles that elaborate on each of the atomicity, consistency, isolation and durability properties. Wikipedia only devotes <a href="http://en.wikipedia.org/wiki/Eventual_consistency" rel="noreferrer">a few lines</a> to the term.</p>
<p>This leaves me with some questions about <strong>the definition</strong>:</p>
<blockquote>
<p><b>B</b>asically <b>A</b>vailable, <b>S</b>oft state, <b>E</b>ventual consistency</p>
</blockquote>
<p>I have interpreted these properties as follows, using <a href="http://queue.acm.org/detail.cfm?id=1394128" rel="noreferrer">this article</a> and my imagination:</p>
<p><strong>Basically available</strong> could refer to the perceived availability of the data. If a single node fails, part of the data won't be available, but the entire data layer stays operational.</p>
<ul>
<li>Is this interpretation correct, or does it refer to something else?</li>
<li><strong>Update:</strong> deducing from <a href="https://stackoverflow.com/questions/3342497/explanation-of-base-terminology/3342749#3342749">Mau's answer</a>, could it mean the entire data layer is always accepting new data, i.e. there are no locking scenarios that prevent data from being inserted immediately?</li>
</ul>
<p><strong>Soft state</strong>: All I could find was the concept of data needing a period refresh. Without a refresh, the data will expire or be deleted.</p>
<ul>
<li>Automatic deletion of data in a database seems strange to me.</li>
<li>Expired or stale data makes more sense. But this concept would apply to any type of redundant data storage, not just NoSQL. Does it describe something else then?</li>
</ul>
<p><strong>Eventual consistency</strong> means that updates will eventually ripple through to all servers, given enough time.</p>
<ul>
<li>This property is clear to me.</li>
</ul>
<hr>
<p>Can someone explain these properties in detail?</p>
<p>Or is it just a far-fetched and meaningless acronym that refers to the concepts of acids and bases as found in chemistry?</p> | <p>The BASE acronym was defined by <a href="http://en.wikipedia.org/wiki/Eric_Brewer_%28scientist%29" rel="noreferrer">Eric Brewer</a>, who is also known for formulating the <a href="http://en.wikipedia.org/wiki/CAP_theorem" rel="noreferrer">CAP theorem</a>.</p>
<p>The CAP theorem states that a distributed computer system cannot guarantee all of the following three properties at the same time:</p>
<ul>
<li>Consistency</li>
<li>Availability</li>
<li>Partition tolerance</li>
</ul>
<p>A BASE system gives up on consistency.</p>
<ul>
<li><strong>Basically available</strong> indicates that the system <em>does</em> guarantee availability, in terms of the CAP theorem.</li>
<li><strong>Soft state</strong> indicates that the state of the system may change over time, even without input. This is because of the eventual consistency model.</li>
<li><strong>Eventual consistency</strong> indicates that the system will become consistent over time, given that the system doesn't receive input during that time.</li>
</ul>
<p>Brewer does admit that <a href="http://www.julianbrowne.com/article/viewer/brewers-cap-theorem" rel="noreferrer">the acronym is contrived</a>:</p>
<blockquote>
<p>I came up with [the BASE] acronym with my students in their office earlier that year. I agree it is contrived a bit, but so is "ACID" -- much more than people realize, so we figured it was good enough.</p>
</blockquote> | {
"question_id": 3342497,
"question_date": "2010-07-27T10:06:01.870Z",
"question_score": 224,
"tags": "database|nosql|terminology|definition|base-db",
"answer_id": 3382260,
"answer_date": "2010-08-01T13:48:42.647Z",
"answer_score": 240
} |
Please answer the following Stack Overflow question:
Title: Tracking Google Analytics Page Views with AngularJS
<p>I'm setting up a new app using AngularJS as the frontend. Everything on the client side is done with HTML5 pushstate and I'd like to be able to track my page views in Google Analytics.</p> | <p>If you're using <code>ng-view</code> in your Angular app you can listen for the <code>$viewContentLoaded</code> event and push a tracking event to Google Analytics.</p>
<p>Assuming you've set up your tracking code in your main index.html file with a name of <code>var _gaq</code> and MyCtrl is what you've defined in the <code>ng-controller</code> directive.</p>
<pre><code>function MyCtrl($scope, $location, $window) {
$scope.$on('$viewContentLoaded', function(event) {
$window._gaq.push(['_trackPageView', $location.url()]);
});
}
</code></pre>
<p><strong>UPDATE:</strong>
for new version of google-analytics use this one</p>
<pre><code>function MyCtrl($scope, $location, $window) {
$scope.$on('$viewContentLoaded', function(event) {
$window.ga('send', 'pageview', { page: $location.url() });
});
}
</code></pre> | {
"question_id": 10713708,
"question_date": "2012-05-23T05:01:29.037Z",
"question_score": 224,
"tags": "google-analytics|angularjs",
"answer_id": 10713709,
"answer_date": "2012-05-23T05:01:29.273Z",
"answer_score": 241
} |
Please answer the following Stack Overflow question:
Title: Is there a C++ gdb GUI for Linux?
<p>Briefly: Does anyone know of a GUI for gdb that brings it on par or close to the feature set you get in the more recent version of Visual C++?</p>
<p>In detail: As someone who has spent a lot of time programming in Windows, one of the larger stumbling blocks I've found whenever I have to code C++ in Linux is that debugging anything using commandline gdb takes me several times longer than it does in Visual Studio, and it does not seem to be getting better with practice. Some things are just easier or faster to express graphically.</p>
<p>Specifically, I'm looking for a GUI that:</p>
<ul>
<li>Handles all the basics like stepping over & into code, watch variables and breakpoints</li>
<li>Understands and can display the contents of complex & nested C++ data types</li>
<li>Doesn't get confused by and preferably can intelligently step through templated code and data structures while displaying relevant information such as the parameter types</li>
<li>Can handle threaded applications and switch between different threads to step through or view the state of</li>
<li>Can handle attaching to an already-started process or reading a core dump, in addition to starting the program up in gdb</li>
</ul>
<p>If such a program does not exist, then I'd like to hear about experiences people have had with programs that meet at least some of the bullet points.
Does anyone have any recommendations?</p>
<p><strong>Edit:</strong><br>
Listing out the possibilities is great, and I'll take what I can get, but it would be even more helpful if you could include in your responses:<br>
(a) Whether or not you've actually used this GUI and if so, what positive/negative feedback you have about it.<br>
(b) If you know, which of the above-mentioned features are/aren't supported</p>
<p>Lists are easy to come by, sites like this are great because you can get an idea of people's personal experiences with applications.</p> | <p>You won't find <em>anything</em> overlaying GDB which can compete with the raw power of the Visual Studio debugger. It's just too powerful, and it's just too well integrated inside the IDE. </p>
<p>For a Linux alternative, try DDD if free software is your thing.</p> | {
"question_id": 79023,
"question_date": "2008-09-17T01:42:57.143Z",
"question_score": 224,
"tags": "c++|linux|gdb|debugging",
"answer_id": 79050,
"answer_date": "2008-09-17T01:45:42.397Z",
"answer_score": 54
} |
Please answer the following Stack Overflow question:
Title: What is the best way to implement nested dictionaries?
<p>I have a data structure which essentially amounts to a nested dictionary. Let's say it looks like this:</p>
<pre><code>{'new jersey': {'mercer county': {'plumbers': 3,
'programmers': 81},
'middlesex county': {'programmers': 81,
'salesmen': 62}},
'new york': {'queens county': {'plumbers': 9,
'salesmen': 36}}}
</code></pre>
<p>Now, maintaining and creating this is pretty painful; every time I have a new state/county/profession I have to create the lower layer dictionaries via obnoxious try/catch blocks. Moreover, I have to create annoying nested iterators if I want to go over all the values. </p>
<p>I could also use tuples as keys, like such:</p>
<pre><code>{('new jersey', 'mercer county', 'plumbers'): 3,
('new jersey', 'mercer county', 'programmers'): 81,
('new jersey', 'middlesex county', 'programmers'): 81,
('new jersey', 'middlesex county', 'salesmen'): 62,
('new york', 'queens county', 'plumbers'): 9,
('new york', 'queens county', 'salesmen'): 36}
</code></pre>
<p>This makes iterating over the values very simple and natural, but it is more syntactically painful to do things like aggregations and looking at subsets of the dictionary (e.g. if I just want to go state-by-state).</p>
<p>Basically, sometimes I want to think of a nested dictionary as a flat dictionary, and sometimes I want to think of it indeed as a complex hierarchy. I could wrap this all in a class, but it seems like someone might have done this already. Alternatively, it seems like there might be some really elegant syntactical constructions to do this. </p>
<p>How could I do this better?</p>
<p>Addendum: I'm aware of <code>setdefault()</code> but it doesn't really make for clean syntax. Also, each sub-dictionary you create still needs to have <code>setdefault()</code> manually set.</p> | <blockquote>
<h2>What is the best way to implement nested dictionaries in Python?</h2>
</blockquote>
<p>This is a bad idea, don't do it. Instead, use a regular dictionary and use <code>dict.setdefault</code> where apropos, so when keys are missing under normal usage you get the expected <code>KeyError</code>. If you insist on getting this behavior, here's how to shoot yourself in the foot:</p>
<p>Implement <code>__missing__</code> on a <code>dict</code> subclass to set and return a new instance.</p>
<p>This approach has been available <a href="http://docs.python.org/2/library/stdtypes.html#dict" rel="noreferrer">(and documented)</a> since Python 2.5, and (particularly valuable to me) <strong>it pretty prints just like a normal dict</strong>, instead of the ugly printing of an autovivified defaultdict:</p>
<pre><code>class Vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)() # retain local pointer to value
return value # faster to return than dict lookup
</code></pre>
<p>(Note <code>self[key]</code> is on the left-hand side of assignment, so there's no recursion here.)</p>
<p>and say you have some data:</p>
<pre><code>data = {('new jersey', 'mercer county', 'plumbers'): 3,
('new jersey', 'mercer county', 'programmers'): 81,
('new jersey', 'middlesex county', 'programmers'): 81,
('new jersey', 'middlesex county', 'salesmen'): 62,
('new york', 'queens county', 'plumbers'): 9,
('new york', 'queens county', 'salesmen'): 36}
</code></pre>
<p>Here's our usage code:</p>
<pre><code>vividict = Vividict()
for (state, county, occupation), number in data.items():
vividict[state][county][occupation] = number
</code></pre>
<p>And now:</p>
<pre><code>>>> import pprint
>>> pprint.pprint(vividict, width=40)
{'new jersey': {'mercer county': {'plumbers': 3,
'programmers': 81},
'middlesex county': {'programmers': 81,
'salesmen': 62}},
'new york': {'queens county': {'plumbers': 9,
'salesmen': 36}}}
</code></pre>
<h2>Criticism</h2>
<p>A criticism of this type of container is that if the user misspells a key, our code could fail silently:</p>
<pre><code>>>> vividict['new york']['queens counyt']
{}
</code></pre>
<p>And additionally now we'd have a misspelled county in our data:</p>
<pre><code>>>> pprint.pprint(vividict, width=40)
{'new jersey': {'mercer county': {'plumbers': 3,
'programmers': 81},
'middlesex county': {'programmers': 81,
'salesmen': 62}},
'new york': {'queens county': {'plumbers': 9,
'salesmen': 36},
'queens counyt': {}}}
</code></pre>
<h1>Explanation:</h1>
<p>We're just providing another nested instance of our class <code>Vividict</code> whenever a key is accessed but missing. (Returning the value assignment is useful because it avoids us additionally calling the getter on the dict, and unfortunately, we can't return it as it is being set.)</p>
<p>Note, these are the same semantics as the most upvoted answer but in half the lines of code - nosklo's implementation:</p>
<blockquote>
<pre><code>class AutoVivification(dict):
"""Implementation of perl's autovivification feature."""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
value = self[item] = type(self)()
return value
</code></pre>
</blockquote>
<h2>Demonstration of Usage</h2>
<p>Below is just an example of how this dict could be easily used to create a nested dict structure on the fly. This can quickly create a hierarchical tree structure as deeply as you might want to go.</p>
<pre><code>import pprint
class Vividict(dict):
def __missing__(self, key):
value = self[key] = type(self)()
return value
d = Vividict()
d['foo']['bar']
d['foo']['baz']
d['fizz']['buzz']
d['primary']['secondary']['tertiary']['quaternary']
pprint.pprint(d)
</code></pre>
<p>Which outputs:</p>
<pre><code>{'fizz': {'buzz': {}},
'foo': {'bar': {}, 'baz': {}},
'primary': {'secondary': {'tertiary': {'quaternary': {}}}}}
</code></pre>
<p>And as the last line shows, it pretty prints beautifully and in order for manual inspection. But if you want to visually inspect your data, implementing <code>__missing__</code> to set a new instance of its class to the key and return it is a far better solution.</p>
<h1>Other alternatives, for contrast:</h1>
<h2><code>dict.setdefault</code></h2>
<p>Although the asker thinks this isn't clean, I find it preferable to the <code>Vividict</code> myself.</p>
<pre><code>d = {} # or dict()
for (state, county, occupation), number in data.items():
d.setdefault(state, {}).setdefault(county, {})[occupation] = number
</code></pre>
<p>and now:</p>
<pre><code>>>> pprint.pprint(d, width=40)
{'new jersey': {'mercer county': {'plumbers': 3,
'programmers': 81},
'middlesex county': {'programmers': 81,
'salesmen': 62}},
'new york': {'queens county': {'plumbers': 9,
'salesmen': 36}}}
</code></pre>
<p>A misspelling would fail noisily, and not clutter our data with bad information:</p>
<pre><code>>>> d['new york']['queens counyt']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'queens counyt'
</code></pre>
<p>Additionally, I think setdefault works great when used in loops and you don't know what you're going to get for keys, but repetitive usage becomes quite burdensome, and I don't think anyone would want to keep up the following:</p>
<pre><code>d = dict()
d.setdefault('foo', {}).setdefault('bar', {})
d.setdefault('foo', {}).setdefault('baz', {})
d.setdefault('fizz', {}).setdefault('buzz', {})
d.setdefault('primary', {}).setdefault('secondary', {}).setdefault('tertiary', {}).setdefault('quaternary', {})
</code></pre>
<p>Another criticism is that setdefault requires a new instance whether it is used or not. However, Python (or at least CPython) is rather smart about handling unused and unreferenced new instances, for example, it reuses the location in memory:</p>
<pre><code>>>> id({}), id({}), id({})
(523575344, 523575344, 523575344)
</code></pre>
<h2>An auto-vivified defaultdict</h2>
<p>This is a neat looking implementation, and usage in a script that you're not inspecting the data on would be as useful as implementing <code>__missing__</code>:</p>
<pre><code>from collections import defaultdict
def vivdict():
return defaultdict(vivdict)
</code></pre>
<p>But if you need to inspect your data, the results of an auto-vivified defaultdict populated with data in the same way looks like this:</p>
<pre><code>>>> d = vivdict(); d['foo']['bar']; d['foo']['baz']; d['fizz']['buzz']; d['primary']['secondary']['tertiary']['quaternary']; import pprint;
>>> pprint.pprint(d)
defaultdict(<function vivdict at 0x17B01870>, {'foo': defaultdict(<function vivdict
at 0x17B01870>, {'baz': defaultdict(<function vivdict at 0x17B01870>, {}), 'bar':
defaultdict(<function vivdict at 0x17B01870>, {})}), 'primary': defaultdict(<function
vivdict at 0x17B01870>, {'secondary': defaultdict(<function vivdict at 0x17B01870>,
{'tertiary': defaultdict(<function vivdict at 0x17B01870>, {'quaternary': defaultdict(
<function vivdict at 0x17B01870>, {})})})}), 'fizz': defaultdict(<function vivdict at
0x17B01870>, {'buzz': defaultdict(<function vivdict at 0x17B01870>, {})})})
</code></pre>
<p>This output is quite inelegant, and the results are quite unreadable. The solution typically given is to recursively convert back to a dict for manual inspection. This non-trivial solution is left as an exercise for the reader.</p>
<h1>Performance</h1>
<p>Finally, let's look at performance. I'm subtracting the costs of instantiation.</p>
<pre><code>>>> import timeit
>>> min(timeit.repeat(lambda: {}.setdefault('foo', {}))) - min(timeit.repeat(lambda: {}))
0.13612580299377441
>>> min(timeit.repeat(lambda: vivdict()['foo'])) - min(timeit.repeat(lambda: vivdict()))
0.2936999797821045
>>> min(timeit.repeat(lambda: Vividict()['foo'])) - min(timeit.repeat(lambda: Vividict()))
0.5354437828063965
>>> min(timeit.repeat(lambda: AutoVivification()['foo'])) - min(timeit.repeat(lambda: AutoVivification()))
2.138362169265747
</code></pre>
<p>Based on performance, <code>dict.setdefault</code> works the best. I'd highly recommend it for production code, in cases where you care about execution speed.</p>
<p>If you need this for interactive use (in an IPython notebook, perhaps) then performance doesn't really matter - in which case, I'd go with Vividict for readability of the output. Compared to the AutoVivification object (which uses <code>__getitem__</code> instead of <code>__missing__</code>, which was made for this purpose) it is far superior.</p>
<h1>Conclusion</h1>
<p>Implementing <code>__missing__</code> on a subclassed <code>dict</code> to set and return a new instance is slightly more difficult than alternatives but has the benefits of</p>
<ul>
<li>easy instantiation</li>
<li>easy data population</li>
<li>easy data viewing</li>
</ul>
<p>and because it is less complicated and more performant than modifying <code>__getitem__</code>, it should be preferred to that method.</p>
<p>Nevertheless, it has drawbacks:</p>
<ul>
<li>Bad lookups will fail silently.</li>
<li>The bad lookup will remain in the dictionary.</li>
</ul>
<p>Thus I personally prefer <code>setdefault</code> to the other solutions, and have in every situation where I have needed this sort of behavior.</p> | {
"question_id": 635483,
"question_date": "2009-03-11T17:09:21.560Z",
"question_score": 224,
"tags": "python|data-structures|dictionary|mapping|autovivification",
"answer_id": 19829714,
"answer_date": "2013-11-07T06:53:24.557Z",
"answer_score": 202
} |
Please answer the following Stack Overflow question:
Title: Jasmine.js comparing arrays
<p>Is there a way in jasmine.js to check if two arrays are equal, for example:</p>
<pre><code>arr = [1, 2, 3]
expect(arr).toBe([1, 2, 3])
expect(arr).toEqual([1, 2, 3])
</code></pre>
<p>Neither seems to work.</p> | <p>Just did the test and it works with <code>toEqual</code></p>
<p>please find my test:</p>
<p><a href="http://jsfiddle.net/7q9N7/3/" rel="noreferrer">http://jsfiddle.net/7q9N7/3/</a></p>
<pre><code>describe('toEqual', function() {
it('passes if arrays are equal', function() {
var arr = [1, 2, 3];
expect(arr).toEqual([1, 2, 3]);
});
});
</code></pre>
<p><strong>Just for information:</strong></p>
<blockquote>
<p>toBe() versus toEqual(): toEqual() checks equivalence. toBe(), on the
other hand, makes sure that they're the exact same object.</p>
</blockquote> | {
"question_id": 15717844,
"question_date": "2013-03-30T11:10:08.383Z",
"question_score": 224,
"tags": "javascript|jasmine",
"answer_id": 15717993,
"answer_date": "2013-03-30T11:25:35.530Z",
"answer_score": 363
} |
Please answer the following Stack Overflow question:
Title: Subject vs BehaviorSubject vs ReplaySubject in Angular
<p>I've been looking to understand those 3:</p>
<ul>
<li><a href="https://rxjs.dev/api/index/class/Subject" rel="noreferrer">Subject</a></li>
<li><a href="https://rxjs.dev/api/index/class/BehaviorSubject" rel="noreferrer">BehaviorSubject</a></li>
<li><a href="https://rxjs.dev/api/index/class/ReplaySubject" rel="noreferrer">ReplaySubject</a></li>
</ul>
<p>I would like to use them and know when and why, what are the benefits of using them and although I've read the documentation, watched tutorials and searched google I've failed to make any sense of this.</p>
<p>So what are their purpose? A real-world case would be most appreciated it does not have to even code.</p>
<p>I would prefer a clean explanation not just "a+b => c you are subscribed to ...."</p>
<p>Thank you</p> | <p>It really comes down to behavior and semantics. With a </p>
<ul>
<li><p><code>Subject</code> - a subscriber will only get published values that were emitted <em>after</em> the subscription. Ask yourself, is that what you want? Does the subscriber need to know anything about previous values? If not, then you can use this, otherwise choose one of the others. For example, with component-to-component communication. Say you have a component that publishes events for other components on a button click. You can use a service with a subject to communicate.</p></li>
<li><p><code>BehaviorSubject</code> - the last value is cached. A subscriber will get the latest value upon initial subscription. The semantics for this subject is to represent a value that changes over time. For example a logged in user. The initial user might be an anonymous user. But once a user logs in, then the new value is the authenticated user state.</p>
<p>The <code>BehaviorSubject</code> is initialized with an initial value. This is sometimes important to coding preference. Say for instance you initialize it with a <code>null</code>. Then in your subscription, you need to do a null check. Maybe OK, or maybe annoying.</p></li>
<li><p><code>ReplaySubject</code> - it can cache up to a specified number of emissions. Any subscribers will get all the cached values upon subscription. When would you need this behavior? Honestly, I have not had any need for such behavior, except for the following case:</p>
<p>If you initialize a <code>ReplaySubject</code> with a buffer size of <code>1</code>, then it actually <em>behaves</em> just like a <code>BehaviorSubject</code>. The last value is always cached, so it acts like a value changing over time. With this, there is no need for a <code>null</code> check like in the case of the <code>BehaviorSubject</code> initialized with a <code>null</code>. In this instance, no value is ever emitted to the subscriber until the first publishing.</p></li>
</ul>
<p>So it really comes down to the behavior you are expecting (as for which one to use). Most of the time you will probably want to use a <code>BehaviorSubject</code> because what you really want to represent is that "value over time" semantic. But I personally don't see anything wrong with the substitution of <code>ReplaySubject</code> initialized with <code>1</code>. </p>
<p>What you want to <em>avoid</em> is using the vanilla <code>Subject</code> when what you really need is some caching behavior. Take for example you are writing a routing guard or a resolve. You fetch some data in that guard and set it in a service <code>Subject</code>. Then in the routed component you subscribe to the service subject to try to get that value that was emitted in the guard. OOPs. Where's the value? It was already emitted, DUH. Use a "caching" subject!</p>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/a/39885817/2587435">What are RxJS Subject's and the benefits of using them?</a></li>
</ul> | {
"question_id": 43118769,
"question_date": "2017-03-30T13:05:30.563Z",
"question_score": 224,
"tags": "javascript|angular|rxjs|reactive-programming|angular2-observables",
"answer_id": 43119768,
"answer_date": "2017-03-30T13:45:24.400Z",
"answer_score": 447
} |
Please answer the following Stack Overflow question:
Title: What does __FILE__ mean in Ruby?
<p>I see this all the time in Ruby:</p>
<pre><code>require File.dirname(__FILE__) + "/../../config/environment"
</code></pre>
<p>What does <code>__FILE__</code> mean?</p> | <p>It is a reference to the current file name. In the file <code>foo.rb</code>, <code>__FILE__</code> would be interpreted as <code>"foo.rb"</code>.</p>
<p><strong>Edit:</strong> Ruby 1.9.2 and 1.9.3 appear to behave a little differently from what Luke Bayes said in <a href="https://stackoverflow.com/questions/224379/what-does-file-mean-in-ruby#comment1243516_224383">his comment</a>. With these files:</p>
<pre class="lang-ruby prettyprint-override"><code># test.rb
puts __FILE__
require './dir2/test.rb'
</code></pre>
<pre class="lang-ruby prettyprint-override"><code># dir2/test.rb
puts __FILE__
</code></pre>
<p>Running <code>ruby test.rb</code> will output</p>
<pre class="lang-none prettyprint-override"><code>test.rb
/full/path/to/dir2/test.rb
</code></pre> | {
"question_id": 224379,
"question_date": "2008-10-22T03:28:19.897Z",
"question_score": 224,
"tags": "ruby",
"answer_id": 224383,
"answer_date": "2008-10-22T03:30:09.800Z",
"answer_score": 154
} |
Please answer the following Stack Overflow question:
Title: Latest version of Xcode stuck on installation (12.5)
<p>I just updated my mac to macOS Big Sur, and am trying to update to the next version of XCode. It has been on 75-80% progress for hours:
<a href="https://i.stack.imgur.com/udVjw.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/udVjw.jpg" alt="enter image description here" /></a></p>
<p>Also, when I go to launchpad I see this:</p>
<p><a href="https://i.stack.imgur.com/dJJr3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/dJJr3.png" alt="enter image description here" /></a></p>
<p>Is anyone else having this issue or know how to fix it?</p> | <p>As a first test to check if everything is just going fine but really slow, try this:</p>
<ul>
<li>Keep the App Store window open (thanks to @Dhruv Saraswat to point this out).</li>
<li>Open the "Console" app (not the "Terminal", but the "Console")</li>
<li>Go to the "Search bar" and type "App store".</li>
<li>Push "Start" button.</li>
<li>Log lines will be added from time to time showing you how the installation process goes. In my case, I saw "... Completed: 825 of 1000", and some time later I got "... Completed: 826 to 1000", and so on.</li>
</ul>
<p>That way you can at least check if everything is working, although really slow. You can then guess how long it will take to the "Completed: 1000 to 1000" step in your own situation.</p> | {
"question_id": 67900692,
"question_date": "2021-06-09T08:49:35.190Z",
"question_score": 224,
"tags": "xcode",
"answer_id": 69437989,
"answer_date": "2021-10-04T14:47:42.370Z",
"answer_score": 774
} |
Please answer the following Stack Overflow question:
Title: What is the minimum valid JSON?
<p>I've carefully read the JSON description <a href="http://json.org/">http://json.org/</a> but I'm not sure I know the answer to the simple question. What strings are the minimum possible valid JSON?</p>
<ul>
<li><code>"string"</code> is the string valid JSON?</li>
<li><code>42</code> is the simple number valid JSON?</li>
<li><code>true</code> is the boolean value a valid JSON?</li>
<li><code>{}</code> is the empty object a valid JSON?</li>
<li><code>[]</code> is the empty array a valid JSON?</li>
</ul> | <p>At the time of writing, JSON was solely described in <a href="http://www.ietf.org/rfc/rfc4627.txt" rel="noreferrer">RFC4627</a>. It describes (at the start of "2") a JSON text as being a serialized object or array.</p>
<p>This means that <em>only</em> <code>{}</code> and <code>[]</code> are valid, complete JSON strings in parsers and stringifiers which adhere to that standard.</p>
<p><em>However</em>, the introduction of ECMA-404 changes that, and the updated advice <a href="https://stackoverflow.com/questions/19569221/in-light-of-ecma-404-is-2-or-hello-considered-a-valid-json-text">can be read here</a>. I've also <a href="http://www.mattlunn.me.uk/blog/2014/01/what-is-the-minimum-valid-json/" rel="noreferrer">written a blog post</a> on the issue.</p>
<hr />
<p>To confuse the matter further however, the <code>JSON</code> object (e.g. <code>JSON.parse()</code> and <code>JSON.stringify()</code>) available in web browsers is <a href="http://es5.github.io/#x15.12" rel="noreferrer">standardised in ES5</a>, and that clearly defines the acceptable JSON texts like so:</p>
<blockquote>
<p>The JSON interchange format used in this specification is exactly that described by RFC 4627 with two exceptions:</p>
<ul>
<li><p>The top level JSONText production of the ECMAScript JSON grammar may consist of any JSONValue rather than being restricted to being a JSONObject or a JSONArray as specified by RFC 4627.</p>
</li>
<li><p><em>snipped</em></p>
</li>
</ul>
</blockquote>
<p>This would mean that <em>all</em> JSON values (including strings, nulls and numbers) are accepted by the JSON object, even though the JSON object technically adheres to RFC 4627.</p>
<p>Note that you could therefore stringify a number in a conformant browser via <code>JSON.stringify(5)</code>, which would be rejected by another parser that adheres to RFC4627, but which doesn't have the specific exception listed above. Ruby, for example, <a href="http://www.ruby-doc.org/stdlib-2.0.0/libdoc/json/rdoc/JSON.html" rel="noreferrer">would seem to be one such example which <em>only</em> accepts objects and arrays as the root</a>. PHP, on the other hand, <a href="http://us2.php.net/manual/en/function.json-decode.php#refsect1-function.json-decode-parameters" rel="noreferrer">specifically adds the exception</a> that "it will also encode and decode scalar types and NULL".</p> | {
"question_id": 18419428,
"question_date": "2013-08-24T14:08:50.983Z",
"question_score": 224,
"tags": "javascript|json|validation",
"answer_id": 18419503,
"answer_date": "2013-08-24T14:17:10.127Z",
"answer_score": 188
} |
Please answer the following Stack Overflow question:
Title: Elements order in a "for (… in …)" loop
<p>Does the "for…in" loop in Javascript loop through the hashtables/elements in the order they are declared? Is there a browser which doesn't do it in order?<br>
The object I wish to use will be declared <em>once</em> and will never be modified.</p>
<p>Suppose I have:</p>
<pre><code>var myObject = { A: "Hello", B: "World" };
</code></pre>
<p>And I further use them in:</p>
<pre><code>for (var item in myObject) alert(item + " : " + myObject[item]);
</code></pre>
<p>Can I expect 'A : "Hello"' to always come before 'B : "World"' in most decent browsers?</p> | <p><a href="http://ejohn.org/blog/javascript-in-chrome/" rel="noreferrer">Quoting John Resig</a>:</p>
<blockquote>
<p>Currently all major browsers loop over the properties of an object in the order in
which they were defined. Chrome does this as well, except for a couple cases. [...]
This behavior is explicitly left undefined by the ECMAScript specification.
In ECMA-262, section 12.6.4:</p>
<blockquote>
<p>The mechanics of enumerating the properties ... is implementation dependent.</p>
</blockquote>
<p>However, specification is quite different from implementation. All modern implementations
of ECMAScript iterate through object properties in the order in which they were defined.
Because of this the Chrome team has deemed this to be a bug and will be fixing it.</p>
</blockquote>
<p>All browsers respect definition order <a href="https://code.google.com/p/v8/issues/detail?id=164" rel="noreferrer">with the exception of Chrome</a> and Opera which do for every non-numerical property name. In these two browsers the properties are pulled in-order ahead of the first non-numerical property (this is has to do with how they implement arrays). The order is the same for <code>Object.keys</code> as well.</p>
<p>This example should make it clear what happens:</p>
<pre><code>var obj = {
"first":"first",
"2":"2",
"34":"34",
"1":"1",
"second":"second"
};
for (var i in obj) { console.log(i); };
// Order listed:
// "1"
// "2"
// "34"
// "first"
// "second"
</code></pre>
<p>The technicalities of this are less important than the fact that this may change at any time. Do not rely on things staying this way.</p>
<p>In short: <strong>Use an array if order is important to you.</strong></p> | {
"question_id": 280713,
"question_date": "2008-11-11T12:00:36.630Z",
"question_score": 224,
"tags": "javascript|for-loop",
"answer_id": 280861,
"answer_date": "2008-11-11T13:24:20.847Z",
"answer_score": 231
} |
Please answer the following Stack Overflow question:
Title: Filter Fiddler traffic
<p>Is it possible to instruct Fiddler to only show me traffic directed to a specific host name?
In other words, can Fiddler traffic be filtered for Host?</p> | <p><a href="http://fiddler2.com/documentation/KnowledgeBase/Filters" rel="noreferrer">Fiddler's Filters tab</a> can do this - set the 'Hosts' dropdown to 'Show only the following hosts' then put the name in the textbox below.</p> | {
"question_id": 4098877,
"question_date": "2010-11-04T16:29:36.423Z",
"question_score": 224,
"tags": "fiddler",
"answer_id": 4098967,
"answer_date": "2010-11-04T16:38:21.443Z",
"answer_score": 191
} |
Please answer the following Stack Overflow question:
Title: How do I forward parameters to other command in bash script?
<p>Inside my bash script, I would like to parse zero, one or two parameters (the script can recognize them), then forward the remaining parameters to a command invoked in the script. How can I do that?</p> | <p>Use the <a href="http://www.gnu.org/software/bash/manual/bashref.html#index-shift" rel="noreferrer"><code>shift</code></a> built-in command to "eat" the arguments. Then call the child process and pass it the <a href="http://www.gnu.org/software/bash/manual/bashref.html#index-_0040" rel="noreferrer"><code>"$@"</code></a> argument to include all remaining arguments. Notice the quotes, they should be kept, since they cause the expansion of the argument list to be properly quoted.</p> | {
"question_id": 1537673,
"question_date": "2009-10-08T13:05:15.363Z",
"question_score": 224,
"tags": "bash|command-line",
"answer_id": 1537695,
"answer_date": "2009-10-08T13:09:12.470Z",
"answer_score": 310
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.