input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: R - Markdown avoiding package loading messages
<p>I have been using Knitr via R-Studio, and think it is pretty neat. I have a minor issue though. When I source a file in an R-Chunk, the knitr output includes external comments as follows: </p>
<pre><code>+ FALSE Loading required package: ggplot2
+ FALSE Loading required package: gridExtra
+ FALSE Loading required package: grid
+ FALSE Loading required package: VGAM
+ FALSE Loading required package: splines
+ FALSE Loading required package: stats4
+ FALSE Attaching package: 'VGAM'
+ FALSE The following object(s) are masked from 'package:stats4':
</code></pre>
<p>I have tried to set R-chunk options in various ways but still didn't seem to avoid the problem: </p>
<pre><code>```{r echo=FALSE, cache=FALSE, results=FALSE, warning=FALSE, comment=FALSE, warning=FALSE}
source("C:/Rscripts/source.R");
```
</code></pre>
<p>Is there any way to comment out these messages?</p> | <p>You can use <code>include=FALSE</code> to exclude everything in a chunk.</p>
<pre><code>```{r include=FALSE}
source("C:/Rscripts/source.R")
```
</code></pre>
<p>If you only want to suppress messages, use <code>message=FALSE</code> instead:</p>
<pre><code>```{r message=FALSE}
source("C:/Rscripts/source.R")
```
</code></pre> | {
"question_id": 13090838,
"question_date": "2012-10-26T16:30:43.150Z",
"question_score": 231,
"tags": "r|markdown|knitr|rstudio|r-markdown",
"answer_id": 13090913,
"answer_date": "2012-10-26T16:35:57.137Z",
"answer_score": 307
} |
Please answer the following Stack Overflow question:
Title: Select rows which are not present in other table
<p>I've got two postgresql tables: </p>
<pre class="lang-none prettyprint-override"><code>table name column names
----------- ------------------------
login_log ip | etc.
ip_location ip | location | hostname | etc.
</code></pre>
<p>I want to get every IP address from <code>login_log</code> which doesn't have a row in <code>ip_location</code>.<br>
I tried this query but it throws a syntax error.</p>
<pre><code>SELECT login_log.ip
FROM login_log
WHERE NOT EXIST (SELECT ip_location.ip
FROM ip_location
WHERE login_log.ip = ip_location.ip)
</code></pre>
<blockquote>
<pre><code>ERROR: syntax error at or near "SELECT"
LINE 3: WHERE NOT EXIST (SELECT ip_location.ip`
</code></pre>
</blockquote>
<p>I'm also wondering if this query (with adjustments to make it work) is the best performing query for this purpose.</p> | <p>There are basically 4 techniques for this task, all of them standard SQL.</p>
<h3><a href="https://www.postgresql.org/docs/current/functions-subquery.html#FUNCTIONS-SUBQUERY-EXISTS" rel="noreferrer"><code>NOT EXISTS</code></a></h3>
<p>Often fastest in Postgres. </p>
<pre><code>SELECT ip
FROM login_log l
WHERE NOT EXISTS (
SELECT -- SELECT list mostly irrelevant; can just be empty in Postgres
FROM ip_location
WHERE ip = l.ip
);
</code></pre>
<p>Also consider:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/7710153/what-is-easier-to-read-in-exists-subqueries">What is easier to read in EXISTS subqueries?</a></li>
</ul>
<h3><a href="https://www.postgresql.org/docs/current/queries-table-expressions.html#QUERIES-FROM" rel="noreferrer"><code>LEFT JOIN / IS NULL</code></a></h3>
<p>Sometimes this is fastest. Often shortest. Often results in the same query plan as <code>NOT EXISTS</code>.</p>
<pre><code>SELECT l.ip
FROM login_log l
LEFT JOIN ip_location i USING (ip) -- short for: ON i.ip = l.ip
WHERE i.ip IS NULL;
</code></pre>
<h3><a href="https://www.postgresql.org/docs/current/queries-union.html" rel="noreferrer"><code>EXCEPT</code></a></h3>
<p>Short. Not as easily integrated in more complex queries.</p>
<pre><code>SELECT ip
FROM login_log
EXCEPT ALL -- "ALL" keeps duplicates and makes it faster
SELECT ip
FROM ip_location;
</code></pre>
<p>Note that (<a href="https://www.postgresql.org/docs/current/queries-union.html" rel="noreferrer">per documentation</a>):</p>
<blockquote>
<p>duplicates are eliminated unless <code>EXCEPT ALL</code> is used.</p>
</blockquote>
<p>Typically, you'll want the <code>ALL</code> keyword. If you don't care, still use it because it makes the query <em>faster</em>.</p>
<h3><a href="https://www.postgresql.org/docs/current/functions-subquery.html#FUNCTIONS-SUBQUERY-NOTIN" rel="noreferrer"><code>NOT IN</code></a></h3>
<p>Only good without <code>NULL</code> values or if you know to handle <code>NULL</code> properly. <a href="https://wiki.postgresql.org/wiki/Don%27t_Do_This#Don.27t_use_NOT_IN" rel="noreferrer">I would <strong><em>not</em></strong> use it for this purpose.</a> Also, performance can deteriorate with bigger tables.</p>
<pre><code>SELECT ip
FROM login_log
WHERE ip NOT IN (
SELECT DISTINCT ip -- DISTINCT is optional
FROM ip_location
);
</code></pre>
<p><code>NOT IN</code> carries a "trap" for <code>NULL</code> values on either side:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/14251180/postgresql-records-where-join-doesnt-exist/14260510#14260510">Find records where join doesn't exist</a></li>
</ul>
<p>Similar question on dba.SE targeted at MySQL:</p>
<ul>
<li><a href="https://dba.stackexchange.com/q/16650/3684">Select rows where value of second column is not present in first column</a></li>
</ul> | {
"question_id": 19363481,
"question_date": "2013-10-14T15:15:29.830Z",
"question_score": 231,
"tags": "sql|postgresql|null|left-join|exists",
"answer_id": 19364694,
"answer_date": "2013-10-14T16:22:17.437Z",
"answer_score": 534
} |
Please answer the following Stack Overflow question:
Title: How to convert a Base64 string into a Bitmap image to show it in a ImageView?
<p>I have a Base64 String that represents a BitMap image.</p>
<p>I need to transform that String into a BitMap image again to use it on a ImageView in my Android app</p>
<p>How to do it?</p>
<p>This is the code that I use to transform the image into the base64 String: </p>
<pre><code>//proceso de transformar la imagen BitMap en un String:
//android:src="c:\logo.png"
Resources r = this.getResources();
Bitmap bm = BitmapFactory.decodeResource(r, R.drawable.logo);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
//String encodedImage = Base64.encode(b, Base64.DEFAULT);
encodedImage = Base64.encodeBytes(b);
</code></pre> | <p>You can just basically revert your code using some other built in methods.</p>
<pre><code>byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
</code></pre> | {
"question_id": 4837110,
"question_date": "2011-01-29T13:28:19.240Z",
"question_score": 231,
"tags": "android|base64|imageview",
"answer_id": 4837293,
"answer_date": "2011-01-29T14:07:44.547Z",
"answer_score": 419
} |
Please answer the following Stack Overflow question:
Title: How to store standard error in a variable
<p>Let's say I have a script like the following:</p>
<p>useless.sh</p>
<pre><code>echo "This Is Error" 1>&2
echo "This Is Output"
</code></pre>
<p>And I have another shell script:</p>
<p>alsoUseless.sh</p>
<pre><code>./useless.sh | sed 's/Output/Useless/'
</code></pre>
<p>I want to capture "This Is Error", or any other stderr from useless.sh, into a variable.
Let's call it ERROR.</p>
<p>Notice that I am using stdout for something. I want to continue using stdout, so redirecting stderr into stdout is not helpful, in this case.</p>
<p>So, basically, I want to do</p>
<pre><code>./useless.sh 2> $ERROR | ...
</code></pre>
<p>but that obviously doesn't work.</p>
<p>I also know that I could do</p>
<pre><code>./useless.sh 2> /tmp/Error
ERROR=`cat /tmp/Error`
</code></pre>
<p>but that's ugly and unnecessary.</p>
<p>Unfortunately, if no answers turn up here that's what I'm going to have to do.</p>
<p>I'm hoping there's another way.</p>
<p>Anyone have any better ideas?</p> | <p>It would be neater to capture the error file thus:</p>
<pre><code>ERROR=$(</tmp/Error)
</code></pre>
<p>The shell recognizes this and doesn't have to run '<code>cat</code>' to get the data.</p>
<p>The bigger question is hard. I don't think there's an easy way to do it. You'd have to build the entire pipeline into the sub-shell, eventually sending its final standard output to a file, so that you can redirect the errors to standard output.</p>
<pre><code>ERROR=$( { ./useless.sh | sed s/Output/Useless/ > outfile; } 2>&1 )
</code></pre>
<p>Note that the semi-colon is needed (in classic shells - Bourne, Korn - for sure; probably in Bash too). The '<code>{}</code>' does I/O redirection over the enclosed commands. As written, it would capture errors from <code>sed</code> too.</p>
<blockquote>
<p><strong>WARNING:</strong> Formally untested code - use at own risk.</p>
</blockquote> | {
"question_id": 962255,
"question_date": "2009-06-07T16:38:11.657Z",
"question_score": 231,
"tags": "bash|shell|redirect|variables|stderr",
"answer_id": 962306,
"answer_date": "2009-06-07T16:57:36.297Z",
"answer_score": 124
} |
Please answer the following Stack Overflow question:
Title: What is the difference between a cer, pvk, and pfx file?
<p>What is the difference between a cer, pvk, and pfx file? Also, which files do I keep and which am I expected to give to my counter-parties?</p> | <p>Windows uses .cer extension for an X.509 certificate. These can be in "binary" (ASN.1 DER), or it can be encoded with Base-64 and have a header and footer applied (PEM); Windows will recognize either. To verify the integrity of a certificate, you have to check its signature using the issuer's public key... which is, in turn, another certificate.</p>
<p>Windows uses .pfx for a PKCS #12 file. This file can contain a variety of cryptographic information, including certificates, certificate chains, root authority certificates, and private keys. Its contents can be cryptographically protected (with passwords) to keep private keys private and preserve the integrity of root certificates.</p>
<p>Windows uses .pvk for a private key file. <strike>I'm not sure what standard (if any) Windows follows for these. Hopefully they are PKCS #8 encoded keys.</strike> <a href="https://stackoverflow.com/users/525725/">Emmanuel Bourg</a> reports that these are a proprietary format. Some <a href="https://web.archive.org/web/20170531040754/http://www.drh-consultancy.demon.co.uk/pvk.html" rel="noreferrer">documentation</a> is available.</p>
<p>You should never disclose your private key. These are contained in .pfx and .pvk files. </p>
<p>Generally, you only exchange your certificate (.cer) and the certificates of any intermediate issuers (i.e., the certificates of all of your CAs, except the root CA) with other parties. </p> | {
"question_id": 2292495,
"question_date": "2010-02-18T21:54:31.430Z",
"question_score": 231,
"tags": "security|public-key",
"answer_id": 2292591,
"answer_date": "2010-02-18T22:09:28.073Z",
"answer_score": 160
} |
Please answer the following Stack Overflow question:
Title: Android Studio error: "Manifest merger failed: Apps targeting Android 12"
<p>I have updated my emulator version and Android SDK version to Android S (<a href="https://en.wikipedia.org/wiki/Android_12" rel="noreferrer">Android 12</a>). After the update, I cannot run the project. I cannot run a <em><a href="https://en.wikipedia.org/wiki/%22Hello,_World!%22_program" rel="noreferrer">Hello, World!</a></em> project (empty project), but I can build Gradle as well as, but I can not run the project. I always got the error:</p>
<blockquote>
<p>Manifest merger failed: Apps targeting Android 12 and higher are
required to specify an explicit value for <code>android: exported</code> when the
corresponding component has an intent filter defined. See
<a href="https://developer.android.com/guide/topics/manifest/activity-element#exported" rel="noreferrer">https://developer.android.com/guide/topics/manifest/activity-element#exported</a>
for details.</p>
</blockquote>
<p>How can I fix it?</p>
<p>Here is a screenshot:</p>
<p><a href="https://i.stack.imgur.com/ZMzmN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZMzmN.png" alt="This is a screenshot." /></a></p>
<p>How can I solve this issue when using Android 12 SDK?</p>
<p><a href="https://stackoverflow.com/questions/67654506/manifest-merger-failed-targeting-android-12">This question</a> is about the issue after applying the solution to this, and is different than this question. Also, this question is older than <a href="https://stackoverflow.com/questions/67654506/manifest-merger-failed-targeting-android-12">this</a>.</p> | <p>You need to specify <code>android:exported="false"</code> or <code>android:exported="true"</code></p>
<p>Manifest:</p>
<pre class="lang-xml prettyprint-override"><code><activity
android:name=".MainActivity"
android:exported="true"
android:theme="@style/Theme.MyApplication.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</code></pre>
<p>as mentioned in <a href="https://developer.android.com/about/versions/12/behavior-changes-12#security" rel="noreferrer">the document</a>:</p>
<blockquote>
<p>If your app targets Android 12 and contains activities, services, or
broadcast receivers that use intent filters, you must explicitly
declare the android: exported attribute for these app components.</p>
</blockquote>
<blockquote>
<p><strong>Warning</strong>: If an activity, service, or broadcast receiver uses intent
filters and doesn't have an explicitly-declared value for
android:exported, your app can't be installed on a device that runs
Android 12.</p>
</blockquote>
<p>Also <a href="https://developer.android.com/guide/topics/manifest/activity-element#exported" rel="noreferrer">check</a> when to use true/false for the 'android:exported' value.</p> | {
"question_id": 67412084,
"question_date": "2021-05-06T05:00:27.120Z",
"question_score": 231,
"tags": "java|android|android-studio|android-emulator|runtime-error",
"answer_id": 67412314,
"answer_date": "2021-05-06T05:25:22.167Z",
"answer_score": 299
} |
Please answer the following Stack Overflow question:
Title: Format decimal for percentage values?
<p>What I want is something like this:</p>
<pre><code>String.Format("Value: {0:%%}.", 0.8526)
</code></pre>
<p>Where %% is that format provider or whatever I am looking for.
Should result: <code>Value: %85.26.</code>.</p>
<p>I basically need it for wpf binding, but first let's solve the general formatting issue:</p>
<pre><code><TextBlock Text="{Binding Percent, StringFormat=%%}" />
</code></pre> | <p>Use the <a href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx" rel="noreferrer"><code>P</code> format string</a>. This will vary by culture:</p>
<pre><code>String.Format("Value: {0:P2}.", 0.8526) // formats as 85.26 % (varies by culture)
</code></pre> | {
"question_id": 1790975,
"question_date": "2009-11-24T15:54:28.300Z",
"question_score": 231,
"tags": "c#|decimal|string.format|formatprovider",
"answer_id": 1790987,
"answer_date": "2009-11-24T15:56:01.073Z",
"answer_score": 466
} |
Please answer the following Stack Overflow question:
Title: How do you get current active/default Environment profile programmatically in Spring?
<p>I need to code different logic based on different current Environment profile.</p>
<p><em><strong>How can you get the currently active and default profiles from Spring?</strong></em></p> | <p>You can autowire the <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/Environment.html" rel="noreferrer"><code>Environment</code></a></p>
<pre><code>@Autowired
Environment env;
</code></pre>
<p><code>Environment</code> offers:</p>
<ul>
<li><a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/Environment.html#getActiveProfiles--" rel="noreferrer"><code>String[] getActiveProfiles()</code></a>,</li>
<li><a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/Environment.html#getDefaultProfiles--" rel="noreferrer"><code>String[] getDefaultProfiles()</code></a>, and </li>
<li><a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/core/env/Environment.html#acceptsProfiles-java.lang.String...-" rel="noreferrer"><code>boolean acceptsProfiles(String... profiles)</code></a></li>
</ul> | {
"question_id": 9267799,
"question_date": "2012-02-13T20:50:18.777Z",
"question_score": 231,
"tags": "java|spring|spring-profiles",
"answer_id": 9268041,
"answer_date": "2012-02-13T21:08:19.820Z",
"answer_score": 313
} |
Please answer the following Stack Overflow question:
Title: How to execute only one test spec with angular-cli
<p>I have Angular2 project build with Angular-CLI (beta 20). </p>
<p>Is there a way to run tests against only one selected spec file?</p>
<p>I used to have a project based on Angular2 quick start, and I could manually add specs to jasmine file. But I don't know how to set this up outside of karma testing or how to limit karma tests to specific files with Angular-CLI builds.</p> | <p>Each of your <code>.spec.ts</code> file have all its tests grouped in <code>describe</code> block like this:</p>
<p><code>describe('SomeComponent', () => {...}</code></p>
<p>You can easily run just this single block, by prefixing the <code>describe</code> function name with <code>f</code>:</p>
<p><code>fdescribe('SomeComponent', () => {...}</code></p>
<p>If you have such function, no other <code>describe</code> blocks will run.
Btw. you can do similar thing with <code>it</code> => <code>fit</code> and there is also a "blacklist" version - <code>x</code>. So:</p>
<ul>
<li><code>fdescribe</code> and <code>fit</code> causes <strong>only</strong> functions marked this way to run</li>
<li><code>xdescribe</code> and <code>xit</code> causes <strong>all but</strong> functions marked this way to run</li>
</ul> | {
"question_id": 40683673,
"question_date": "2016-11-18T18:20:44.503Z",
"question_score": 231,
"tags": "angular|jasmine|angular-cli",
"answer_id": 40683791,
"answer_date": "2016-11-18T18:27:54.580Z",
"answer_score": 322
} |
Please answer the following Stack Overflow question:
Title: HSL to RGB color conversion
<p>I am looking for an algorithm to convert between HSL color to RGB.</p>
<p>It seems to me that HSL is not very widely used so I am not having much luck searching for a converter.</p> | <p>Found the easiest way, python to the <a href="http://docs.python.org/library/colorsys.html#module-colorsys" rel="noreferrer">rescue</a> :D</p>
<blockquote>
<p><code>colorsys.hls_to_rgb(h, l, s)</code></p>
<p>Convert the color from HLS coordinates to RGB coordinates.</p>
</blockquote> | {
"question_id": 2353211,
"question_date": "2010-02-28T23:58:49.490Z",
"question_score": 231,
"tags": "algorithm|colors|rgb|hsl",
"answer_id": 2353265,
"answer_date": "2010-03-01T00:20:05.797Z",
"answer_score": 46
} |
Please answer the following Stack Overflow question:
Title: Get file name from URI string in C#
<p>I have this method for grabbing the file name from a string URI. What can I do to make it more robust?</p>
<pre><code>private string GetFileName(string hrefLink)
{
string[] parts = hrefLink.Split('/');
string fileName = "";
if (parts.Length > 0)
fileName = parts[parts.Length - 1];
else
fileName = hrefLink;
return fileName;
}
</code></pre> | <p>You can just make a System.Uri object, and use IsFile to verify it's a file, then <a href="http://msdn.microsoft.com/en-us/library/system.uri.localpath.aspx" rel="noreferrer">Uri.LocalPath</a> to extract the filename.</p>
<p>This is much safer, as it provides you a means to check the validity of the URI as well.</p>
<hr>
<p>Edit in response to comment:</p>
<p>To get just the full filename, I'd use:</p>
<pre><code>Uri uri = new Uri(hreflink);
if (uri.IsFile) {
string filename = System.IO.Path.GetFileName(uri.LocalPath);
}
</code></pre>
<p>This does all of the error checking for you, and is platform-neutral. All of the special cases get handled for you quickly and easily.</p> | {
"question_id": 1105593,
"question_date": "2009-07-09T18:07:47.330Z",
"question_score": 231,
"tags": "c#|string|uri|filenames",
"answer_id": 1105614,
"answer_date": "2009-07-09T18:11:17.430Z",
"answer_score": 427
} |
Please answer the following Stack Overflow question:
Title: Objective-C for Windows
<p>What would be the best way to write Objective-C on the Windows platform?</p>
<p>Cygwin and gcc? Is there a way I can somehow integrate this into Visual Studio?</p>
<p>Along those lines - are there any suggestions as to how to link in and use the Windows SDK for something like this. Its a different beast but I know I can write assembly and link in the Windows DLLs giving me accessibility to those calls but I don't know how to do this without googling and getting piecemeal directions.</p>
<p>Is anyone aware of a good online or book resource to do or explain these kinds of things?</p> | <p>Expanding on the two previous answers, if you just want Objective-C but not any of the Cocoa frameworks, then gcc will work on any platform. You can use it through Cygwin or get MinGW. However, if you want the Cocoa frameworks, or at least a reasonable subset of them, then GNUStep and Cocotron are your best bets.</p>
<p>Cocotron implements a lot of stuff that GNUStep does not, such as CoreGraphics and CoreData, though I can't vouch for how complete their implementation is on a specific framework. Their aim is to keep Cocotron up to date with the latest version of OS X so that any viable OS X program can run on Windows. Because GNUStep typically uses the latest version of gcc, they also add in support for Objective-C++ and a lot of the Objective-C 2.0 features.</p>
<p>I haven't tested those features with GNUStep, but if you use a sufficiently new version of gcc, you might be able to use them. I was not able to use Objective-C++ with GNUStep a few years ago. However, GNUStep does compile from just about any platform. Cocotron is a very mac-centric project. Although it is probably possible to compile it on other platforms, it comes XCode project files, not makefiles, so you can only compile its frameworks out of the box on OS X. It also comes with instructions on compiling Windows apps on XCode, but not any other platform. Basically, it's probably possible to set up a Windows development environment for Cocotron, but it's not as easy as setting one up for GNUStep, and you'll be on your own, so GNUStep is definitely the way to go if you're developing on Windows as opposed to just for Windows.</p>
<p>For what it's worth, Cocotron is licensed under the MIT license, and GNUStep is licensed under the LGPL.</p> | {
"question_id": 56708,
"question_date": "2008-09-11T14:38:42.883Z",
"question_score": 231,
"tags": "objective-c|windows|winapi|gcc|cygwin",
"answer_id": 141197,
"answer_date": "2008-09-26T18:42:43.120Z",
"answer_score": 147
} |
Please answer the following Stack Overflow question:
Title: What is a good practice to check if an environmental variable exists or not?
<p>I want to check my environment for the existence of a variable, say <code>"FOO"</code>, in Python. For this purpose, I am using the <code>os</code> standard library. After reading the library's documentation, I have figured out 2 ways to achieve my goal:</p>
<p>Method 1: </p>
<pre><code>if "FOO" in os.environ:
pass
</code></pre>
<p>Method 2:</p>
<pre><code>if os.getenv("FOO") is not None:
pass
</code></pre>
<p>I would like to know which method, if either, is a good/preferred conditional and why.</p> | <p>Use the first; it directly tries to check if something is defined in <code>environ</code>. Though the second form works equally well, it's lacking semantically since you get a value back if it exists and <em>only</em> use it for a comparison. </p>
<p>You're trying to see if something is present <em>in</em> <code>environ</code>, why would you <em>get</em> just to compare it and then <em>toss it away</em>? </p>
<p>That's exactly what <code>getenv</code> does:</p>
<blockquote>
<p><em>Get an environment variable</em>, return <code>None</code> if it doesn't exist. The
optional second argument can specify an alternate default.</p>
</blockquote>
<p>(this also means your check could just be <code>if getenv("FOO")</code>)</p>
<p>you don't want to <em>get it</em>, you want to check for it's existence. </p>
<p>Either way, <code>getenv</code> is just a wrapper around <code>environ.get</code> but you don't see people checking for membership in mappings with:</p>
<pre><code>from os import environ
if environ.get('Foo') is not None:
</code></pre>
<p>To summarize, use: </p>
<pre><code>if "FOO" in os.environ:
pass
</code></pre>
<p>if you <em>just</em> want to check for existence, while, use <code>getenv("FOO")</code> if you actually want to do something with the value you might get.</p> | {
"question_id": 40697845,
"question_date": "2016-11-19T20:59:57.637Z",
"question_score": 231,
"tags": "python|python-2.7|python-3.x|if-statement|environment-variables",
"answer_id": 40698307,
"answer_date": "2016-11-19T21:52:27.653Z",
"answer_score": 262
} |
Please answer the following Stack Overflow question:
Title: Razor View throwing "The name 'model' does not exist in the current context"
<p>After significant refactoring in my MVC 4 application, and Razor shows this error while debugging Views:</p>
<blockquote>
<p>The name 'model' does not exist in the current context.</p>
</blockquote>
<p>This is the offending line of code:</p>
<pre><code>@model ICollection<DataSourceByActive>
</code></pre>
<p>I know that the usage of <code>@model</code> is correct.</p>
<p>Why is this happening? How can I fix it?</p> | <p>I think you have messed up the web.config file which lives in the Views folder.</p>
<p>Create a new project targeting the same .NET framework and copy its Views/web.config file on top of the one in your current project. This will fix your problem.</p>
<p>Also, as Dudeman3000 commented, if you have Areas in your MVC project they all have <code>Views\web.config</code> files too.</p> | {
"question_id": 19696963,
"question_date": "2013-10-31T01:38:32.797Z",
"question_score": 231,
"tags": "asp.net-mvc|asp.net-mvc-4|razor",
"answer_id": 19696998,
"answer_date": "2013-10-31T01:44:28.977Z",
"answer_score": 287
} |
Please answer the following Stack Overflow question:
Title: equals vs Arrays.equals in Java
<p>When comparing arrays in Java, are there any differences between the following 2 statements?</p>
<pre><code>Object[] array1, array2;
array1.equals(array2);
Arrays.equals(array1, array2);
</code></pre>
<p>And if so, what are they?</p> | <p><code>array1.equals(array2)</code> is the same as <code>array1 == array2</code>, i.e. is it the same array. As @alf points out it's not what most people expect.</p>
<p><code>Arrays.equals(array1, array2)</code> compares the contents of the arrays.</p>
<hr>
<p>Similarly <code>array.toString()</code> may not be very useful and you need to use <code>Arrays.toString(array)</code>.</p> | {
"question_id": 8777257,
"question_date": "2012-01-08T11:53:26.760Z",
"question_score": 231,
"tags": "java|arrays|equality",
"answer_id": 8777279,
"answer_date": "2012-01-08T11:57:32.230Z",
"answer_score": 335
} |
Please answer the following Stack Overflow question:
Title: Prevent scrolling of parent element when inner element scroll position reaches top/bottom?
<p>I have a little "floating tool box" - a div with <code>position:fixed; overflow:auto</code>.
Works just fine.</p>
<p>But when scrolling inside that box (with the mouse wheel) and reaching the bottom OR top, the parent element "takes over" the "scroll request" : The document behind the tool box scrolls.<br>
- Which is annoying and not what the user "asked for".</p>
<p>I'm using jQuery and thought I could stop this behaviour with event.stoppropagation():<br>
<code>$("#toolBox").scroll( function(event){ event.stoppropagation() });</code> </p>
<p>It does enter the function, but still, propagation happens anyway (the document scrolls)<br>
- It's surprisingly hard to search for this topic on SO (and Google), so I have to ask:<br>
How to prevent propagation / bubbling of the scroll-event ? </p>
<p>Edit:<br>
Working solution thanks to amustill (and Brandon Aaron for the mousewheel-plugin here:<br>
<a href="https://github.com/brandonaaron/jquery-mousewheel/raw/master/jquery.mousewheel.js" rel="noreferrer">https://github.com/brandonaaron/jquery-mousewheel/raw/master/jquery.mousewheel.js</a> </p>
<pre><code>$(".ToolPage").bind('mousewheel', function(e, d)
var t = $(this);
if (d > 0 && t.scrollTop() === 0) {
e.preventDefault();
}
else {
if (d < 0 && (t.scrollTop() == t.get(0).scrollHeight - t.innerHeight())) {
e.preventDefault();
}
}
});
</code></pre> | <p>It's possible with the use of Brandon Aaron's <a href="https://plugins.jquery.com/mousewheel/" rel="nofollow noreferrer">Mousewheel plugin</a>.</p>
<p>Here's a demo: <a href="http://jsbin.com/jivutakama/edit?html,js,output" rel="nofollow noreferrer">http://jsbin.com/jivutakama/edit?html,js,output</a></p>
<pre><code>$(function() {
var toolbox = $('#toolbox'),
height = toolbox.height(),
scrollHeight = toolbox.get(0).scrollHeight;
toolbox.bind('mousewheel', function(e, d) {
if((this.scrollTop === (scrollHeight - height) && d < 0) || (this.scrollTop === 0 && d > 0)) {
e.preventDefault();
}
});
});
</code></pre> | {
"question_id": 5802467,
"question_date": "2011-04-27T10:13:28.247Z",
"question_score": 231,
"tags": "javascript|jquery|scroll|event-bubbling|event-propagation",
"answer_id": 5802887,
"answer_date": "2011-04-27T10:53:05.953Z",
"answer_score": 45
} |
Please answer the following Stack Overflow question:
Title: Why is --isolatedModules error fixed by any import?
<p>In a create-react-app typescript project, I tried to write this just to test some stuff quickly:</p>
<pre class="lang-js prettyprint-override"><code>// experiment.test.ts
it('experiment', () => {
console.log('test');
});
</code></pre>
<p>But it gives me the following error, with a red squiggly beneath <code>it</code>:</p>
<blockquote>
<p>All files must be modules when the '--isolatedModules' flag is provided.</p>
</blockquote>
<p>However, if I change the file to the following, then everything apparently is fine (except for the unused import of course):</p>
<pre class="lang-js prettyprint-override"><code>// experiment.test.ts
import { Component} from 'react'; // literally anything, don't even have to use it
it('test', () => {
console.log('test');
});
</code></pre>
<p>Why? What is happening here? What does <code>--isolatedModules</code> actually mean/do?</p> | <p>Typescript treats files without import/exports as legacy script files. As such files are not modules and any definitions they have get merged in the global namespace. <code>isolatedModules</code> forbids such files.</p>
<p>Adding any import or export to a file makes it a module and the error disappears.</p>
<p><strong>Also <code>export {}</code> is a handy way</strong> to make a file a module without importing anything.</p> | {
"question_id": 56577201,
"question_date": "2019-06-13T09:15:42.710Z",
"question_score": 231,
"tags": "typescript",
"answer_id": 56577324,
"answer_date": "2019-06-13T09:23:03.063Z",
"answer_score": 408
} |
Please answer the following Stack Overflow question:
Title: angular ng-repeat in reverse
<p>How can i get a reversed array in angular?
i'm trying to use orderBy filter, but it needs a predicate(e.g. 'name') to sort:</p>
<pre><code><tr ng-repeat="friend in friends | orderBy:'name':true">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
<tr>
</code></pre>
<p>Is there a way to reverse original array, without sorting.
like that:</p>
<pre><code><tr ng-repeat="friend in friends | orderBy:'':true">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
<tr>
</code></pre> | <p>I would suggest using a custom filter such as this:</p>
<pre class="lang-js prettyprint-override"><code>app.filter('reverse', function() {
return function(items) {
return items.slice().reverse();
};
});
</code></pre>
<p>Which can then be used like:</p>
<pre class="lang-html prettyprint-override"><code><div ng-repeat="friend in friends | reverse">{{friend.name}}</div>
</code></pre>
<p>See it working here: <a href="http://plnkr.co/edit/REU7mTsfG5HISCnLKEr8?p=preview" rel="noreferrer">Plunker Demonstration</a></p>
<hr>
<p>This filter can be customized to fit your needs as seen fit. I have provided other examples in the demonstration. Some options include checking that the variable is an array before performing the reverse, or making it more lenient to allow the reversal of more things such as strings.</p> | {
"question_id": 15266671,
"question_date": "2013-03-07T08:48:18.193Z",
"question_score": 231,
"tags": "javascript|arrays|angularjs|reverse|angularjs-ng-repeat",
"answer_id": 15267754,
"answer_date": "2013-03-07T09:42:22.787Z",
"answer_score": 333
} |
Please answer the following Stack Overflow question:
Title: Are members of a C++ struct initialized to 0 by default?
<p>I have this <code>struct</code>:</p>
<pre><code>struct Snapshot
{
double x;
int y;
};
</code></pre>
<p>I want <code>x</code> and <code>y</code> to be 0. Will they be 0 by default or do I have to do:</p>
<pre><code>Snapshot s = {0,0};
</code></pre>
<p>What are the other ways to zero out the structure?</p> | <p>They are not null if you don't initialize the struct. </p>
<pre><code>Snapshot s; // receives no initialization
Snapshot s = {}; // value initializes all members
</code></pre>
<p>The second will make all members zero, the first leaves them at unspecified values. Note that it is recursive:</p>
<pre><code>struct Parent { Snapshot s; };
Parent p; // receives no initialization
Parent p = {}; // value initializes all members
</code></pre>
<p>The second will make <code>p.s.{x,y}</code> zero. You cannot use these aggregate initializer lists if you've got constructors in your struct. If that is the case, you will have to add proper initalization to those constructors</p>
<pre><code>struct Snapshot {
int x;
double y;
Snapshot():x(0),y(0) { }
// other ctors / functions...
};
</code></pre>
<p>Will initialize both x and y to 0. Note that you can use <code>x(), y()</code> to initialize them disregarding of their type: That's then value initialization, and usually yields a proper initial value (0 for int, 0.0 for double, calling the default constructor for user defined types that have user declared constructors, ...). This is important especially if your struct is a template. </p> | {
"question_id": 1069621,
"question_date": "2009-07-01T14:58:39.757Z",
"question_score": 231,
"tags": "c++",
"answer_id": 1069634,
"answer_date": "2009-07-01T15:00:33.700Z",
"answer_score": 304
} |
Please answer the following Stack Overflow question:
Title: Angularjs - ng-cloak/ng-show elements blink
<p>I have an issue in angular.js with directive/class <code>ng-cloak</code> or <code>ng-show</code>.</p>
<p>Chrome works fine, but Firefox is causing blink of elements with <code>ng-cloak</code> or <code>ng-show</code>.
IMHO it's caused by the converting <code>ng-cloak</code>/<code>ng-show</code> to <code>style="display: none;"</code>, probably the Firefox javascript compiler is little bit slower, so the elements appears for a while and then hide?</p>
<p>Example:</p>
<pre><code><ul ng-show="foo != null" ng-cloak>..</ul>
</code></pre> | <p>Though the documentation doesn't mention it, it might not be enough to add the <code>display: none;</code> rule to your CSS. In cases where you are loading angular.js in the body or templates aren't compiled soon enough, use the <code>ng-cloak</code> directive <strong>and</strong> include the following in your CSS:</p>
<pre><code>/*
Allow angular.js to be loaded in body, hiding cloaked elements until
templates compile. The !important is important given that there may be
other selectors that are more specific or come later and might alter display.
*/
[ng\:cloak], [ng-cloak], .ng-cloak {
display: none !important;
}
</code></pre>
<p>As mentioned in the comment, the <code>!important</code> is important. For example, if you have the following markup</p>
<pre><code><ul class="nav">
<li><a href="/foo" ng-cloak>{{bar}}</a></li>
</ul>
</code></pre>
<p>and you happen to be using <code>bootstrap.css</code>, the following selector is more specific for your <code>ng-cloak</code>'ed element</p>
<pre><code>.nav > li > a {
display: block;
}
</code></pre>
<p>So if you include a rule with simply <code>display: none;</code>, Bootstrap's rule will take precedence and the <code>display</code> will be set to <code>block</code>, so you'll see the flicker before the template compiles.</p> | {
"question_id": 11249768,
"question_date": "2012-06-28T17:19:11.933Z",
"question_score": 231,
"tags": "javascript|class|angularjs",
"answer_id": 13276214,
"answer_date": "2012-11-07T18:52:00.643Z",
"answer_score": 387
} |
Please answer the following Stack Overflow question:
Title: What is a Memory Heap?
<p>What is a memory heap ?</p> | <p>Presumably you mean <em>heap</em> from a memory allocation point of view, not from a data structure point of view (the term has multiple meanings).</p>
<p>A very simple explanation is that the <strong>heap</strong> is the portion of memory where <em>dynamically allocated</em> memory resides (i.e. memory allocated via <code>malloc</code>). Memory allocated from the heap will remain allocated until one of the following occurs:</p>
<ol>
<li>The memory is <code>free</code>'d</li>
<li>The program terminates</li>
</ol>
<p>If all references to allocated memory are lost (e.g. you don't store a pointer to it anymore), you have what is called a <em>memory leak</em>. This is where the memory has still been allocated, but you have no easy way of accessing it anymore. Leaked memory cannot be reclaimed for future memory allocations, but when the program ends the memory will be free'd up by the operating system.</p>
<p>Contrast this with <strong>stack</strong> memory which is where local variables (those defined within a method) live. Memory allocated on the stack generally only lives until the function returns (there are some exceptions to this, e.g. static local variables).</p>
<p>You can find more information about the heap in <a href="http://en.wikipedia.org/wiki/Heap_%28programming%29" rel="noreferrer">this article</a>.</p> | {
"question_id": 2308751,
"question_date": "2010-02-22T04:15:11.570Z",
"question_score": 231,
"tags": "malloc",
"answer_id": 2308762,
"answer_date": "2010-02-22T04:19:44.430Z",
"answer_score": 300
} |
Please answer the following Stack Overflow question:
Title: Difference between @click and v-on:click Vuejs
<p>The questions should be enough clear.</p>
<p>But I can see that someone use:</p>
<pre><code><button @click="function()">press</button>
</code></pre>
<p>Someone use:</p>
<pre><code><button v-on:click="function()">press</button>
</code></pre>
<p>But really what is the difference between the two (if exists)</p> | <p>There is no difference between the two, one is just a shorthand for the second.</p>
<blockquote>
<p>The v- prefix serves as a visual cue for identifying Vue-specific
attributes in your templates. This is useful when you are using Vue.js
to apply dynamic behavior to some existing markup, but can feel
verbose for some frequently used directives. At the same time, the
need for the v- prefix becomes less important when you are building an
SPA where Vue.js manages every template.</p>
</blockquote>
<pre class="lang-html prettyprint-override"><code><!-- full syntax -->
<a v-on:click="doSomething"></a>
<!-- shorthand -->
<a @click="doSomething"></a>
</code></pre>
<p>Source: <a href="https://v2.vuejs.org/v2/guide/syntax.html#v-on-Shorthand" rel="nofollow noreferrer">official documentation</a>.</p> | {
"question_id": 45369553,
"question_date": "2017-07-28T09:17:31.537Z",
"question_score": 231,
"tags": "vue.js|vue-directives",
"answer_id": 45369629,
"answer_date": "2017-07-28T09:20:48.093Z",
"answer_score": 267
} |
Please answer the following Stack Overflow question:
Title: Converting NSString to NSDate (and back again)
<p>How would I convert an <code>NSString</code> like "<strong>01/02/10</strong>" (meaning 1st February 2010) into an <code>NSDate</code>? And how could I turn the <code>NSDate</code> back into a string?</p> | <h2><strong>Swift 4 and later</strong></h2>
<p>Updated: 2018</p>
<p><strong>String to Date</strong></p>
<pre><code>var dateString = "02-03-2017"
var dateFormatter = DateFormatter()
// This is important - we set our input date format to match our input string
// if the format doesn't match you'll get nil from your string, so be careful
dateFormatter.dateFormat = "dd-MM-yyyy"
//`date(from:)` returns an optional so make sure you unwrap when using.
var dateFromString: Date? = dateFormatter.date(from: dateString)
</code></pre>
<p><strong>Date to String</strong></p>
<pre><code>var formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
guard let unwrappedDate = dateFromString else { return }
//Using the dateFromString variable from before.
let stringDate: String = formatter.string(from: dateFromString)
</code></pre>
<h2><strong>Swift 3</strong></h2>
<p>Updated: 20th July 2017</p>
<p><strong>String to NSDate</strong></p>
<pre><code>var dateString = "02-03-2017"
var dateFormatter = DateFormatter()
// This is important - we set our input date format to match our input string
// if the format doesn't match you'll get nil from your string, so be careful
dateFormatter.dateFormat = "dd-MM-yyyy"
var dateFromString = dateFormatter.date(from: dateString)
</code></pre>
<p><strong>NSDate to String</strong></p>
<pre><code>var formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let stringDate: String = formatter.string(from: dateFromString)
</code></pre>
<hr>
<h2><strong>Swift</strong></h2>
<p>Updated: 22nd October 2015</p>
<p><strong>String to NSDate</strong></p>
<pre><code>var dateString = "01-02-2010"
var dateFormatter = NSDateFormatter()
// this is imporant - we set our input date format to match our input string
dateFormatter.dateFormat = "dd-MM-yyyy"
// voila!
var dateFromString = dateFormatter.dateFromString(dateString)
</code></pre>
<p><strong>NSDate to String</strong></p>
<pre><code>var formatter = NSDateFormatter()
formatter.dateFormat = "dd-MM-yyyy"
let stringDate: String = formatter.stringFromDate(NSDate())
println(stringDate)
</code></pre>
<hr>
<h2>Objective-C</h2>
<p><strong>NSString to NSDate</strong></p>
<pre><code>NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
</code></pre>
<p><strong>NSDate convert to NSString:</strong></p>
<pre><code>NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *stringDate = [dateFormatter stringFromDate:[NSDate date]];
NSLog(@"%@", stringDate);
</code></pre> | {
"question_id": 3917250,
"question_date": "2010-10-12T17:11:16.333Z",
"question_score": 231,
"tags": "ios|objective-c|nsstring|nsdate",
"answer_id": 3917329,
"answer_date": "2010-10-12T17:19:48.603Z",
"answer_score": 454
} |
Please answer the following Stack Overflow question:
Title: Editing dictionary values in a foreach loop
<p>I am trying to build a pie chart from a dictionary. Before I display the pie chart, I want to tidy up the data. I'm removing any pie slices that would be less than 5% of the pie and putting them in a "Other" pie slice. However I'm getting a <code>Collection was modified; enumeration operation may not execute</code> exception at runtime.</p>
<p>I understand why you can not add or remove items from a dictionary while iterating over them. However I don't understand why you can't simply change a value for an existing key within the foreach loop.</p>
<p>Any suggestions re: fixing my code, would be appreciated.</p>
<pre><code>Dictionary<string, int> colStates = new Dictionary<string,int>();
// ...
// Some code to populate colStates dictionary
// ...
int OtherCount = 0;
foreach(string key in colStates.Keys)
{
double Percent = colStates[key] / TotalCount;
if (Percent < 0.05)
{
OtherCount += colStates[key];
colStates[key] = 0;
}
}
colStates.Add("Other", OtherCount);
</code></pre> | <p>Setting a value in a dictionary updates its internal "version number" - which invalidates the iterator, and any iterator associated with the keys or values collection.</p>
<p>I do see your point, but at the same time it would be odd if the values collection could change mid-iteration - and for simplicity there's only one version number.</p>
<p>The normal way of fixing this sort of thing is to either copy the collection of keys beforehand and iterate over the copy, or iterate over the original collection but maintain a collection of changes which you'll apply after you've finished iterating.</p>
<p>For example:</p>
<p><strong>Copying keys first</strong></p>
<pre><code>List<string> keys = new List<string>(colStates.Keys);
foreach(string key in keys)
{
double percent = colStates[key] / TotalCount;
if (percent < 0.05)
{
OtherCount += colStates[key];
colStates[key] = 0;
}
}
</code></pre>
<p>Or...</p>
<p><strong>Creating a list of modifications</strong></p>
<pre><code>List<string> keysToNuke = new List<string>();
foreach(string key in colStates.Keys)
{
double percent = colStates[key] / TotalCount;
if (percent < 0.05)
{
OtherCount += colStates[key];
keysToNuke.Add(key);
}
}
foreach (string key in keysToNuke)
{
colStates[key] = 0;
}
</code></pre> | {
"question_id": 1070766,
"question_date": "2009-07-01T19:00:50.157Z",
"question_score": 231,
"tags": "c#|.net|.net-2.0",
"answer_id": 1070795,
"answer_date": "2009-07-01T19:07:15.150Z",
"answer_score": 295
} |
Please answer the following Stack Overflow question:
Title: Python function attributes - uses and abuses
<p>Not many are aware of this feature, but Python's functions (and methods) can have <a href="http://www.python.org/dev/peps/pep-0232/" rel="noreferrer">attributes</a>. Behold:</p>
<pre><code>>>> def foo(x):
... pass
...
>>> foo.score = 10
>>> dir(foo)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name', 'score']
>>> foo.score
10
>>> foo.score += 1
>>> foo.score
11
</code></pre>
<p>What are the possible uses and abuses of this feature in Python ? One good use I'm aware of is <a href="http://www.dabeaz.com/ply/" rel="noreferrer">PLY</a>'s usage of the docstring to associate a syntax rule with a method. But what about custom attributes ? Are there good reasons to use them ?</p> | <p>I typically use function attributes as storage for annotations. Suppose I want to write, in the style of C# (indicating that a certain method should be part of the web service interface)</p>
<pre><code>class Foo(WebService):
@webmethod
def bar(self, arg1, arg2):
...
</code></pre>
<p>then I can define</p>
<pre><code>def webmethod(func):
func.is_webmethod = True
return func
</code></pre>
<p>Then, when a webservice call arrives, I look up the method, check whether the underlying function has the is_webmethod attribute (the actual value is irrelevant), and refuse the service if the method is absent or not meant to be called over the web.</p> | {
"question_id": 338101,
"question_date": "2008-12-03T17:56:45.387Z",
"question_score": 231,
"tags": "python|function|attributes",
"answer_id": 338145,
"answer_date": "2008-12-03T18:06:51.230Z",
"answer_score": 175
} |
Please answer the following Stack Overflow question:
Title: HTML5 textarea placeholder not appearing
<p>I cannot figure out what is wrong with my markup, but the placeholder for the text area will not appear. It seems as though it may be covered up with some blank spaces and tabs. When you focus on the text area and delete from where the cursor puts itself, then leave the text area, the proper placeholder then appears.</p>
<pre><code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
</head>
<body>
<form action="message.php" method="post" id="message_form">
<fieldset>
<input type="email" name="email" id="email" title="Email address"
maxlength="40"
placeholder="Email Address"
autocomplete="off" required />
<br />
<input type="text"
name="subject"
id="subject" title="Subject"
maxlength="60" placeholder="Subject" autocomplete="off" required />
<br />
<textarea name="message"
id="message"
title="Message"
cols="30"
rows="5"
maxlength="100"
placeholder="Message" required>
</textarea>
<br />
<input type="submit" value="Send" id="submit"/>
</fieldset>
</form>
</body>
<script>
$(document).ready(function() {
$('#message_form').html5form({
allBrowsers : true,
responseDiv : '#response',
messages: 'en',
messages: 'es',
method : 'GET',
colorOn :'#d2d2d2',
colorOff :'#000'
}
);
});
</script>
</html>
</code></pre> | <p>This one has always been a gotcha for me and many others. In short, the opening and closing tags for the <code><textarea></code> element must be on the same line, otherwise a newline character occupies it. The placeholder will therefore not be displayed since the input area contains content (a newline character is, technically, valid content).</p>
<p>Good:</p>
<pre><code><textarea></textarea>
</code></pre>
<p>Bad:</p>
<pre><code><textarea>
</textarea>
</code></pre>
<h2>Update (2020)</h2>
<p>This is <a href="https://html.spec.whatwg.org/multipage/parsing.html#parsing-main-inbody:parse-errors-35" rel="noreferrer">not true</a> anymore, according to the HTML5 parsing spec:</p>
<pre><code>If the next token is a U+000A LINE FEED (LF) character token,
then ignore that token and move on to the next one. (Newlines
at the start of textarea elements are ignored as an authoring
convenience.)
</code></pre>
<p>You might still have trouble if you editor insists on ending lines with CRLF, though.</p> | {
"question_id": 10186913,
"question_date": "2012-04-17T07:23:33.287Z",
"question_score": 231,
"tags": "jquery|forms|html|textarea|placeholder",
"answer_id": 14048003,
"answer_date": "2012-12-27T00:34:58.943Z",
"answer_score": 820
} |
Please answer the following Stack Overflow question:
Title: Git on Bitbucket: Always asked for password, even after uploading my public SSH key
<p>I uploaded my <code>~/.ssh/id_rsa.pub</code> to <a href="https://bitbucket.org/account/ssh-keys/" rel="noreferrer">Bitbucket's SSH keys</a> as <a href="https://confluence.atlassian.com/bitbucket/use-the-ssh-protocol-with-bitbucket-cloud-221449711.html" rel="noreferrer">explained</a>, but Git still asks me for my password at every operation (such as <code>git pull</code>). Did I miss something?</p>
<p>It is a private repository (fork of another person's private repository) and I cloned it like this:</p>
<pre><code>git clone [email protected]:Nicolas_Raoul/therepo.git
</code></pre>
<p>Here is my local <code>.git/config</code>:</p>
<pre><code>[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = https://[email protected]/Nicolas_Raoul/therepo.git
[branch "master"]
remote = origin
merge = refs/heads/master
</code></pre>
<p>In the same environment with the same public key, Git on Github works fine.<br>
<code>.ssh</code> is <code>rwx------</code>, <code>.ssh/id_rsa</code> is <code>-rw-------</code>, <code>.ssh/id_rsa.pub</code> is <code>-rw-r--r--</code></p> | <p>Are you sure you cloned it using the ssh url?</p>
<p>The url for origin says <code>url = https://[email protected]/Nicolas_Raoul/therepo.git</code> so if it is using https it will ask for password irrespective of your ssh keys.</p>
<p>So what you want to do is the following:</p>
<p>open your config file in your current repo ..</p>
<p><code>vim .git/config</code></p>
<p>and change the line with the url from</p>
<pre><code>[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = https://[email protected]/Nicolas_Raoul/therepo.git
</code></pre>
<p>to </p>
<pre><code>[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = [email protected]:Nicolas_Raoul/therepo.git
</code></pre> | {
"question_id": 8600652,
"question_date": "2011-12-22T07:28:48.103Z",
"question_score": 231,
"tags": "git|ssh|bitbucket",
"answer_id": 8600699,
"answer_date": "2011-12-22T07:35:34.167Z",
"answer_score": 337
} |
Please answer the following Stack Overflow question:
Title: Case-insensitive search in Rails model
<p>My product model contains some items</p>
<pre><code> Product.first
=> #<Product id: 10, name: "Blue jeans" >
</code></pre>
<p>I'm now importing some product parameters from another dataset, but there are inconsistencies in the spelling of the names. For instance, in the other dataset, <code>Blue jeans</code> could be spelled <code>Blue Jeans</code>.</p>
<p>I wanted to <code>Product.find_or_create_by_name("Blue Jeans")</code>, but this will create a new product, almost identical to the first. What are my options if I want to find and compare the lowercased name. </p>
<p>Performance issues is not really important here: There are only 100-200 products, and I want to run this as a migration that imports the data.</p>
<p>Any ideas?</p> | <p>You'll probably have to be more verbose here</p>
<pre><code>name = "Blue Jeans"
model = Product.where('lower(name) = ?', name.downcase).first
model ||= Product.create(:name => name)
</code></pre> | {
"question_id": 2220423,
"question_date": "2010-02-08T08:55:24.217Z",
"question_score": 231,
"tags": "ruby-on-rails|activerecord|case-insensitive",
"answer_id": 2220595,
"answer_date": "2010-02-08T09:35:23.083Z",
"answer_score": 404
} |
Please answer the following Stack Overflow question:
Title: How do I use Node.js Crypto to create a HMAC-SHA1 hash?
<p>I want to create a hash of <code>I love cupcakes</code> (signed with the key <code>abcdeg</code>)</p>
<p>How can I create that hash, using Node.js Crypto?</p> | <p>Documentation for crypto: <a href="http://nodejs.org/api/crypto.html" rel="noreferrer">http://nodejs.org/api/crypto.html</a></p>
<pre class="lang-js prettyprint-override"><code>const crypto = require('crypto')
const text = 'I love cupcakes'
const key = 'abcdeg'
crypto.createHmac('sha1', key)
.update(text)
.digest('hex')
</code></pre> | {
"question_id": 7480158,
"question_date": "2011-09-20T04:29:52.523Z",
"question_score": 231,
"tags": "javascript|node.js|algorithm|hash|node-crypto",
"answer_id": 7480211,
"answer_date": "2011-09-20T04:38:21.757Z",
"answer_score": 407
} |
Please answer the following Stack Overflow question:
Title: How to add 'libs' folder in Android Studio?
<p>I need help in creating the 'libs' folder in Android Studio for my project (It is not auto-generated in my project).</p>
<p>When I want to create a folder, it gives me lots of options, like AIDL, Assets, JNI, Java, Java Resources, Renderscripts, and 'res' folders. I chose <strong>Res</strong> and added a libs folder but it didn't show up on my file structure on the left.</p>
<p>Can anyone help me?</p>
<p>I wanted to add a JAR file but I can't find libs to put in.</p> | <p>The solution for me was very simple (after 10 hours of searching).
Above where your folders are there is a combobox that says "android"
click it and choose "Project".</p>
<p><a href="https://i.stack.imgur.com/6kHlA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6kHlA.png" alt="enter image description here"></a></p> | {
"question_id": 26956827,
"question_date": "2014-11-16T12:19:45.123Z",
"question_score": 231,
"tags": "android|android-studio|directory|libs",
"answer_id": 27120224,
"answer_date": "2014-11-25T06:36:46.110Z",
"answer_score": 539
} |
Please answer the following Stack Overflow question:
Title: What is the equivalent of the join operator over a vector of Strings?
<p>I wasn't able to find the Rust equivalent for the "join" operator over a vector of <code>String</code>s. I have a <code>Vec<String></code> and I'd like to join them as a single <code>String</code>:</p>
<pre><code>let string_list = vec!["Foo".to_string(),"Bar".to_string()];
let joined = something::join(string_list,"-");
assert_eq!("Foo-Bar", joined);
</code></pre>
<p>Related:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/36941851/whats-an-idiomatic-way-to-print-an-iterator-separated-by-spaces-in-rust">What's an idiomatic way to print an iterator separated by spaces in Rust?</a></li>
</ul> | <p>In Rust 1.3.0 and later, <a href="https://doc.rust-lang.org/std/primitive.slice.html#method.join" rel="noreferrer"><code>join</code></a> is available:</p>
<pre><code>fn main() {
let string_list = vec!["Foo".to_string(),"Bar".to_string()];
let joined = string_list.join("-");
assert_eq!("Foo-Bar", joined);
}
</code></pre>
<p>Before 1.3.0 this method was called <a href="https://doc.rust-lang.org/std/primitive.slice.html#method.connect" rel="noreferrer"><code>connect</code></a>:</p>
<pre><code>let joined = string_list.connect("-");
</code></pre>
<p>Note that you do not need to import anything since the methods are automatically imported by the <a href="https://doc.rust-lang.org/std/prelude/index.html" rel="noreferrer">standard library prelude</a>.</p> | {
"question_id": 28311868,
"question_date": "2015-02-04T01:19:59.870Z",
"question_score": 231,
"tags": "string|rust",
"answer_id": 28312049,
"answer_date": "2015-02-04T01:38:56.257Z",
"answer_score": 301
} |
Please answer the following Stack Overflow question:
Title: Git says remote ref does not exist when I delete remote branch
<p>I ran <code>git branch -a</code> </p>
<pre><code>* master
remotes/origin/test
remotes/origin/master
</code></pre>
<p>I want to delete my remote branch </p>
<p>I've tried </p>
<pre><code>git push origin --delete remotes/origin/test
</code></pre>
<p>I got </p>
<blockquote>
<p>error: unable to delete 'remotes/origin/test': remote ref does not
exist</p>
</blockquote>
<p>How is it not exist ? </p>
<p>I did a <code>git branch -a</code>, and I saw it listed. </p>
<p>Did I miss anything ? </p> | <p>The command <code>git branch -a</code> shows remote branches that exist <em>in your local repository</em>. This may sound a bit confusing but to understand it, you have to understand that there is a difference between a remote branch, and a branch that exists in a remote repository. Remote branches are <em>local</em> branches that map to branches of the remote repository. So the set of remote branches represent the state of the remote repository.</p>
<p>The usual way to update the list of remote branches is to use <code>git fetch</code>. This automatically gets an updated list of branches from the remote and sets up remote branches in the local repository, also fetching any commit objects you may be missing.</p>
<p>However, by default, <code>git fetch</code> does not remove remote branches that no longer have a counterpart branch on the remote. In order to do that, you explicitly need to <em>prune</em> the list of remote branches:</p>
<pre><code>git fetch --prune
</code></pre>
<p>This will automatically get rid of remote branches that no longer exist on the remote. Afterwards, <code>git branch -r</code> will show you an updated list of branches that really exist on the remote: And those you can delete using <code>git push</code>.</p>
<p>That being said, in order to use <code>git push --delete</code>, you need to specify the name of the branch on the remote repository; not the name of your remote branch. So to delete the branch <code>test</code> (represented by your remote branch <code>origin/test</code>), you would use <code>git push origin --delete test</code>.</p> | {
"question_id": 35941566,
"question_date": "2016-03-11T13:31:09.930Z",
"question_score": 231,
"tags": "git",
"answer_id": 35941658,
"answer_date": "2016-03-11T13:35:51.147Z",
"answer_score": 479
} |
Please answer the following Stack Overflow question:
Title: Can I force a UITableView to hide the separator between empty cells?
<p>When using a plain-style <code>UITableView</code> with a large enough number of cells that the <code>UITableView</code> cannot display them all without scrolling, no separators appear in the empty space below the cells. If I have only a few cells the empty space below them includes separators.</p>
<p>Is there a way that I can force a <code>UITableView</code> to remove the separators in the empty space? If not I'll have to load a custom background with a separator drawn in for each cell which will make it harder to inherit behavior.</p>
<p>I found a somewhat similar question <a href="https://stackoverflow.com/questions/1369831/eliminate-extra-separators-below-uitableview-in-iphone-sdk">here</a>, but I can't use a grouped <code>UITableView</code> in my implementation.</p> | <p>You can achieve what you want by defining a footer for the tableview. See this answer for more details:<a href="https://stackoverflow.com/questions/1369831/eliminate-extra-separators-below-uitableview-in-iphone-sdk">Eliminate Extra separators below UITableView</a></p> | {
"question_id": 1633966,
"question_date": "2009-10-27T22:09:40.250Z",
"question_score": 231,
"tags": "ios|objective-c|cocoa-touch|uitableview",
"answer_id": 1936600,
"answer_date": "2009-12-20T18:49:58.873Z",
"answer_score": 128
} |
Please answer the following Stack Overflow question:
Title: Accessing constructor of an anonymous class
<p>Lets say I have a concrete class Class1 and I am creating an anonymous class out of it.</p>
<pre><code>Object a = new Class1(){
void someNewMethod(){
}
};
</code></pre>
<p>Now is there any way I could overload the constructor of this anonymous class. Like shown below</p>
<pre><code>Object a = new Class1(){
void someNewMethod(){
}
public XXXXXXXX(int a){
super();
System.out.println(a);
}
};
</code></pre>
<p>With something at xxxxxxxx to name the constructor?</p> | <p>From the <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9.5.1" rel="noreferrer">Java Language Specification</a>, section 15.9.5.1:</p>
<blockquote>
<p>An anonymous class cannot have an
explicitly declared constructor.</p>
</blockquote>
<p>Sorry :(</p>
<p>EDIT: As an alternative, you can create some final local variables, and/or include an instance initializer in the anonymous class. For example:</p>
<pre><code>public class Test {
public static void main(String[] args) throws Exception {
final int fakeConstructorArg = 10;
Object a = new Object() {
{
System.out.println("arg = " + fakeConstructorArg);
}
};
}
}
</code></pre>
<p>It's grotty, but it might just help you. Alternatively, use a proper nested class :)</p> | {
"question_id": 362424,
"question_date": "2008-12-12T10:34:23.510Z",
"question_score": 231,
"tags": "java|constructor|overloading|anonymous-types",
"answer_id": 362443,
"answer_date": "2008-12-12T10:42:54.320Z",
"answer_score": 304
} |
Please answer the following Stack Overflow question:
Title: ActiveRecord: size vs count
<p>In Rails, you can find the number of records using both <code>Model.size</code> and <code>Model.count</code>. If you're dealing with more complex queries is there any advantage to using one method over the other? How are they different?</p>
<p>For instance, I have users with photos. If I want to show a table of users and how many photos they have, will running many instances of <code>user.photos.size</code> be faster or slower than <code>user.photos.count</code>?</p>
<p>Thanks!</p> | <p>You should read <a href="http://web.archive.org/web/20100210204319/http://blog.hasmanythrough.com/2008/2/27/count-length-size">that</a>, it's still valid.</p>
<p>You'll adapt the function you use depending on your needs.</p>
<p>Basically:</p>
<ul>
<li><p>if you already load all entries, say <code>User.all</code>, then you should use <code>length</code> to avoid another db query</p></li>
<li><p>if you haven't anything loaded, use <code>count</code> to make a count query on your db</p></li>
<li><p>if you don't want to bother with these considerations, use <code>size</code> which will adapt</p></li>
</ul> | {
"question_id": 6083219,
"question_date": "2011-05-21T17:07:56.537Z",
"question_score": 231,
"tags": "ruby-on-rails|ruby|ruby-on-rails-3|rails-activerecord",
"answer_id": 6083229,
"answer_date": "2011-05-21T17:10:18.397Z",
"answer_score": 394
} |
Please answer the following Stack Overflow question:
Title: How to switch kubectl clusters between gcloud and minikube
<p>I have Kubernetes working well in two different environments, namely in my local environment (MacBook running minikube) and as well as on Google's Container Engine (GCE, Kubernetes on Google Cloud). I use the MacBook/local environment to develop and test my YAML files and then, upon completion, try them on GCE. </p>
<p>Currently I need to work with each environment individually: I need to edit the YAML files in my local environment and, when ready, (git) clone them to a GCE environment and then use/deploy them. This is a somewhat cumbersome process.</p>
<p>Ideally, I would like to use kubectl from my Macbook to easily switch between the local minikube or GCE Kubernetes environments and to easily determine where the YAML files are used. Is there a simple way to switch contexts to do this?</p> | <p>You can switch from local (minikube) to gcloud and back with:</p>
<p><code>kubectl config use-context CONTEXT_NAME</code></p>
<p>to list all contexts:</p>
<p><code>kubectl config get-contexts</code></p>
<p>You can create different enviroments for local and gcloud and put it in separate yaml files. </p> | {
"question_id": 43643463,
"question_date": "2017-04-26T19:57:47.590Z",
"question_score": 231,
"tags": "kubernetes|google-kubernetes-engine|minikube",
"answer_id": 43661208,
"answer_date": "2017-04-27T14:52:26.473Z",
"answer_score": 452
} |
Please answer the following Stack Overflow question:
Title: npm failed to install time with make not found error
<p>When i try to install time on nodejs server i get the below error:</p>
<pre><code>[email protected] install /var/www/track/node_modules/time
node-gyp rebuild
gyp ERR! build error
gyp ERR! stack Error: not found: make
gyp ERR! stack at F (/usr/lib/nodejs/npm/node_modules/which/which.js:43:28)
gyp ERR! stack at E (/usr/lib/nodejs/npm/node_modules/which/which.js:46:29)
gyp ERR! stack at /usr/lib/nodejs/npm/node_modules/which/which.js:57:16
gyp ERR! stack at Object.oncomplete (fs.js:297:15)
gyp ERR! System Linux 3.2.0-31-virtual
gyp ERR! command "node" "/usr/lib/nodejs/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"
gyp ERR! cwd /var/www/track/node_modules/time
gyp ERR! node -v v0.8.15
gyp ERR! node-gyp -v v0.7.1
gyp ERR! not ok
npm ERR! [email protected] install: `node-gyp rebuild`
npm ERR! `sh "-c" "node-gyp rebuild"` failed with 1
npm ERR!
npm ERR! Failed at the [email protected] install script.
npm ERR! This is most likely a problem with the time package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! node-gyp rebuild
npm ERR! You can get their info via:
npm ERR! npm owner ls time
npm ERR! There is likely additional logging output above.
npm ERR! System Linux 3.2.0-31-virtual
npm ERR! command "nodejs" "/usr/bin/npm" "install" "time"
npm ERR! cwd /var/www/track
npm ERR! node -v v0.8.15
npm ERR! npm -v 1.1.66
npm ERR! code ELIFECYCLE
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /var/www/track/npm-debug.log
npm ERR! not ok code 0
</code></pre> | <p>Which OS are you using?</p>
<p>If it's Ubuntu you'll need to install the build-essential package:</p>
<pre><code>$ sudo apt-get install build-essential
</code></pre>
<p>Then try to install the package again.</p> | {
"question_id": 14772508,
"question_date": "2013-02-08T12:23:53.927Z",
"question_score": 231,
"tags": "node.js",
"answer_id": 14772631,
"answer_date": "2013-02-08T12:29:56.673Z",
"answer_score": 714
} |
Please answer the following Stack Overflow question:
Title: What are good examples of genetic algorithms/genetic programming solutions?
<p><a href="http://en.wikipedia.org/wiki/Genetic_algorithm" rel="noreferrer">Genetic algorithms</a> (GA) and <a href="http://en.wikipedia.org/wiki/Genetic_programming" rel="noreferrer">genetic programming</a> (GP) are interesting areas of research. </p>
<p>I'd like to know about specific problems you have solved using GA/GP and what libraries/frameworks you used if you didn't roll your own.</p>
<p>Questions:</p>
<ul>
<li>What problems have you used GA/GP to solve?</li>
<li>What libraries/frameworks did you use?</li>
</ul>
<p>I'm looking for first-hand experiences, so please do not answer unless you have that.</p> | <p><em>Not</em> homework.</p>
<p>My first job as a professional programmer (1995) was writing a genetic-algorithm based automated trading system for S&P500 futures. The application was written in Visual Basic 3 [!] and I have no idea how I did anything back then, since VB3 didn't even have classes.</p>
<p>The application started with a population of randomly-generated fixed-length strings (the "gene" part), each of which corresponded to a specific shape in the minute-by-minute price data of the S&P500 futures, as well as a specific order (buy or sell) and stop-loss and stop-profit amounts. Each string (or "gene") had its profit performance evaluated by a run through 3 years of historical data; whenever the specified "shape" matched the historical data, I assumed the corresponding buy or sell order and evaluated the trade's result. I added the caveat that each gene started with a fixed amount of money and could thus potentially go broke and be removed from the gene pool entirely.</p>
<p>After each evaluation of a population, the survivors were cross-bred randomly (by just mixing bits from two parents), with the likelihood of a gene being selected as a parent being proportional to the profit it produced. I also added the possibility of point mutations to spice things up a bit. After a few hundred generations of this, I ended up with a population of genes that could turn $5000 into an average of about $10000 with no chance of death/brokeness (on the historical data, of course).</p>
<p>Unfortunately, I never got the chance to use this system live, since my boss lost close to $100,000 in less than 3 months trading the traditional way, and he lost his willingness to continue with the project. In retrospect, I think the system would have made huge profits - not because I was necessarily doing anything right, but because the population of genes that I produced happened to be biased towards buy orders (as opposed to sell orders) by about a 5:1 ratio. And as we know with our 20/20 hindsight, the market went up a bit after 1995.</p> | {
"question_id": 1538235,
"question_date": "2009-10-08T14:37:53.537Z",
"question_score": 231,
"tags": "algorithm|artificial-intelligence|genetic-algorithm|evolutionary-algorithm",
"answer_id": 1538464,
"answer_date": "2009-10-08T15:11:52.377Z",
"answer_score": 152
} |
Please answer the following Stack Overflow question:
Title: Create one-time subscription
<p>I need to create a subscription to an <code>Observable</code> that is immediately disposed of when it is first called.</p>
<p>Is there something like:</p>
<pre><code>observable.subscribeOnce(func);
</code></pre>
<p>My use case, I am creating a subscription in an express route handler and the subscription is being called multiple times per request.</p> | <p>Not 100% certain about what you need, but if you only want to observe the first value, then use either <code>first()</code> or <code>take(1)</code>:</p>
<pre><code>observable.first().subscribe(func);
</code></pre>
<p>note: <code>.take(1)</code> and <code>.first()</code> both unsubscribe automatically when their condition is met</p>
<h1>Update from RxJS 5.5+</h1>
<p>From comment by <a href="https://stackoverflow.com/questions/28007777/create-one-time-subscription/28030416#comment91800031_28030416">Coderer</a>.</p>
<pre class="lang-js prettyprint-override"><code>import { first } from 'rxjs/operators'
observable
.pipe(first())
.subscribe(func);
</code></pre>
<p><a href="https://github.com/ReactiveX/rxjs/blob/22c6137116268af91fafa14cc89d5db4f234bec3/doc/pipeable-operators.md#why" rel="noreferrer">Here's why</a></p> | {
"question_id": 28007777,
"question_date": "2015-01-18T06:38:20.263Z",
"question_score": 231,
"tags": "rxjs",
"answer_id": 28030416,
"answer_date": "2015-01-19T17:33:45.607Z",
"answer_score": 411
} |
Please answer the following Stack Overflow question:
Title: Execute code when Django starts ONCE only?
<p>I'm writing a Django Middleware class that I want to execute only once at startup, to initialise some other arbritary code. I've followed the very nice solution posted by sdolan <a href="https://stackoverflow.com/questions/3495964/in-django-how-do-i-call-the-subcommand-syncdb-from-the-initialization-script">here</a>, but the "Hello" message is output to the terminal <em>twice</em>. E.g.</p>
<pre><code>from django.core.exceptions import MiddlewareNotUsed
from django.conf import settings
class StartupMiddleware(object):
def __init__(self):
print "Hello world"
raise MiddlewareNotUsed('Startup complete')
</code></pre>
<p>and in my Django settings file, I've got the class included in the <code>MIDDLEWARE_CLASSES</code> list.</p>
<p>But when I run Django using runserver and request a page, I get in the terminal</p>
<pre><code>Django version 1.3, using settings 'config.server'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
Hello world
[22/Jul/2011 15:54:36] "GET / HTTP/1.1" 200 698
Hello world
[22/Jul/2011 15:54:36] "GET /static/css/base.css HTTP/1.1" 200 0
</code></pre>
<p>Any ideas why "Hello world" is printed twice? Thanks.</p> | <p>Update from Pykler's answer below: Django 1.7 now has a <a href="https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.ready" rel="noreferrer">hook for this</a></p>
<hr>
<p>Don't do it this way.</p>
<p>You don't want "middleware" for a one-time startup thing.</p>
<p>You want to execute code in the top-level <code>urls.py</code>. That module is imported and executed once.</p>
<p><code>urls.py</code></p>
<pre><code>from django.confs.urls.defaults import *
from my_app import one_time_startup
urlpatterns = ...
one_time_startup()
</code></pre> | {
"question_id": 6791911,
"question_date": "2011-07-22T15:00:10.877Z",
"question_score": 231,
"tags": "python|django",
"answer_id": 6792076,
"answer_date": "2011-07-22T15:11:17.607Z",
"answer_score": 140
} |
Please answer the following Stack Overflow question:
Title: Selecting the first "n" items with jQuery
<p>With Jquery, I need to select just the first "n" items from the page, for example the first 20 links instead of selecting all of them with the usual</p>
<pre><code>$("a")
</code></pre>
<p>Sounds simple but the jQuery manual has no evidence of something like this.</p> | <p>You probably want to read up on <a href="https://api.jquery.com/slice/" rel="noreferrer">slice</a>. Your code will look something like this:</p>
<pre><code>$("a").slice(0,20)
</code></pre> | {
"question_id": 1865552,
"question_date": "2009-12-08T08:38:02.477Z",
"question_score": 231,
"tags": "jquery",
"answer_id": 1865571,
"answer_date": "2009-12-08T08:42:55.793Z",
"answer_score": 394
} |
Please answer the following Stack Overflow question:
Title: How to prevent docker from starting a container automatically on system startup?
<p>Docker starts a container on every system startup (debian) but I didn't create a service to do so. How can I prevent docker from doing that?</p> | <p>Docker will autostart any container with a RestartPolicy of 'always' when the docker service initially starts. You won't find any evidence of this within cron or any other normal system startup scripts; you'll have to dig into the container configuration to find it.</p>
<p><code>docker inspect my-container</code>
(Look for RestartPolicy in the output)</p>
<p>I've mostly had this situation occur when a container was created with <code>--restart always</code>, and the situation later changed such that I no longer wanted this to happen.</p>
<p>After docker 1.11, this is easy to fix</p>
<p><code>docker update --restart=no my-container</code></p>
<p>Original answer is here: <a href="https://stackoverflow.com/questions/37599128/docker-how-do-you-disable-auto-restart-on-a-container">docker - how do you disable auto-restart on a container?</a></p> | {
"question_id": 40513545,
"question_date": "2016-11-09T18:21:03.653Z",
"question_score": 231,
"tags": "docker|startup",
"answer_id": 45022623,
"answer_date": "2017-07-10T22:29:58.657Z",
"answer_score": 449
} |
Please answer the following Stack Overflow question:
Title: Identifying the dependency relationship for python packages installed with pip
<p>When I do a pip freeze I see large number of Python packages that I didn't explicitly install, e.g.</p>
<pre><code>$ pip freeze
Cheetah==2.4.3
GnuPGInterface==0.3.2
Landscape-Client==11.01
M2Crypto==0.20.1
PAM==0.4.2
PIL==1.1.7
PyYAML==3.09
Twisted-Core==10.2.0
Twisted-Web==10.2.0
(etc.)
</code></pre>
<p>Is there a way for me to determine why pip installed these particular dependent packages? In other words, how do I determine the parent package that had these packages as dependencies? </p>
<p>For example, I might want to use Twisted and I don't want to depend on a package until I know more about not accidentally uninstalling it or upgrading it.</p> | <p>You could try <a href="https://github.com/naiquevin/pipdeptree" rel="noreferrer">pipdeptree</a> which displays dependencies as a tree structure e.g.:
</p>
<pre><code>$ pipdeptree
Lookupy==0.1
wsgiref==0.1.2
argparse==1.2.1
psycopg2==2.5.2
Flask-Script==0.6.6
- Flask [installed: 0.10.1]
- Werkzeug [required: >=0.7, installed: 0.9.4]
- Jinja2 [required: >=2.4, installed: 2.7.2]
- MarkupSafe [installed: 0.18]
- itsdangerous [required: >=0.21, installed: 0.23]
alembic==0.6.2
- SQLAlchemy [required: >=0.7.3, installed: 0.9.1]
- Mako [installed: 0.9.1]
- MarkupSafe [required: >=0.9.2, installed: 0.18]
ipython==2.0.0
slugify==0.0.1
redis==2.9.1
</code></pre>
<p>To get it run:</p>
<pre><code>pip install pipdeptree
</code></pre>
<p><br>
<strong>EDIT:</strong> as noted by @Esteban in the comments you can also list the tree in reverse with <code>-r</code> or for a single package with <code>-p <package_name></code> so to find what installed Werkzeug you could run:</p>
<pre class="lang-bash prettyprint-override"><code>$ pipdeptree -r -p Werkzeug
Werkzeug==0.11.15
- Flask==0.12 [requires: Werkzeug>=0.7]
</code></pre> | {
"question_id": 9232568,
"question_date": "2012-02-10T18:04:22.950Z",
"question_score": 231,
"tags": "python|pip",
"answer_id": 30450999,
"answer_date": "2015-05-26T06:28:24.690Z",
"answer_score": 298
} |
Please answer the following Stack Overflow question:
Title: Longest line in a file
<p>I'm looking for a simple way to find the length of the longest line in a file. Ideally, it would be a simple bash shell command instead of a script.</p> | <p>Using wc (GNU coreutils) 7.4:</p>
<pre><code>wc -L filename
</code></pre>
<p>gives:</p>
<pre><code>101 filename
</code></pre> | {
"question_id": 1655372,
"question_date": "2009-10-31T19:34:36.953Z",
"question_score": 231,
"tags": "bash|shell|utilities",
"answer_id": 3191708,
"answer_date": "2010-07-07T03:33:06.877Z",
"answer_score": 308
} |
Please answer the following Stack Overflow question:
Title: How and where are Annotations used in Java?
<p>What are the major areas that we can use Annotations? Is the feature a replacement for XML based configuration?</p> | <p>Annotations are <em>meta-meta-objects</em> which can be used to describe other <em>meta-objects</em>. Meta-objects are classes, fields and methods. Asking an object for its meta-object (e.g. <code>anObj.getClass()</code> ) is called <em>introspection</em>. The introspection can go further and we can ask a meta-object what are its annotations (e.g. <code>aClass.getAnnotations</code>). Introspection and annotations belong to what is called <em>reflection</em> and <em>meta-programming</em>. </p>
<p>An annotation needs to be interpreted in one way or another to be useful. Annotations can be interpreted at <em>development-time</em> by the IDE or the compiler, or at <em>run-time</em> by a framework. </p>
<p>Annotation processing is a very powerful mechanism and can be used in a lot of different ways:</p>
<ul>
<li>to describe constraints or usage of an element: e.g. <code>@Deprecated, @Override</code>, or <code>@NotNull</code></li>
<li>to describe the "nature" of an element, e.g. <code>@Entity, @TestCase, @WebService</code></li>
<li>to describe the behavior of an element: <code>@Statefull, @Transaction</code> </li>
<li>to describe how to process the element: <code>@Column, @XmlElement</code></li>
</ul>
<p>In all cases, an annotation is used to <em>describe</em> the element and clarify its <em>meaning</em>. </p>
<p>Prior to JDK5, information that is now expressed with annotations needed to be stored somewhere else, and XML files were frequently used. But it is more convenient to use annotations because they will belong to the Java code itself, and are hence much easier to manipulate than XML.</p>
<p>Usage of annotations:</p>
<ul>
<li>Documentation, e.g. XDoclet</li>
<li>Compilation</li>
<li>IDE</li>
<li>Testing framework, e.g. JUnit</li>
<li>IoC container e.g. as Spring</li>
<li>Serialization, e.g. XML </li>
<li>Aspect-oriented programming (AOP), e.g. Spring AOP</li>
<li>Application servers, e.g. EJB container, Web Service</li>
<li>Object-relational mapping (ORM), e.g. Hibernate, JPA</li>
<li>and many more...</li>
</ul>
<p>...have a look for instance at the project <a href="http://projectlombok.org/features/index.html" rel="noreferrer">Lombok</a>, which uses annotations to define how to generate <code>equals</code> or <code>hashCode</code> methods.</p> | {
"question_id": 1372876,
"question_date": "2009-09-03T11:33:09.700Z",
"question_score": 231,
"tags": "java|annotations",
"answer_id": 1918154,
"answer_date": "2009-12-16T22:11:23.143Z",
"answer_score": 323
} |
Please answer the following Stack Overflow question:
Title: An algorithm for inflating/deflating (offsetting, buffering) polygons
<p>How would I "inflate" a polygon? That is, I want to do something similar to this:</p>
<p><img src="https://i.stack.imgur.com/GUzIo.gif" alt="alt text" /></p>
<p>The requirement is that the new (inflated) polygon's edges/points are all at the same constant distance from the old (original) polygon's (on the example picture they are not, since then it would have to use arcs for inflated vertices, but let's forget about that for now ;) ).</p>
<p>The mathematical term for what I'm looking for is actually <strong>inward/outward polygon offseting</strong>. +1 to balint for pointing this out. The alternative naming is <strong>polygon buffering</strong>.</p>
<p><strong>Results of my search:</strong></p>
<p>Here are some links:</p>
<ul>
<li><a href="http://fcacciola.50webs.com/Offseting%20Methods.htm" rel="noreferrer">A Survey of Polygon Offseting Strategies</a></li>
<li><a href="http://groups.google.si/group/comp.graphics/browse_thread/thread/4799ab44d71f434e/e3ec0b40c231706c?hl=en&ie=UTF-8&q=offset+polygon&pli=1" rel="noreferrer">Polygon offset, PROBLEM</a></li>
<li><a href="https://geogra.uah.es/patxi/gisweb/BuffersModule/Buff_poly.htm" rel="noreferrer">Buffering Polygon Data</a></li>
</ul> | <p>I thought I might briefly mention my own <strong>polygon clipping and offsetting library</strong> - <a href="http://www.angusj.com/delphi/clipper.php" rel="nofollow noreferrer"><strong>Clipper</strong></a>.</p>
<p>While <a href="http://www.angusj.com/delphi/clipper.php" rel="nofollow noreferrer">Clipper</a> is primarily designed for polygon clipping operations, it does polygon offsetting too. The library is <strong>open source freeware</strong> written in <strong>Delphi, C++ and C#</strong>. It has a very unencumbered <a href="http://www.boost.org/LICENSE_1_0.txt" rel="nofollow noreferrer">Boost</a> license allowing it to be used in both freeware and commercial applications without charge.</p>
<p>Polygon offsetting can be performed using one of three offset styles - squared, round and mitered.</p>
<p><img src="https://i.stack.imgur.com/LqZeh.png" alt="Polygon offsetting styles" /></p>
<p>August 2022:<br>
<a href="https://github.com/AngusJohnson/Clipper2" rel="nofollow noreferrer"><b>Clipper2</b></a> has now been formally released and it supercedes Clipper (aka Clipper1).</p> | {
"question_id": 1109536,
"question_date": "2009-07-10T13:32:47.490Z",
"question_score": 231,
"tags": "algorithm|geometry|polygon|computational-geometry|buffering",
"answer_id": 7947389,
"answer_date": "2011-10-30T19:52:32.867Z",
"answer_score": 159
} |
Please answer the following Stack Overflow question:
Title: Immutability of Strings in Java
<p>Consider the following example.</p>
<pre><code>String str = new String();
str = "Hello";
System.out.println(str); //Prints Hello
str = "Help!";
System.out.println(str); //Prints Help!
</code></pre>
<p>Now, in Java, String objects are immutable. Then how come the object <code>str</code> can be assigned value "Help!". Isn't this contradicting the immutability of strings in Java? Can anybody please explain me the exact concept of immutability?</p>
<p>Edit:</p>
<p>Ok. I am now getting it, but just one follow-up question. What about the following code: </p>
<pre><code>String str = "Mississippi";
System.out.println(str); // prints Mississippi
str = str.replace("i", "!");
System.out.println(str); // prints M!ss!ss!pp!
</code></pre>
<p>Does this mean that two objects are created again ("Mississippi" and "M!ss!ss!pp!") and the reference <code>str</code> points to a different object after <code>replace()</code> method? </p> | <p><code>str</code> is not an object, it's a reference to an object. <code>"Hello"</code> and <code>"Help!"</code> are two distinct <code>String</code> objects. Thus, <code>str</code> <em>points to</em> a string. You can change what it <em>points to</em>, but not that which it <em>points at</em>.</p>
<p>Take this code, for example:</p>
<pre><code>String s1 = "Hello";
String s2 = s1;
// s1 and s2 now point at the same string - "Hello"
</code></pre>
<p>Now, there is nothing<sup>1</sup> we could do to <code>s1</code> that would affect the value of <code>s2</code>. They refer to the same object - the string <code>"Hello"</code> - but that object is immutable and thus cannot be altered.</p>
<p>If we do something like this:</p>
<pre><code>s1 = "Help!";
System.out.println(s2); // still prints "Hello"
</code></pre>
<p>Here we see the difference between mutating an object, and changing a reference. <code>s2</code> still points to the same object as we initially set <code>s1</code> to point to. Setting <code>s1</code> to <code>"Help!"</code> only changes the <em>reference</em>, while the <code>String</code> object it originally referred to remains unchanged.</p>
<p>If strings <em>were</em> mutable, we could do something like this:</p>
<pre><code>String s1 = "Hello";
String s2 = s1;
s1.setCharAt(1, 'a'); // Fictional method that sets character at a given pos in string
System.out.println(s2); // Prints "Hallo"
</code></pre>
<hr />
<p><strong>Edit to respond to OP's edit:</strong></p>
<p>If you look at the <a href="http://www.docjar.com/html/api/java/lang/String.java.html#2041" rel="noreferrer">source code for String.replace(char,char)</a> (also available in src.zip in your JDK installation directory -- a pro tip is to look there whenever you wonder how something really works) you can see that what it does is the following:</p>
<ul>
<li>If there is one or more occurrences of <code>oldChar</code> in the current string, make a copy of the current string where all occurrences of <code>oldChar</code> are replaced with <code>newChar</code>.</li>
<li>If the <code>oldChar</code> is not present in the current string, return the current string.</li>
</ul>
<p>So yes, <code>"Mississippi".replace('i', '!')</code> creates a new <code>String</code> object. Again, the following holds:</p>
<pre><code>String s1 = "Mississippi";
String s2 = s1;
s1 = s1.replace('i', '!');
System.out.println(s1); // Prints "M!ss!ss!pp!"
System.out.println(s2); // Prints "Mississippi"
System.out.println(s1 == s2); // Prints "false" as s1 and s2 are two different objects
</code></pre>
<p>Your homework for now is to see what the above code does if you change <code>s1 = s1.replace('i', '!');</code> to <code>s1 = s1.replace('Q', '!');</code> :)</p>
<hr />
<p><sup>1</sup> Actually, it <em>is</em> possible to mutate strings (and other immutable objects). It requires reflection and is very, very dangerous and should never ever be used unless you're actually interested in destroying the program.</p> | {
"question_id": 1552301,
"question_date": "2009-10-12T01:23:21.427Z",
"question_score": 231,
"tags": "java|string|immutability",
"answer_id": 1553110,
"answer_date": "2009-10-12T07:04:59.453Z",
"answer_score": 340
} |
Please answer the following Stack Overflow question:
Title: Is there any way to view the currently mapped keys in Vim?
<p>Basically, I'd like to view all of the keys maps made in the current buffer by all of plugins, vimrc, etc, in the current buffer. Is there anyway to do this?</p> | <p>You can do that with the <code>:map</code> command. There are also other variants.</p>
<ul>
<li><code>:nmap</code> for normal mode mappings</li>
<li><code>:vmap</code> for visual mode mappings</li>
<li><code>:imap</code> for insert mode mappings</li>
</ul>
<p>The above list is not complete. Typing <code>:help map</code> in Vim will give you more info.</p> | {
"question_id": 7642746,
"question_date": "2011-10-04T02:35:35.513Z",
"question_score": 231,
"tags": "vim",
"answer_id": 7642762,
"answer_date": "2011-10-04T02:38:56.317Z",
"answer_score": 308
} |
Please answer the following Stack Overflow question:
Title: AutoMapper: "Ignore the rest"?
<p>Is there a way to tell AutoMapper to ignore all of the properties except the ones which are mapped explicitly? </p>
<p>I have external DTO classes which are likely to change from the outside and I want to avoid specifying each property to be ignored explicitly, since adding new properties will break the functionality (cause exceptions) when trying to map them into my own objects.</p> | <p>This is an extension method I wrote that ignores all non existing properties on the destination. Not sure if it will still be useful as the question is more than two years old, but I ran into the same issue having to add a lot of manual Ignore calls.</p>
<pre><code>public static IMappingExpression<TSource, TDestination> IgnoreAllNonExisting<TSource, TDestination>
(this IMappingExpression<TSource, TDestination> expression)
{
var flags = BindingFlags.Public | BindingFlags.Instance;
var sourceType = typeof (TSource);
var destinationProperties = typeof (TDestination).GetProperties(flags);
foreach (var property in destinationProperties)
{
if (sourceType.GetProperty(property.Name, flags) == null)
{
expression.ForMember(property.Name, opt => opt.Ignore());
}
}
return expression;
}
</code></pre>
<p>Usage:</p>
<pre><code>Mapper.CreateMap<SourceType, DestinationType>()
.IgnoreAllNonExisting();
</code></pre>
<p><strong>UPDATE</strong>: Apparently this does not work correctly if you have custom mappings because it overwrites them. I guess it could still work if call IgnoreAllNonExisting first and then the custom mappings later.</p>
<p>schdr has a solution (as an answer to this question) which uses <code>Mapper.GetAllTypeMaps()</code> to find out which properties are unmapped and auto ignore them. Seems like a more robust solution to me.</p> | {
"question_id": 954480,
"question_date": "2009-06-05T06:18:37.093Z",
"question_score": 231,
"tags": ".net|automapper",
"answer_id": 6280647,
"answer_date": "2011-06-08T14:44:25.613Z",
"answer_score": 88
} |
Please answer the following Stack Overflow question:
Title: What does "keyof typeof" mean in TypeScript?
<p>Explain to me what <code>keyof typeof</code> means in TypeScript</p>
<p>Example:</p>
<pre><code>enum ColorsEnum {
white = '#ffffff',
black = '#000000',
}
type Colors = keyof typeof ColorsEnum;
</code></pre>
<p>The last row is equivalent to:</p>
<pre><code>type Colors = "white" | "black"
</code></pre>
<p>But how does it work?</p>
<p>I would expect <code>typeof ColorsEnum</code> to return something like <code>"Object"</code> and then <code>keyof "Object"</code> to not do anything interesting. But I am obviously wrong.</p> | <p><code>keyof</code> takes an object type and returns a type that accepts any of the object's keys.</p>
<pre class="lang-js prettyprint-override"><code>type Point = { x: number; y: number };
type P = keyof Point; // type '"x" || "y"'
const coordinate: P = 'z' // Type '"z"' is not assignable to type '"x" | "y"'.
</code></pre>
<h2>typeof with TypeScript types</h2>
<p><code>typeof</code> behaves differently when called on javascript objects, to when it is called on typescript types.</p>
<ul>
<li>TypeScript uses <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof" rel="noreferrer">javascript's typeof</a> when called on javascript values at runtime and returns one of <code>"undefined", "object", "boolean", "number", "bigint", "string", "symbol", "function"</code></li>
<li><a href="https://www.typescriptlang.org/docs/handbook/2/typeof-types.html" rel="noreferrer">TypeScript's typeof</a> is called on type values, but can also be called on javascript values when in a type expression. It can also infer the type of javascript objects, returning a more detailed object type.</li>
</ul>
<pre class="lang-js prettyprint-override"><code>type Language = 'EN' | 'ES';
const userLanguage: Language = 'EN';
const preferences = { language: userLanguage, theme: 'light' };
console.log(typeof preferences); // "object"
type Preferences = typeof preferences; // type '{language: 'EN''; theme: string; }'
</code></pre>
<p>Because the second <code>typeof preferences</code> is in a type expression it is actually TypeScript's own <code>typeof</code> that get called, and not javascript's.</p>
<h2>keyof typeof</h2>
<p>Because <a href="https://www.typescriptlang.org/docs/handbook/2/keyof-types.html" rel="noreferrer"><code>keyof</code></a> is a TypeScript concept we will be calling TypeScript's verion of <code>typeof</code>.</p>
<p><code>keyof typeof</code> will infer the type of a javascript object and return a type that is the union of its keys. Because it can infer the exact value of the keys it can return a union of their <a href="https://www.typescriptlang.org/docs/handbook/literal-types.html" rel="noreferrer">literal types</a> instead of just returning "string".</p>
<pre class="lang-js prettyprint-override"><code>type PreferenceKeys = keyof typeof preferences; // type '"language" | "theme"'
</code></pre> | {
"question_id": 55377365,
"question_date": "2019-03-27T12:36:37.590Z",
"question_score": 231,
"tags": "typescript|typeof|union-types|keyof",
"answer_id": 65958095,
"answer_date": "2021-01-29T16:18:39.663Z",
"answer_score": 59
} |
Please answer the following Stack Overflow question:
Title: Is there a way to simulate the C++ 'friend' concept in Java?
<p>I would like to be able to write a Java class in one package which can access non-public methods of a class in another package without having to make it a subclass of the other class. Is this possible?</p> | <p>The 'friend' concept is useful in Java, for example, to separate an API from its implementation. It is common for implementation classes to need access to API class internals but these should not be exposed to API clients. This can be achieved using the 'Friend Accessor' pattern as detailed below:</p>
<p>The class exposed through the API:</p>
<pre><code>package api;
public final class Exposed {
static {
// Declare classes in the implementation package as 'friends'
Accessor.setInstance(new AccessorImpl());
}
// Only accessible by 'friend' classes.
Exposed() {
}
// Only accessible by 'friend' classes.
void sayHello() {
System.out.println("Hello");
}
static final class AccessorImpl extends Accessor {
protected Exposed createExposed() {
return new Exposed();
}
protected void sayHello(Exposed exposed) {
exposed.sayHello();
}
}
}
</code></pre>
<p>The class providing the 'friend' functionality:</p>
<pre><code>package impl;
public abstract class Accessor {
private static Accessor instance;
static Accessor getInstance() {
Accessor a = instance;
if (a != null) {
return a;
}
return createInstance();
}
private static Accessor createInstance() {
try {
Class.forName(Exposed.class.getName(), true,
Exposed.class.getClassLoader());
} catch (ClassNotFoundException e) {
throw new IllegalStateException(e);
}
return instance;
}
public static void setInstance(Accessor accessor) {
if (instance != null) {
throw new IllegalStateException(
"Accessor instance already set");
}
instance = accessor;
}
protected abstract Exposed createExposed();
protected abstract void sayHello(Exposed exposed);
}
</code></pre>
<p>Example access from a class in the 'friend' implementation package:</p>
<pre><code>package impl;
public final class FriendlyAccessExample {
public static void main(String[] args) {
Accessor accessor = Accessor.getInstance();
Exposed exposed = accessor.createExposed();
accessor.sayHello(exposed);
}
}
</code></pre> | {
"question_id": 182278,
"question_date": "2008-10-08T11:37:53.360Z",
"question_score": 231,
"tags": "java|c++|friend|accessor",
"answer_id": 316838,
"answer_date": "2008-11-25T09:44:13.493Z",
"answer_score": 47
} |
Please answer the following Stack Overflow question:
Title: How to determine if a process runs inside lxc/Docker?
<p>Is there any way to determine if a process (script) runs inside an lxc container (~ Docker runtime)? I know that some programs are able to detect whether they run inside a virtual machine, is something similar available for lxc/docker?</p> | <p>The most reliable way is to check <code>/proc/1/cgroup</code>. It will tell you the control groups of the init process, and when you are <em>not</em> in a container, that will be <code>/</code> for all hierarchies. When you are <em>inside</em> a container, you will see the name of the anchor point. With LXC/Docker containers, it will be something like <code>/lxc/<containerid></code> or <code>/docker/<containerid></code> respectively.</p> | {
"question_id": 20010199,
"question_date": "2013-11-15T20:42:04.983Z",
"question_score": 231,
"tags": "linux|bash|docker",
"answer_id": 20012536,
"answer_date": "2013-11-15T23:36:06.527Z",
"answer_score": 198
} |
Please answer the following Stack Overflow question:
Title: smart pointers (boost) explained
<p>What is the difference between the following set of pointers? When do you use each pointer in production code, if at all?</p>
<p>Examples would be appreciated!</p>
<ol>
<li><p><code>scoped_ptr</code></p></li>
<li><p><code>shared_ptr</code></p></li>
<li><p><code>weak_ptr</code></p></li>
<li><p><code>intrusive_ptr</code></p></li>
</ol>
<p>Do you use boost in production code?</p> | <h3>Basic properties of smart pointers</h3>
<p>It's easy when you have properties that you can assign each smart pointer. There are three important properties.</p>
<ul>
<li><strong>no ownership at all</strong></li>
<li><strong>transfer of ownership</strong></li>
<li><strong>share of ownership</strong></li>
</ul>
<p>The first means that a smart pointer cannot delete the object, because it doesn't own it. The second means that only one smart pointer can ever point to the same object at the same time. If the smart pointer is to be returned from functions, the ownership is transferred to the returned smart pointer, for example. </p>
<p>The third means that multiple smart pointers can point to the same object at the same time. This applies to a <em>raw pointer</em> too, however raw pointers lack an important feature: They do not define whether they are <em>owning</em> or not. A share of ownership smart pointer will delete the object if every owner gives up the object. This behavior happens to be needed often, so shared owning smart pointers are widely spread.</p>
<p>Some owning smart pointers support neither the second nor the third. They can therefore not be returned from functions or passed somewhere else. Which is most suitable for <code>RAII</code> purposes where the smart pointer is kept local and is just created so it frees an object after it goes out of scope. </p>
<p>Share of ownership can be implemented by having a copy constructor. This naturally copies a smart pointer and both the copy and the original will reference the same object. Transfer of ownership cannot really be implemented in C++ currently, because there are no means to transfer something from one object to another supported by the language: If you try to return an object from a function, what is happening is that the object is copied. So a smart pointer that implements transfer of ownership has to use the copy constructor to implement that transfer of ownership. However, this in turn breaks its usage in containers, because requirements state a certain behavior of the copy constructor of elements of containers which is incompatible with this so-called "moving constructor" behavior of these smart pointers. </p>
<p>C++1x provides native support for transfer-of-ownership by introducing so-called "move constructors" and "move assignment operators". It also comes with such a transfer-of-ownership smart pointer called <code>unique_ptr</code>. </p>
<h3>Categorizing smart pointers</h3>
<p><code>scoped_ptr</code> is a smart pointer that is neither transferable nor sharable. It's just usable if you locally need to allocate memory, but be sure it's freed again when it goes out of scope. But it can still be swapped with another scoped_ptr, if you wish to do so. </p>
<p><code>shared_ptr</code> is a smart pointer that shares ownership (third kind above). It is reference counted so it can see when the last copy of it goes out of scope and then it frees the object managed. </p>
<p><code>weak_ptr</code> is a non-owning smart pointer. It is used to reference a managed object (managed by a shared_ptr) without adding a reference count. Normally, you would need to get the raw pointer out of the shared_ptr and copy that around. But that would not be safe, as you would not have a way to check when the object was actually deleted. So, weak_ptr provides means by referencing an object managed by shared_ptr. If you need to access the object, you can lock the management of it (to avoid that in another thread a shared_ptr frees it while you use the object) and then use it. If the weak_ptr points to an object already deleted, it will notice you by throwing an exception. Using weak_ptr is most beneficial when you have a cyclic reference: Reference counting cannot easily cope with such a situation. </p>
<p><code>intrusive_ptr</code> is like a shared_ptr but it does not keep the reference count in a shared_ptr but leaves incrementing/decrementing the count to some helper functions that need to be defined by the object that is managed. This has the advantage that an already referenced object (which has a reference count incremented by an external reference counting mechanism) can be stuffed into an intrusive_ptr - because the reference count is not anymore internal to the smart pointer, but the smart pointer uses an existing reference counting mechanism.</p>
<p><code>unique_ptr</code> is a transfer of ownership pointer. You cannot copy it, but you can move it by using C++1x's move constructors:</p>
<pre><code>unique_ptr<type> p(new type);
unique_ptr<type> q(p); // not legal!
unique_ptr<type> r(move(p)); // legal. p is now empty, but r owns the object
unique_ptr<type> s(function_returning_a_unique_ptr()); // legal!
</code></pre>
<p>This is the semantic that std::auto_ptr obeys, but because of missing native support for moving, it fails to provide them without pitfalls. unique_ptr will automatically steal resources from a temporary other unique_ptr which is one of the key features of move semantics. auto_ptr will be deprecated in the next C++ Standard release in favor of unique_ptr. C++1x will also allow stuffing objects that are only movable but not copyable into containers. So you can stuff unique_ptr's into a vector for example. I'll stop here and reference you to <a href="https://devblogs.microsoft.com/cppblog/rvalue-references-c0x-features-in-vc10-part-2/" rel="noreferrer">a fine article</a> about this if you want to read more about this. </p> | {
"question_id": 569775,
"question_date": "2009-02-20T14:42:46.923Z",
"question_score": 231,
"tags": "c++|boost|smart-pointers",
"answer_id": 569931,
"answer_date": "2009-02-20T15:19:34.980Z",
"answer_score": 353
} |
Please answer the following Stack Overflow question:
Title: What is the purpose of the "Prefer 32-bit" setting in Visual Studio and how does it actually work?
<p><img src="https://i.stack.imgur.com/6OyyU.jpg" alt="Enter image description here"></p>
<p>It is unclear to me how the compiler will automatically know to compile for 64-bit when it needs to. How does it know when it can confidently target 32-bit?</p>
<p>I am mainly curious about how the compiler knows which architecture to target when compiling. Does it analyze the code and make a decision based on what it finds?</p> | <p>Microsoft has a blog entry <em><a href="https://dzone.com/articles/what-anycpu-really-means-net" rel="noreferrer">What AnyCPU Really Means As Of .NET 4.5 and Visual Studio 11</a></em>:</p>
<blockquote>
<p>In .NET 4.5 and Visual Studio 11 the cheese has been moved. The
default for most .NET projects is again AnyCPU, but there is more than
one meaning to AnyCPU now. There is an additional sub-type of AnyCPU,
“Any CPU 32-bit preferred”, which is the new default (overall, there
are now five options for the /platform C# compiler switch: x86,
Itanium, x64, anycpu, and anycpu32bitpreferred). When using the "Prefer 32-Bit"
flavor of AnyCPU, the semantics are as follows:</p>
<ul>
<li>If the process runs on a 32-bit Windows system, it runs as a 32-bit process. IL is compiled to x86 machine code. </li>
<li>If the process runs on a 64-bit Windows system, it runs as a 32-bit process. IL is compiled to x86 machine code. </li>
<li>If the process runs on an ARM Windows system, it runs as a 32-bit process. IL is compiled to ARM machine code.</li>
</ul>
<p><strong>The difference, then, between “Any CPU 32-bit preferred” and “x86” is
only this: a .NET application compiled to x86 will fail to run on an
ARM Windows system, but an “Any CPU 32-bit preferred” application will
run successfully.</strong></p>
</blockquote> | {
"question_id": 12066638,
"question_date": "2012-08-22T05:13:47.523Z",
"question_score": 231,
"tags": "c#|.net|visual-studio|compilation|cpu-architecture",
"answer_id": 12066861,
"answer_date": "2012-08-22T05:36:20.870Z",
"answer_score": 238
} |
Please answer the following Stack Overflow question:
Title: Concurrent.futures vs Multiprocessing in Python 3
<p>Python 3.2 introduced <a href="http://docs.python.org/3/library/concurrent.futures.html" rel="noreferrer">Concurrent Futures</a>, which appear to be some advanced combination of the older threading and <a href="http://docs.python.org/2/library/multiprocessing.html" rel="noreferrer">multiprocessing</a> modules.</p>
<p>What are the advantages and disadvantages of using this for CPU bound tasks over the older multiprocessing module?</p>
<p><a href="http://eli.thegreenplace.net/2013/01/16/python-paralellizing-cpu-bound-tasks-with-concurrent-futures/" rel="noreferrer">This article</a> suggests they're much easier to work with - is that the case?</p> | <p>I wouldn't call <code>concurrent.futures</code> more "advanced" - it's a <em>simpler</em> interface that works very much the same regardless of whether you use multiple threads or multiple processes as the underlying parallelization gimmick.</p>
<p>So, like virtually all instances of "simpler interface", much the same trade-offs are involved: it has a shallower learning curve, in large part just because there's so much less available <em>to</em> be learned; but, because it offers fewer options, it may eventually frustrate you in ways the richer interfaces won't.</p>
<p>So far as CPU-bound tasks go, that's way too under-specified to say much meaningful. For CPU-bound tasks under CPython, you need multiple processes rather than multiple threads to have any chance of getting a speedup. But how much (if any) of a speedup you get depends on the details of your hardware, your OS, and especially on how much inter-process communication your specific tasks require. Under the covers, all inter-process parallelization gimmicks rely on the same OS primitives - the high-level API you use to get at those isn't a primary factor in bottom-line speed.</p>
<p><strong>Edit: example</strong></p>
<p>Here's the final code shown in the article you referenced, but I'm adding an import statement needed to make it work:</p>
<pre><code>from concurrent.futures import ProcessPoolExecutor
def pool_factorizer_map(nums, nprocs):
# Let the executor divide the work among processes by using 'map'.
with ProcessPoolExecutor(max_workers=nprocs) as executor:
return {num:factors for num, factors in
zip(nums,
executor.map(factorize_naive, nums))}
</code></pre>
<p>Here's exactly the same thing using <code>multiprocessing</code> instead:</p>
<pre><code>import multiprocessing as mp
def mp_factorizer_map(nums, nprocs):
with mp.Pool(nprocs) as pool:
return {num:factors for num, factors in
zip(nums,
pool.map(factorize_naive, nums))}
</code></pre>
<p>Note that the ability to use <code>multiprocessing.Pool</code> objects as context managers was added in Python 3.3.</p>
<p>As for which one is easier to work with, they're essentially identical.</p>
<p>One difference is that <code>Pool</code> supports so many different ways of doing things that you may not realize how easy it <em>can</em> be until you've climbed quite a way up the learning curve.</p>
<p>Again, all those different ways are both a strength and a weakness. They're a strength because the flexibility may be required in some situations. They're a weakness because of "preferably only one obvious way to do it". A project sticking exclusively (if possible) to <code>concurrent.futures</code> will probably be easier to maintain over the long run, due to the lack of gratuitous novelty in how its minimal API can be used.</p> | {
"question_id": 20776189,
"question_date": "2013-12-25T19:41:55.670Z",
"question_score": 231,
"tags": "python|python-3.x|multiprocessing",
"answer_id": 20776444,
"answer_date": "2013-12-25T20:19:20.423Z",
"answer_score": 208
} |
Please answer the following Stack Overflow question:
Title: How can I get `find` to ignore .svn directories?
<p>I often use the <code>find</code> command to search through source code, delete files, whatever. Annoyingly, because Subversion stores duplicates of each file in its <code>.svn/text-base/</code> directories my simple searches end up getting lots of duplicate results. For example, I want to recursively search for <code>uint</code> in multiple <code>messages.h</code> and <code>messages.cpp</code> files:</p>
<pre><code># find -name 'messages.*' -exec grep -Iw uint {} +
./messages.cpp: Log::verbose << "Discarding out of date message: id " << uint(olderMessage.id)
./messages.cpp: Log::verbose << "Added to send queue: " << *message << ": id " << uint(preparedMessage->id)
./messages.cpp: Log::error << "Received message with invalid SHA-1 hash: id " << uint(incomingMessage.id)
./messages.cpp: Log::verbose << "Received " << *message << ": id " << uint(incomingMessage.id)
./messages.cpp: Log::verbose << "Sent message: id " << uint(preparedMessage->id)
./messages.cpp: Log::verbose << "Discarding unsent message: id " << uint(preparedMessage->id)
./messages.cpp: for (uint i = 0; i < 10 && !_stopThreads; ++i) {
./.svn/text-base/messages.cpp.svn-base: Log::verbose << "Discarding out of date message: id " << uint(olderMessage.id)
./.svn/text-base/messages.cpp.svn-base: Log::verbose << "Added to send queue: " << *message << ": id " << uint(preparedMessage->id)
./.svn/text-base/messages.cpp.svn-base: Log::error << "Received message with invalid SHA-1 hash: id " << uint(incomingMessage.id)
./.svn/text-base/messages.cpp.svn-base: Log::verbose << "Received " << *message << ": id " << uint(incomingMessage.id)
./.svn/text-base/messages.cpp.svn-base: Log::verbose << "Sent message: id " << uint(preparedMessage->id)
./.svn/text-base/messages.cpp.svn-base: Log::verbose << "Discarding unsent message: id " << uint(preparedMessage->id)
./.svn/text-base/messages.cpp.svn-base: for (uint i = 0; i < 10 && !_stopThreads; ++i) {
./virus/messages.cpp:void VsMessageProcessor::_progress(const string &fileName, uint scanCount)
./virus/messages.cpp:ProgressMessage::ProgressMessage(const string &fileName, uint scanCount)
./virus/messages.h: void _progress(const std::string &fileName, uint scanCount);
./virus/messages.h: ProgressMessage(const std::string &fileName, uint scanCount);
./virus/messages.h: uint _scanCount;
./virus/.svn/text-base/messages.cpp.svn-base:void VsMessageProcessor::_progress(const string &fileName, uint scanCount)
./virus/.svn/text-base/messages.cpp.svn-base:ProgressMessage::ProgressMessage(const string &fileName, uint scanCount)
./virus/.svn/text-base/messages.h.svn-base: void _progress(const std::string &fileName, uint scanCount);
./virus/.svn/text-base/messages.h.svn-base: ProgressMessage(const std::string &fileName, uint scanCount);
./virus/.svn/text-base/messages.h.svn-base: uint _scanCount;
</code></pre>
<p>How can I tell <code>find</code> to ignore the <code>.svn</code> directories?</p>
<hr>
<p><strong>Update</strong>: If you upgrade your SVN client to <a href="http://subversion.apache.org/docs/release-notes/1.7.html#single-db" rel="noreferrer">version 1.7</a> this is no longer an issue.</p>
<blockquote>
<p>A key feature of the changes introduced in Subversion 1.7 is the centralization of working copy metadata storage into a single location. Instead of a <code>.svn</code> directory in every directory in the working copy, Subversion 1.7 working copies have just one <code>.svn</code> directory—in the root of the working copy. This directory includes (among other things) an SQLite-backed database which contains all of the metadata Subversion needs for that working copy.</p>
</blockquote> | <p>For searching, can I suggest you look at <a href="http://www.betterthangrep.com" rel="noreferrer">ack</a> ? It's a source-code aware <code>find</code>, and as such will automatically ignore many file types, including source code repository info such as the above.</p> | {
"question_id": 2314643,
"question_date": "2010-02-22T22:09:17.913Z",
"question_score": 231,
"tags": "linux|find|bash|grep|svn",
"answer_id": 2314668,
"answer_date": "2010-02-22T22:13:17.953Z",
"answer_score": 67
} |
Please answer the following Stack Overflow question:
Title: See all breakpoints in Visual Studio 2010+
<p>Is there a window in Visual Studio 2010 and newer where I can see all the breakpoints that I have in my project or solution?</p> | <p>Try <strong>Debug</strong> -> <strong>Windows</strong> -> <strong>Breakpoints</strong>.</p> | {
"question_id": 7781977,
"question_date": "2011-10-16T02:33:11.617Z",
"question_score": 231,
"tags": "visual-studio-2010|visual-studio|breakpoints",
"answer_id": 7781988,
"answer_date": "2011-10-16T02:35:31.743Z",
"answer_score": 410
} |
Please answer the following Stack Overflow question:
Title: How do I step out of a loop with Ruby Pry?
<p>I'm using Pry with my Rails application. I set <code>binding.pry</code> inside a loop in my model to try and debug a problem. For example:</p>
<pre><code>(1..100).each do |i|
binding.pry
puts i
end
</code></pre>
<p>When I type <code>quit</code>, it goes to the next iteration and stops again. Is there a way to step out of the loop so I don't have to type <code>quit</code> 100 times?</p>
<p>Currently the only way I know how to get out of it is to use <kbd>CTRL</kbd>+<kbd>C</kbd> and restart the application.</p> | <p>To exit Pry unconditionally, type</p>
<pre><code>exit-program
</code></pre>
<p><strong>Edit from @Nick's comment</strong>: Also works:</p>
<pre><code>!!!
</code></pre> | {
"question_id": 8015531,
"question_date": "2011-11-04T20:47:05.920Z",
"question_score": 231,
"tags": "ruby-on-rails|ruby|loops|exit|pry",
"answer_id": 11227635,
"answer_date": "2012-06-27T13:42:49.413Z",
"answer_score": 465
} |
Please answer the following Stack Overflow question:
Title: Why do Objective-C files use the .m extension?
<p>Since I started learning Objective-C and Cocoa, I've been wondering why they have chosen the extension .m for the implementation files - was it supposed to mean something, or was it just a random letter?</p> | <p>Today most people would refer to them as "method files", but</p>
<blockquote>
<p>"The .m extension originally stood for
"<strong>m</strong>essages" when Objective-C was first
introduced, referring to a central
feature of Objective-C [...]"</p>
</blockquote>
<p>(from the book "<a href="https://rads.stackoverflow.com/amzn/click/com/1430218150" rel="noreferrer" rel="nofollow noreferrer">Learn Objective-C on the Mac</a>" by Mark Dalrymple and Scott Knaster, page 9)</p>
<p><strong>EDIT:</strong> To satisfy an itch I emailed <a href="http://www.virtualschool.edu/cox/" rel="noreferrer">Brad Cox</a>, the inventor of Objective-C, about the question and he answered with this single line: </p>
<blockquote>
<p>"Because .o and .c were taken. Simple
as that."</p>
</blockquote>
<p>Here's the email as visual proof:</p>
<p><img src="https://i.stack.imgur.com/O7pPJ.png" alt="Visual Proof"></p> | {
"question_id": 652186,
"question_date": "2009-03-16T21:17:51.890Z",
"question_score": 231,
"tags": "objective-c|file-extension",
"answer_id": 652266,
"answer_date": "2009-03-16T21:46:30.697Z",
"answer_score": 514
} |
Please answer the following Stack Overflow question:
Title: How to clone a case class instance and change just one field in Scala?
<p>Let's say I have a case class that represents personas, people on different social networks. Instances of that class are fully immutable, and are held in immutable collections, to be eventually modified by an Akka actor.</p>
<p>Now, I have a case class with many fields, and I receive a message that says I must update one of the fields, something like this:</p>
<pre><code>case class Persona(serviceName : String,
serviceId : String,
sentMessages : Set[String])
// Somewhere deep in an actor
val newPersona = Persona(existingPersona.serviceName,
existingPersona.serviceId,
existingPersona.sentMessages + newMessage)
</code></pre>
<p>Notice I have to specify all fields, even though only one changes. Is there a way to clone existingPersona and replace only one field, without specifying all the fields that don't change? Can I write that as a trait and use it for all my case classes?</p>
<p>If Persona was a Map-like instance, it would be easy to do.</p> | <p><code>case class</code>comes with a <code>copy</code> method that is dedicated exactly to this usage:</p>
<pre><code>val newPersona = existingPersona.copy(sentMessages =
existingPersona.sentMessages + newMessage)
</code></pre> | {
"question_id": 7249396,
"question_date": "2011-08-30T20:28:58.723Z",
"question_score": 231,
"tags": "scala",
"answer_id": 7249439,
"answer_date": "2011-08-30T20:32:31.017Z",
"answer_score": 347
} |
Please answer the following Stack Overflow question:
Title: AWS VPC - Internet Gateway vs. NAT
<p>What is an Internet Gateway? What is a NAT Instance? What services do they offer?</p>
<p>Reading AWS VPC documentation, I gather they both map private IP addresses to internet route-able addresses for the outgoing requests and route the incoming responses from the internet to the requester on the subnet. </p>
<p>So what are the differences between them? What scenarios do I use a NAT Instance instead of (or besides) an Internet Gateway?
Are they essentially EC2 instances running some network applications or are they special hardware like a router?</p>
<p>Instead of simply pointing to AWS documentation links, can you please explain these with adding some background on what is public and private subnets so any beginner with limited knowledge of networking can understand these easily?
Also when should I use a NAT Gateway instead of a NAT instance?</p>
<p>P.S. I am new to AWS VPC, so I might be comparing apples to oranges here.</p> | <p><strong>Internet Gateway</strong></p>
<p>An Internet Gateway is a <strong>logical connection between an Amazon VPC and the Internet</strong>. It is <em>not</em> a physical device. Only one can be associated with each VPC. It does <em>not</em> limit the bandwidth of Internet connectivity. (The only limitation on bandwidth is the size of the Amazon EC2 instance, and it applies to all traffic -- internal to the VPC and out to the Internet.)</p>
<p>If a VPC <strong>does not</strong> have an Internet Gateway, then the resources in the VPC <strong>cannot be accessed from the Internet</strong> (unless the traffic flows via a corporate network and VPN/Direct Connect).</p>
<p>A subnet is deemed to be a <strong>Public Subnet</strong> if it has a Route Table that directs traffic to the Internet Gateway.</p>
<p><strong>NAT Instance</strong></p>
<p>A NAT Instance is an Amazon EC2 instance configured to forward traffic to the Internet. It can be launched from an existing AMI, or can be configured via User Data like this:</p>
<pre><code>#!/bin/sh
echo 1 > /proc/sys/net/ipv4/ip_forward
echo 0 > /proc/sys/net/ipv4/conf/eth0/send_redirects
/sbin/iptables -t nat -A POSTROUTING -o eth0 -s 0.0.0.0/0 -j MASQUERADE
/sbin/iptables-save > /etc/sysconfig/iptables
mkdir -p /etc/sysctl.d/
cat <<EOF > /etc/sysctl.d/nat.conf
net.ipv4.ip_forward = 1
net.ipv4.conf.eth0.send_redirects = 0
EOF
</code></pre>
<p>Instances in a private subnet that want to access the Internet can have their Internet-bound traffic forwarded to the NAT Instance via a Route Table configuration. The NAT Instance will then make the request to the Internet (since it is in a Public Subnet) and the response will be forwarded back to the private instance.</p>
<p>Traffic sent to a NAT Instance will typically be sent to an IP address that is not associated with the NAT Instance itself (it will be destined for a server on the Internet). Therefore, it is important to turn off the <strong>Source/Destination Check</strong> option on the NAT Instance otherwise the traffic will be blocked.</p>
<p><strong>NAT Gateway</strong></p>
<p>AWS introduced a <strong>NAT Gateway Service</strong> that can take the place of a NAT Instance. The benefits of using a NAT Gateway service are:</p>
<ul>
<li>It is a fully-managed service -- just create it and it works automatically, including fail-over</li>
<li>It can burst up to 10 Gbps (a NAT Instance is limited to the bandwidth associated with the EC2 instance type)</li>
</ul>
<p>However:</p>
<ul>
<li>Security Groups <strong>cannot</strong> be associated with a NAT Gateway</li>
<li>You'll need one in each AZ since they only operate in a single AZ</li>
</ul> | {
"question_id": 38690012,
"question_date": "2016-08-01T01:55:29.680Z",
"question_score": 231,
"tags": "amazon-web-services|amazon-vpc",
"answer_id": 38691109,
"answer_date": "2016-08-01T04:36:27.857Z",
"answer_score": 253
} |
Please answer the following Stack Overflow question:
Title: How to undo the effect of "set -e" which makes bash exit immediately if any command fails?
<p>After entering <code>set -e</code> in an interactive bash shell, bash will exit immediately if any command exits with non-zero. How can I undo this effect?</p> | <p>With <code>set +e</code>. Yeah, it's backward that you <em>enable</em> shell options with <code>set -</code> and <em>disable</em> them with <code>set +</code>. Historical raisins, donchanow.</p> | {
"question_id": 3517162,
"question_date": "2010-08-18T22:13:37.093Z",
"question_score": 231,
"tags": "bash|exit",
"answer_id": 3517181,
"answer_date": "2010-08-18T22:17:06.007Z",
"answer_score": 358
} |
Please answer the following Stack Overflow question:
Title: What does `:_*` (colon underscore star) do in Scala?
<p>I have the following piece of code from <a href="https://stackoverflow.com/questions/2199040/scala-xml-building-adding-children-to-existing-nodes">this question</a>:</p>
<pre><code>def addChild(n: Node, newChild: Node) = n match {
case Elem(prefix, label, attribs, scope, child @ _*) => Elem(prefix, label, attribs, scope, child ++ newChild : _*)
case _ => error("Can only add children to elements!")
}
</code></pre>
<p>Everything in it is pretty clear, except this piece: <code>child ++ newChild : _*</code></p>
<p>What does it do? </p>
<p>I understand there is <code>Seq[Node]</code> concatenated with another <code>Node</code>, and then? What does <code>: _*</code> do?</p> | <p>It "splats"<sup>1</sup> the sequence.</p>
<p>Look at the constructor signature</p>
<pre><code>new Elem(prefix: String, label: String, attributes: MetaData, scope: NamespaceBinding,
child: Node*)
</code></pre>
<p>which is called as</p>
<pre><code>new Elem(prefix, label, attributes, scope,
child1, child2, ... childN)
</code></pre>
<p>but here there is only a sequence, not <code>child1</code>, <code>child2</code>, etc. so this allows the result sequence to be used as the input to the constructor.</p>
<hr />
<p><sup>1</sup> This doesn't have a cutesy-name in the SLS, but here are the details. The important thing to get is that it changes how Scala binds the arguments to the method with repeated parameters (as denoted with <code>Node*</code> above).</p>
<p>The <strong><code>_*</code> type annotation</strong> is covered in "4.6.2 Repeated Parameters" of the SLS.</p>
<blockquote>
<blockquote>
<p>The last value parameter of a parameter section may be suffixed by “*”, e.g. (..., x:T <em>). The type of such a repeated parameter inside the method is then
the sequence type scala.Seq[T]. Methods with repeated parameters T * take
a variable number of arguments of type T . That is, if a method m with type
(p1 : T1, . . . , pn : Tn,ps : S</em>)U is applied to arguments (e1, . . . , ek) where k >= n, then
m is taken in that application to have type (p1 : T1, . . . , pn : Tn,ps : S, . . . , ps0S)U,
with k ¡ n occurrences of type S where any parameter names beyond ps are
fresh. <em><em>The only exception to this rule is if the last argument is marked to be
a sequence argument via a _</em> type annotation. If m above is applied to arguments (e1, . . . , en,e0 : _</em>), then the type of m in that application is taken to be
(p1 : T1, . . . , pn : Tn,ps :scala.Seq[S])**</p>
</blockquote>
</blockquote> | {
"question_id": 6051302,
"question_date": "2011-05-18T21:35:51.747Z",
"question_score": 231,
"tags": "scala|pattern-matching",
"answer_id": 6051356,
"answer_date": "2011-05-18T21:41:14.987Z",
"answer_score": 170
} |
Please answer the following Stack Overflow question:
Title: Using bitwise OR 0 to floor a number
<p>A colleague of mine stumbled upon a method to floor float numbers using a bitwise or:</p>
<pre><code>var a = 13.6 | 0; //a == 13
</code></pre>
<p>We were talking about it and wondering a few things.</p>
<ul>
<li>How does it work? Our theory was that using such an operator casts the number to an integer, thus removing the fractional part</li>
<li>Does it have any advantages over doing <code>Math.floor</code>? Maybe it's a bit faster? (pun not intended)</li>
<li>Does it have any disadvantages? Maybe it doesn't work in some cases? Clarity is an obvious one, since we had to figure it out, and well, I'm writting this question.</li>
</ul>
<p>Thanks.</p> | <blockquote>
<p>How does it work? Our theory was that using such an operator casts the
number to an integer, thus removing the fractional part</p>
</blockquote>
<p>All bitwise operations except unsigned right shift, <code>>>></code>, work on signed 32-bit integers. So using bitwise operations will convert a float to an integer.</p>
<blockquote>
<p>Does it have any advantages over doing Math.floor? Maybe it's a bit
faster? (pun not intended)</p>
</blockquote>
<p><a href="http://jsperf.com/or-vs-floor/2" rel="noreferrer">http://jsperf.com/or-vs-floor/2</a> seems slightly faster</p>
<blockquote>
<p>Does it have any disadvantages? Maybe it doesn't work in some cases?
Clarity is an obvious one, since we had to figure it out, and well,
I'm writting this question.</p>
</blockquote>
<ul>
<li>Will not pass jsLint. </li>
<li>32-bit signed integers only</li>
<li>Odd Comparative behavior: <code>Math.floor(NaN) === NaN</code>, while <code>(NaN | 0) === 0</code></li>
</ul> | {
"question_id": 7487977,
"question_date": "2011-09-20T15:47:08.357Z",
"question_score": 231,
"tags": "javascript|floating-point|bit-manipulation",
"answer_id": 7488075,
"answer_date": "2011-09-20T15:54:09.027Z",
"answer_score": 186
} |
Please answer the following Stack Overflow question:
Title: Stack vs heap allocation of structs in Go, and how they relate to garbage collection
<p>I'm new to Go, and I'm experiencing a bit of cognitive dissonance between C-style stack-based programming, where automatic variables live on the stack and allocated memory lives on the heap, and Python-style stack-based-programming, where the only thing that lives on the stack are references/pointers to objects on the heap.</p>
<p>As far as I can tell, the two following functions give the same output:</p>
<pre><code>func myFunction() (*MyStructType, error) {
var chunk *MyStructType = new(HeaderChunk)
...
return chunk, nil
}
func myFunction() (*MyStructType, error) {
var chunk MyStructType
...
return &chunk, nil
}
</code></pre>
<p>i.e., allocate a new struct and return it.</p>
<p>If I'd written that in C, the first one would have put an object on the heap and the second would have put it on the stack. The first would return a pointer to the heap, the second would return a pointer to the stack, which would have evaporated by the time the function had returned, which would be a Bad Thing.</p>
<p>If I'd written it in Python (or many other modern languages except C#) example 2 would not have been possible.</p>
<p>I get that Go garbage collects both values, so both of the above forms are fine.</p>
<p>To quote:</p>
<blockquote>
<p>Note that, unlike in C, it's perfectly OK to return the address of a
local variable; the storage associated with the variable survives
after the function returns. In fact, taking the address of a composite
literal allocates a fresh instance each time it is evaluated, so we
can combine these last two lines.</p>
<p><a href="http://golang.org/doc/effective_go.html#functions" rel="nofollow noreferrer">http://golang.org/doc/effective_go.html#functions</a></p>
</blockquote>
<p>But it raises a couple of questions.</p>
<ol>
<li><p>In example 1, the struct is declared on the heap. What about example 2? Is that declared on the stack in the same way it would be in C or does it go on the heap too?</p>
</li>
<li><p>If example 2 is declared on the stack, how does it stay available after the function returns?</p>
</li>
<li><p>If example 2 is actually declared on the heap, how is it that structs are passed by value rather than by reference? What's the point of pointers in this case?</p>
</li>
</ol> | <p>It's worth noting that the words "stack" and "heap" do not appear anywhere in the language spec. Your question is worded with "...is declared on the stack," and "...declared on the heap," but note that Go declaration syntax says nothing about stack or heap.</p>
<p>That technically makes the answer to all of your questions implementation dependent. In actuality of course, there is a stack (per goroutine!) and a heap and some things go on the stack and some on the heap. In some cases the compiler follows rigid rules (like "<code>new</code> always allocates on the heap") and in others the compiler does "escape analysis" to decide if an object can live on the stack or if it must be allocated on the heap.</p>
<p>In your example 2, escape analysis would show the pointer to the struct escaping and so the compiler would have to allocate the struct. I think the current implementation of Go follows a rigid rule in this case however, which is that if the address is taken of any part of a struct, the struct goes on the heap.</p>
<p>For question 3, we risk getting confused about terminology. Everything in Go is passed by value, there is no pass by reference. Here you are returning a pointer value. What's the point of pointers? Consider the following modification of your example:</p>
<pre><code>type MyStructType struct{}
func myFunction1() (*MyStructType, error) {
var chunk *MyStructType = new(MyStructType)
// ...
return chunk, nil
}
func myFunction2() (MyStructType, error) {
var chunk MyStructType
// ...
return chunk, nil
}
type bigStruct struct {
lots [1e6]float64
}
func myFunction3() (bigStruct, error) {
var chunk bigStruct
// ...
return chunk, nil
}
</code></pre>
<p>I modified myFunction2 to return the struct rather than the address of the struct. Compare the assembly output of myFunction1 and myFunction2 now,</p>
<pre><code>--- prog list "myFunction1" ---
0000 (s.go:5) TEXT myFunction1+0(SB),$16-24
0001 (s.go:6) MOVQ $type."".MyStructType+0(SB),(SP)
0002 (s.go:6) CALL ,runtime.new+0(SB)
0003 (s.go:6) MOVQ 8(SP),AX
0004 (s.go:8) MOVQ AX,.noname+0(FP)
0005 (s.go:8) MOVQ $0,.noname+8(FP)
0006 (s.go:8) MOVQ $0,.noname+16(FP)
0007 (s.go:8) RET ,
--- prog list "myFunction2" ---
0008 (s.go:11) TEXT myFunction2+0(SB),$0-16
0009 (s.go:12) LEAQ chunk+0(SP),DI
0010 (s.go:12) MOVQ $0,AX
0011 (s.go:14) LEAQ .noname+0(FP),BX
0012 (s.go:14) LEAQ chunk+0(SP),BX
0013 (s.go:14) MOVQ $0,.noname+0(FP)
0014 (s.go:14) MOVQ $0,.noname+8(FP)
0015 (s.go:14) RET ,
</code></pre>
<p>Don't worry that myFunction1 output here is different than in peterSO's (excellent) answer. We're obviously running different compilers. Otherwise, see that I modfied myFunction2 to return myStructType rather than *myStructType. The call to runtime.new is gone, which in some cases would be a good thing. Hold on though, here's myFunction3,</p>
<pre><code>--- prog list "myFunction3" ---
0016 (s.go:21) TEXT myFunction3+0(SB),$8000000-8000016
0017 (s.go:22) LEAQ chunk+-8000000(SP),DI
0018 (s.go:22) MOVQ $0,AX
0019 (s.go:22) MOVQ $1000000,CX
0020 (s.go:22) REP ,
0021 (s.go:22) STOSQ ,
0022 (s.go:24) LEAQ chunk+-8000000(SP),SI
0023 (s.go:24) LEAQ .noname+0(FP),DI
0024 (s.go:24) MOVQ $1000000,CX
0025 (s.go:24) REP ,
0026 (s.go:24) MOVSQ ,
0027 (s.go:24) MOVQ $0,.noname+8000000(FP)
0028 (s.go:24) MOVQ $0,.noname+8000008(FP)
0029 (s.go:24) RET ,
</code></pre>
<p>Still no call to runtime.new, and yes it really works to return an 8MB object by value. It works, but you usually wouldn't want to. The point of a pointer here would be to avoid pushing around 8MB objects.</p> | {
"question_id": 10866195,
"question_date": "2012-06-02T21:46:14.180Z",
"question_score": 231,
"tags": "go|heap-memory|stack-memory",
"answer_id": 10866871,
"answer_date": "2012-06-03T00:01:15.370Z",
"answer_score": 228
} |
Please answer the following Stack Overflow question:
Title: EINVRES Request to https://bower.herokuapp.com/packages/ failed with 502
<p>Bower install fails with 502 - Bad Gateway when downloading bower packages.</p>
<p>For example bower install for ember library gives following response in command line.</p>
<blockquote>
<p>EINVRES Request to <a href="https://bower.herokuapp.com/packages/ember" rel="noreferrer">https://bower.herokuapp.com/packages/ember</a> failed
with 502</p>
</blockquote>
<p>When <a href="http://bower.herokuapp.com/" rel="noreferrer">http://bower.herokuapp.com/</a> is accessed directly from URL it gives the following message.</p>
<blockquote>
<p>This Bower version is deprecated. Please update it: npm install -g
bower. The new registry address is <a href="https://registry.bower.io" rel="noreferrer">https://registry.bower.io</a></p>
</blockquote> | <p>Bower is deprecating their registry hosted with Heroku. <a href="http://bower.herokuapp.com/" rel="noreferrer">http://bower.herokuapp.com/</a> Will not be accessible anymore or it might be down intermittently, therefore, forcing users to a new registry.</p>
<p>Users working on old bower versions can update the <strong><em>.bowerrc</em></strong> file with the following data.</p>
<pre><code>{
"registry": "https://registry.bower.io"
}
</code></pre>
<p><strong><em>.bowerrc</em></strong> file can be located at the same folder where <em>bower.json</em> and <em>bower_components</em> folder is located. If it is not present already, you can make one.</p>
<p>For references check the below links</p>
<ul>
<li><a href="https://twitter.com/bower/status/918073147789889536" rel="noreferrer">https://twitter.com/bower/status/918073147789889536</a></li>
<li><a href="https://gist.github.com/sheerun/c04d856a7a368bad2896ff0c4958cb00" rel="noreferrer">https://gist.github.com/sheerun/c04d856a7a368bad2896ff0c4958cb00</a></li>
</ul> | {
"question_id": 51020317,
"question_date": "2018-06-25T09:34:50.253Z",
"question_score": 231,
"tags": "javascript|bower",
"answer_id": 51020318,
"answer_date": "2018-06-25T09:34:50.253Z",
"answer_score": 452
} |
Please answer the following Stack Overflow question:
Title: Would it be beneficial to begin using instancetype instead of id?
<p>Clang adds a keyword <a href="http://clang.llvm.org/docs/LanguageExtensions.html#objc_instancetype"><code>instancetype</code></a> that, as far as I can see, replaces <code>id</code> as a return type in <code>-alloc</code> and <code>init</code>. </p>
<p>Is there a benefit to using <code>instancetype</code> instead of <code>id</code>?</p> | <p>There definitely is a benefit. When you use 'id', you get essentially no type checking at all. With instancetype, the compiler and IDE know what type of thing is being returned, and can check your code better and autocomplete better.</p>
<p>Only use it where it makes sense of course (i.e. a method that is returning an instance of that class); id is still useful.</p> | {
"question_id": 8972221,
"question_date": "2012-01-23T13:15:17.110Z",
"question_score": 231,
"tags": "objective-c|instancetype",
"answer_id": 8976920,
"answer_date": "2012-01-23T18:47:01.083Z",
"answer_score": 200
} |
Please answer the following Stack Overflow question:
Title: What does [nyae] mean in Zsh?
<p>I run the following command unsuccessfully</p>
<pre><code>dir
</code></pre>
<p>and I get</p>
<pre><code>zsh: correct 'dir' to 'gdir' [nyae]?
</code></pre>
<p><strong>What does [nyae] mean in Zsh?</strong></p> | <p><code>zsh</code> has a powerful correction mechanism. If you type a command in the wrong way it suggests corrections.
What happend here is that <code>dir</code> is an unknown command and <code>zsh</code> suggests <code>gdir</code>, while maybe <code>ls</code> was what you wanted.</p>
<ol>
<li>If you want to execute <code>gdir</code> hit <code>y</code> (yes)</li>
<li>If you want to try to execute <code>dir</code> anyway hit <code>n</code> (no)</li>
<li>If you want to execute completely different spelt command like <code>ls</code> hit <code>a</code> (abort) and type your command</li>
<li>If you want to execute a similar spelt commant like <code>udir</code> hit <code>e</code> (edit) and edit your command.</li>
</ol> | {
"question_id": 800182,
"question_date": "2009-04-28T22:54:28.023Z",
"question_score": 231,
"tags": "zsh",
"answer_id": 800196,
"answer_date": "2009-04-28T22:59:09.840Z",
"answer_score": 307
} |
Please answer the following Stack Overflow question:
Title: Why would introducing useless MOV instructions speed up a tight loop in x86_64 assembly?
<p><strong>Background:</strong></p>
<p>While optimizing some <a href="http://en.wikipedia.org/wiki/Pascal_%28programming_language%29">Pascal</a> code with embedded assembly language, I noticed an unnecessary <code>MOV</code> instruction, and removed it.</p>
<p>To my surprise, removing the un-necessary instruction caused my program to <em>slow down</em>.</p>
<p>I found that <strong>adding arbitrary, useless <code>MOV</code> instructions increased performance</strong> even further.</p>
<p>The effect is erratic, and changes based on execution order: <strong>the same junk instructions transposed</strong> up or down by a single line <strong>produce a slowdown</strong>.</p>
<p>I understand that the CPU does all kinds of optimizations and streamlining, but, this seems more like black magic.</p>
<p><strong>The data:</strong></p>
<p>A version of my code conditionally compiles <strong>three junk operations</strong> in the middle of a loop that runs <code>2**20==1048576</code> times. (The surrounding program just calculates <a href="http://en.wikipedia.org/wiki/SHA-2">SHA-256</a> hashes).</p>
<p>The results on my rather old machine (Intel(R) Core(TM)2 CPU 6400 @ 2.13 GHz):</p>
<pre><code>avg time (ms) with -dJUNKOPS: 1822.84 ms
avg time (ms) without: 1836.44 ms
</code></pre>
<p>The programs were run 25 times in a loop, with the run order changing randomly each time.</p>
<p><strong>Excerpt:</strong></p>
<pre><code>{$asmmode intel}
procedure example_junkop_in_sha256;
var s1, t2 : uint32;
begin
// Here are parts of the SHA-256 algorithm, in Pascal:
// s0 {r10d} := ror(a, 2) xor ror(a, 13) xor ror(a, 22)
// s1 {r11d} := ror(e, 6) xor ror(e, 11) xor ror(e, 25)
// Here is how I translated them (side by side to show symmetry):
asm
MOV r8d, a ; MOV r9d, e
ROR r8d, 2 ; ROR r9d, 6
MOV r10d, r8d ; MOV r11d, r9d
ROR r8d, 11 {13 total} ; ROR r9d, 5 {11 total}
XOR r10d, r8d ; XOR r11d, r9d
ROR r8d, 9 {22 total} ; ROR r9d, 14 {25 total}
XOR r10d, r8d ; XOR r11d, r9d
// Here is the extraneous operation that I removed, causing a speedup
// s1 is the uint32 variable declared at the start of the Pascal code.
//
// I had cleaned up the code, so I no longer needed this variable, and
// could just leave the value sitting in the r11d register until I needed
// it again later.
//
// Since copying to RAM seemed like a waste, I removed the instruction,
// only to discover that the code ran slower without it.
{$IFDEF JUNKOPS}
MOV s1, r11d
{$ENDIF}
// The next part of the code just moves on to another part of SHA-256,
// maj { r12d } := (a and b) xor (a and c) xor (b and c)
mov r8d, a
mov r9d, b
mov r13d, r9d // Set aside a copy of b
and r9d, r8d
mov r12d, c
and r8d, r12d { a and c }
xor r9d, r8d
and r12d, r13d { c and b }
xor r12d, r9d
// Copying the calculated value to the same s1 variable is another speedup.
// As far as I can tell, it doesn't actually matter what register is copied,
// but moving this line up or down makes a huge difference.
{$IFDEF JUNKOPS}
MOV s1, r9d // after mov r12d, c
{$ENDIF}
// And here is where the two calculated values above are actually used:
// T2 {r12d} := S0 {r10d} + Maj {r12d};
ADD r12d, r10d
MOV T2, r12d
end
end;
</code></pre>
<p><strong>Try it yourself:</strong></p>
<p>The code is online <a href="https://github.com/tangentstorm/coinops/tree/junkops">at GitHub</a> if you want to try it out yourself.</p>
<p><strong>My questions:</strong></p>
<ul>
<li>Why would uselessly copying a register's contents to <a href="http://en.wikipedia.org/wiki/Random-access_memory">RAM</a> ever increase performance?</li>
<li>Why would the same useless instruction provide a speedup on some lines, and a slowdown on others?</li>
<li>Is this behavior something that could be exploited predictably by a compiler?</li>
</ul> | <p>The most likely cause of the speed improvement is that:</p>
<ul>
<li>inserting a MOV shifts the subsequent instructions to different memory addresses</li>
<li>one of those moved instructions was an important conditional branch</li>
<li>that branch was being incorrectly predicted due to aliasing in the branch prediction table</li>
<li>moving the branch eliminated the alias and allowed the branch to be predicted correctly</li>
</ul>
<p>Your Core2 doesn't keep a separate history record for each conditional jump. Instead it keeps a shared history of all conditional jumps. One disadvantage of <a href="http://en.wikipedia.org/wiki/Branch_predictor#Global_branch_prediction" rel="noreferrer">global branch prediction</a> is that the history is diluted by irrelevant information if the different conditional jumps are uncorrelated.</p>
<p>This little <a href="http://www.ece.unm.edu/~jimp/611/slides/chap4_5.html" rel="noreferrer">branch prediction tutorial</a> shows how branch prediction buffers work. The cache buffer is indexed by the lower portion of the address of the branch instruction. This works well unless two important uncorrelated branches share the same lower bits. In that case, you end-up with aliasing which causes many mispredicted branches (which stalls the instruction pipeline and slowing your program).</p>
<p>If you want to understand how branch mispredictions affect performance, take a look at this excellent answer: <a href="https://stackoverflow.com/a/11227902/1001643">https://stackoverflow.com/a/11227902/1001643</a></p>
<p>Compilers typically don't have enough information to know which branches will alias and whether those aliases will be significant. However, that information can be determined at runtime with tools such as <a href="http://valgrind.org/docs/manual/cg-manual.html" rel="noreferrer">Cachegrind</a> and <a href="http://software.intel.com/en-us/forums/topic/392268" rel="noreferrer">VTune</a>.</p> | {
"question_id": 17896714,
"question_date": "2013-07-27T10:25:10.273Z",
"question_score": 231,
"tags": "performance|optimization|assembly|x86-64|freepascal",
"answer_id": 17906589,
"answer_date": "2013-07-28T08:52:41.047Z",
"answer_score": 151
} |
Please answer the following Stack Overflow question:
Title: Disable ALL CAPS menu items in Visual Studio 2013
<p>In Visual Studio 2013, Microsoft again presents the menu in UPPERCASE as the default. </p>
<p>Can these be modified to be Sentence Case?</p> | <p>Yes - in the new <strong>Visual Studio 2013</strong> (as in VS 2012), MS reinforced their design decision to make ALL CAPS MENU ITEMS the default. The methods for reverting the menu style are almost the same methods used for Visual Studio 2012, <a href="https://stackoverflow.com/questions/10859173/how-to-disable-all-caps-menu-titles-in-visual-studio-2012-rc">which has been discussed before</a>.
<hr>
<strong>Update</strong> (after Visual Studio 2013 Update 4)</p>
<p>As of Visual Studio 2013 Update 4 you can go into <em>Tools > Options > Environment</em><br>
and uncheck <em>Turn off upper case in the menu bar</em>
<img src="https://i.stack.imgur.com/r3cn4.png" alt="screenshot of the menu"></p>
<p><hr>
<strong>Before</strong> Visual Studio 2013 Update 4:</p>
<p>You need to create a specific registry key if you want "old-style" menus back.
<hr />
<strong>First Variant</strong>: Since <em>Package Manager Console</em> is <a href="http://technet.microsoft.com/en-us/scriptcenter/powershell.aspx" rel="noreferrer">Powershell</a>, select menu options <strong>TOOLS</strong> / <strong>Library Package Manager</strong> / <strong>Package Manager Console</strong> and enter and run</p>
<p><code>Set-ItemProperty -Path HKCU:\Software\Microsoft\VisualStudio\12.0\General -Name SuppressUppercaseConversion -Type DWord -Value 1</code>
(as a single line).
<hr />
<strong>Second Variant</strong>: Open up a Command Prompt (<kbd>win</kbd>+<kbd>r</kbd>, <code>cmd</code>, <kbd>enter</kbd>) and enter and run</p>
<p><code>REG ADD HKCU\Software\Microsoft\VisualStudio\12.0\General /v SuppressUppercaseConversion /t REG_DWORD /d 1</code>
(as a single line).
<hr />
<strong>Third Variant</strong>:
Change registry values by hand, open <code>regedit</code> and navigate to</p>
<pre><code>HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\12.0\General
</code></pre>
<p>then, create (right click):</p>
<pre><code> DWORD value
</code></pre>
<p>with the content of</p>
<pre><code> SuppressUppercaseConversion
</code></pre>
<p>and set it to</p>
<pre><code> 1
</code></pre>
<p>Close regedit.exe and you're done.</p>
<hr />
<p><strong>Fourth Variant</strong>: At least one VS Extension (<strong><a href="http://visualstudiogallery.msdn.microsoft.com/c6d1c265-7007-405c-a68b-5606af238ece" rel="noreferrer">VSCommands for Visual Studio 2013</a></strong>) has been published that enables you (among other things) <strong>to switch menu style via config menu</strong> from within VS 2013.</p>
<p>You may also set it to <strong>all-lower-case</strong> items (which is, imho, nice):
<img src="https://i.stack.imgur.com/dKoS2.png" alt="enter image description here"></p>
<p>switch to <strong>Sentence Case</strong> (subtly different from what you get with SuppressUppercaseConversion: the SQL menu gets renamed to Sql)
<img src="https://i.stack.imgur.com/7eO9H.png" alt="enter image description here"></p>
<p>or <strong>hide it completely</strong> (and have it appear on ALT key press or mouse over)
<img src="https://i.stack.imgur.com/oeHrI.png" alt="enter image description here"></p> | {
"question_id": 17413001,
"question_date": "2013-07-01T20:23:07.090Z",
"question_score": 231,
"tags": "visual-studio-2013",
"answer_id": 17413002,
"answer_date": "2013-07-01T20:23:07.090Z",
"answer_score": 368
} |
Please answer the following Stack Overflow question:
Title: xkcd style graphs in MATLAB
<p><img src="https://i.stack.imgur.com/FPz54.png" alt="xkcd-style graph" /></p>
<p>So talented people have figured out how to make <a href="http://en.wikipedia.org/wiki/Xkcd" rel="noreferrer">xkcd</a> style graphs <a href="https://mathematica.stackexchange.com/questions/11350/xkcd-style-graphs">in Mathematica</a>, <a href="https://tex.stackexchange.com/questions/74878/create-xkcd-style-diagram-in-tex">in LaTeX</a>, <a href="http://nbviewer.ipython.org/3835181/" rel="noreferrer">in Python</a> and <a href="https://stackoverflow.com/questions/12675147/xkcd-style-graphs-in-r">in R</a> already.</p>
<p>How can one use MATLAB to produce a plot that looks like the one above?</p>
<h3>What I have tried</h3>
<p>I created wiggly lines, but I couldn't get wiggly axes. The only solution I thought of was to overwrite them with wiggly lines, but I want to be able to change the actual axes. I also could not get the Humor font to work, the code bit used was:</p>
<pre><code> annotation('textbox',[left+left/8 top+0.65*top 0.05525 0.065],...
'String',{'EMBARRASSMENT'},...
'FontSize',24,...
'FontName','Humor',...
'FitBoxToText','off',...
'LineStyle','none');
</code></pre>
<p>For the wiggly line, I experimented with adding a small random noise and smoothing:</p>
<pre><code> smooth(0.05*randn(size(x)),10)
</code></pre>
<p>But I couldn't make the white background the appears around them when they intersect...</p> | <p>I see two ways to solve this: The first way is to add some jitter to the x/y coordinates of the plot features. This has the advantage that you can easily modify a plot, but you have to draw the axes yourself if you want to have them xkcdyfied (see <a href="https://stackoverflow.com/a/12711092/232610">@Rody Oldenhuis' solution</a>). The second way is to create a non-jittery plot, and use <code>imtransform</code> to apply a random distortion to the image. This has the advantage that you can use it with any plot, but you will end up with an image, not an editable plot.</p>
<p>I'll show #2 first, and my attempt at #1 below (if you like #1 better, look at <a href="https://stackoverflow.com/a/12711092/232610">Rody's solution</a>!).</p>
<p><img src="https://i.stack.imgur.com/s6hts.png" alt="enter image description here"></p>
<p>This solution relies on two key functions: <a href="http://www.mathworks.com/matlabcentral/fileexchange/23629" rel="noreferrer">EXPORT_FIG</a> from the file exchange to get an anti-aliased screenshot, and <a href="http://www.mathworks.com/help/images/ref/imtransform.html" rel="noreferrer">IMTRANSFORM</a> to get a transformation.</p>
<pre><code>%# define plot data
x = 1:0.1:10;
y1 = sin(x).*exp(-x/3) + 3;
y2 = 3*exp(-(x-7).^2/2) + 1;
%# plot
fh = figure('color','w');
hold on
plot(x,y1,'b','lineWidth',3);
plot(x,y2,'w','lineWidth',7);
plot(x,y2,'r','lineWidth',3);
xlim([0.95 10])
ylim([0 5])
set(gca,'fontName','Comic Sans MS','fontSize',18,'lineWidth',3,'box','off')
%# add an annotation
annotation(fh,'textarrow',[0.4 0.55],[0.8 0.65],...
'string',sprintf('text%shere',char(10)),'headStyle','none','lineWidth',1.5,...
'fontName','Comic Sans MS','fontSize',14,'verticalAlignment','middle','horizontalAlignment','left')
%# capture with export_fig
im = export_fig('-nocrop',fh);
%# add a bit of border to avoid black edges
im = padarray(im,[15 15 0],255);
%# make distortion grid
sfc = size(im);
[yy,xx]=ndgrid(1:7:sfc(1),1:7:sfc(2));
pts = [xx(:),yy(:)];
tf = cp2tform(pts+randn(size(pts)),pts,'lwm',12);
w = warning;
warning off images:inv_lwm:cannotEvaluateTransfAtSomeOutputLocations
imt = imtransform(im,tf);
warning(w)
%# remove padding
imt = imt(16:end-15,16:end-15,:);
figure('color','w')
imshow(imt)
</code></pre>
<hr>
<p>Here's my initial attempt at jittering</p>
<p><img src="https://i.stack.imgur.com/tFnPs.png" alt="enter image description here"></p>
<pre><code>%# define plot data
x = 1:0.1:10;
y1 = sin(x).*exp(-x/3) + 3;
y2 = 3*exp(-(x-7).^2/2) + 1;
%# jitter
x = x+randn(size(x))*0.01;
y1 = y1+randn(size(x))*0.01;
y2 = y2+randn(size(x))*0.01;
%# plot
figure('color','w')
hold on
plot(x,y1,'b','lineWidth',3);
plot(x,y2,'w','lineWidth',7);
plot(x,y2,'r','lineWidth',3);
xlim([0.95 10])
ylim([0 5])
set(gca,'fontName','Comic Sans MS','fontSize',18,'lineWidth',3,'box','off')
</code></pre> | {
"question_id": 12701841,
"question_date": "2012-10-03T04:19:01.680Z",
"question_score": 231,
"tags": "matlab|plot",
"answer_id": 12709481,
"answer_date": "2012-10-03T13:25:19.543Z",
"answer_score": 123
} |
Please answer the following Stack Overflow question:
Title: How to get a table cell value using jQuery?
<p>I am trying to work out how to get the value of table cell for each row using jQuery.</p>
<p>My table looks like this:</p>
<pre><code><table id="mytable">
<tr>
<th>Customer Id</th>
<th>Result</th>
</tr>
<tr>
<td>123</td>
<td></td>
</tr>
<tr>
<td>456</td>
<td></td>
</tr>
<tr>
<td>789</td>
<td></td>
</tr>
</table>
</code></pre>
<p>I basically want to loop through the table, and get the value of the <code>Customer Id</code> column for each row.</p>
<p>In the code below I have worked out that I need to do this to get it looping through each row, but I'm not sure how to get the value of the first cell in the row.</p>
<pre><code>$('#mytable tr').each(function() {
var cutomerId =
}
</code></pre> | <p>If you can, it might be worth using a class attribute on the TD containing the customer ID so you can write:</p>
<pre><code>$('#mytable tr').each(function() {
var customerId = $(this).find(".customerIDCell").html();
});
</code></pre>
<p>Essentially this is the same as the other solutions (possibly because I copy-pasted), but has the advantage that you won't need to change the structure of your code if you move around the columns, or even put the customer ID into a <code><span></code>, provided you keep the class attribute with it.</p>
<p>By the way, I think you could do it in one selector:</p>
<pre><code>$('#mytable .customerIDCell').each(function() {
alert($(this).html());
});
</code></pre>
<p>If that makes things easier.</p> | {
"question_id": 376081,
"question_date": "2008-12-17T21:25:38.953Z",
"question_score": 230,
"tags": "jquery",
"answer_id": 376116,
"answer_date": "2008-12-17T21:39:13.683Z",
"answer_score": 333
} |
Please answer the following Stack Overflow question:
Title: The multi-part identifier could not be bound
<p>I've seen similar errors on SO, but I don't find a solution for my problem.
I have a SQL query like:</p>
<pre><code>SELECT DISTINCT
a.maxa ,
b.mahuyen ,
a.tenxa ,
b.tenhuyen ,
ISNULL(dkcd.tong, 0) AS tongdkcd
FROM phuongxa a ,
quanhuyen b
LEFT OUTER JOIN ( SELECT maxa ,
COUNT(*) AS tong
FROM khaosat
WHERE CONVERT(DATETIME, ngaylap, 103) BETWEEN 'Sep 1 2011'
AND
'Sep 5 2011'
GROUP BY maxa
) AS dkcd ON dkcd.maxa = a.maxa
WHERE a.maxa <> '99'
AND LEFT(a.maxa, 2) = b.mahuyen
ORDER BY maxa;
</code></pre>
<p>When I execute this query, the error result is:
<strong>The multi-part identifier "a.maxa" could not be bound.</strong> Why?
<br>
P/s: if i divide the query into 2 individual query, it run ok.</p>
<pre><code>SELECT DISTINCT
a.maxa ,
b.mahuyen ,
a.tenxa ,
b.tenhuyen
FROM phuongxa a ,
quanhuyen b
WHERE a.maxa <> '99'
AND LEFT(a.maxa, 2) = b.mahuyen
ORDER BY maxa;
</code></pre>
<p>and</p>
<pre><code>SELECT maxa ,
COUNT(*) AS tong
FROM khaosat
WHERE CONVERT(DATETIME, ngaylap, 103) BETWEEN 'Sep 1 2011'
AND 'Sep 5 2011'
GROUP BY maxa;
</code></pre> | <p>You are mixing implicit joins with explicit joins. That is allowed, but you need to be aware of how to do that properly.</p>
<p>The thing is, explicit joins (the ones that are implemented using the <code>JOIN</code> keyword) take precedence over implicit ones (the 'comma' joins, where the join condition is specified in the <code>WHERE</code> clause).</p>
<p>Here's an outline of your query:</p>
<pre><code>SELECT
…
FROM a, b LEFT JOIN dkcd ON …
WHERE …
</code></pre>
<p>You are probably expecting it to behave like this:</p>
<pre><code>SELECT
…
FROM (a, b) LEFT JOIN dkcd ON …
WHERE …
</code></pre>
<p>that is, the combination of tables <code>a</code> and <code>b</code> is joined with the table <code>dkcd</code>. In fact, what's happening is</p>
<pre><code>SELECT
…
FROM a, (b LEFT JOIN dkcd ON …)
WHERE …
</code></pre>
<p>that is, as you may already have understood, <code>dkcd</code> is joined specifically against <code>b</code> and only <code>b</code>, then the result of the join is combined with <code>a</code> and filtered further with the <code>WHERE</code> clause. In this case, any reference to <code>a</code> in the <code>ON</code> clause is invalid, <code>a</code> is unknown at that point. That is why you are getting the error message.</p>
<p>If I were you, I would probably try to rewrite this query, and one possible solution might be:</p>
<pre><code>SELECT DISTINCT
a.maxa,
b.mahuyen,
a.tenxa,
b.tenhuyen,
ISNULL(dkcd.tong, 0) AS tongdkcd
FROM phuongxa a
INNER JOIN quanhuyen b ON LEFT(a.maxa, 2) = b.mahuyen
LEFT OUTER JOIN (
SELECT
maxa,
COUNT(*) AS tong
FROM khaosat
WHERE CONVERT(datetime, ngaylap, 103) BETWEEN 'Sep 1 2011' AND 'Sep 5 2011'
GROUP BY maxa
) AS dkcd ON dkcd.maxa = a.maxa
WHERE a.maxa <> '99'
ORDER BY a.maxa
</code></pre>
<p>Here the tables <code>a</code> and <code>b</code> are joined first, then the result is joined to <code>dkcd</code>. Basically, this is the same query as yours, only using a different syntax for one of the joins, which makes a great difference: the reference <code>a.maxa</code> in the <code>dkcd</code>'s join condition is now absolutely valid.</p>
<p>As @Aaron Bertrand has correctly noted, you should probably qualify <code>maxa</code> with a specific alias, probably <code>a</code>, in the <code>ORDER BY</code> clause.</p> | {
"question_id": 7314134,
"question_date": "2011-09-06T01:29:40.790Z",
"question_score": 230,
"tags": "sql|sql-server|sql-server-2005",
"answer_id": 7314936,
"answer_date": "2011-09-06T04:28:22.823Z",
"answer_score": 263
} |
Please answer the following Stack Overflow question:
Title: How to check a string for specific characters?
<p>How can I check if a string has several specific characters in it using Python 2?</p>
<p>For example, given the following string:</p>
<blockquote>
<p>The criminals stole $1,000,000 in jewels.</p>
</blockquote>
<p>How do I detect if it has dollar signs ("$"), commas (","), and numbers?</p> | <p>Assuming your string is <code>s</code>:</p>
<pre><code>'$' in s # found
'$' not in s # not found
# original answer given, but less Pythonic than the above...
s.find('$')==-1 # not found
s.find('$')!=-1 # found
</code></pre>
<p>And so on for other characters.</p>
<p>... or</p>
<pre><code>pattern = re.compile(r'\d\$,')
if pattern.findall(s):
print('Found')
else
print('Not found')
</code></pre>
<p>... or</p>
<pre><code>chars = set('0123456789$,')
if any((c in chars) for c in s):
print('Found')
else:
print('Not Found')
</code></pre>
<p>[Edit: added the <code>'$' in s</code> answers]</p> | {
"question_id": 5188792,
"question_date": "2011-03-04T01:47:24.787Z",
"question_score": 230,
"tags": "python|string",
"answer_id": 5188909,
"answer_date": "2011-03-04T02:07:17.497Z",
"answer_score": 320
} |
Please answer the following Stack Overflow question:
Title: Disable Scrolling on Body
<p>I would like to disable scrolling on the HTML <code>body</code> completely. I have tried the following options:</p>
<ul>
<li><p><code>overflow: hidden;</code> (not working, did not disable scrolling, it just hid the scrollbar)</p></li>
<li><p><code>position: fixed;</code> (this worked, but it scrolled completely to the top, which is unacceptable for this specific application)</p></li>
</ul>
<p>I was unable to find any alternatives to these two options, are there any more?</p> | <p>Set <code>height</code> and <code>overflow</code>:</p>
<pre><code>html, body {margin: 0; height: 100%; overflow: hidden}
</code></pre>
<p><a href="http://jsfiddle.net/q99hvawt/">http://jsfiddle.net/q99hvawt/</a></p> | {
"question_id": 28411499,
"question_date": "2015-02-09T14:00:28.203Z",
"question_score": 230,
"tags": "html|css|scroll",
"answer_id": 28411556,
"answer_date": "2015-02-09T14:03:12.260Z",
"answer_score": 382
} |
Please answer the following Stack Overflow question:
Title: Deserialize JSON with C#
<p>I'm trying to deserialize a Facebook friend's <a href="http://en.wikipedia.org/wiki/Facebook_Platform#Graph_API" rel="noreferrer">Graph API</a> call into a list of objects. The JSON object looks like:</p>
<pre><code>{"data":[{"id":"518523721","name":"ftyft"},
{"id":"527032438","name":"ftyftyf"},
{"id":"527572047","name":"ftgft"},
{"id":"531141884","name":"ftftft"},
{"id":"532652067","name"...
List<EFacebook> facebooks = new JavaScriptSerializer().Deserialize<List<EFacebook>>(result);
</code></pre>
<p>It's not working, because the primitive object is invalid. How can I deserialize this?</p> | <p>You need to create a structure like this:</p>
<pre><code>public class Friends
{
public List<FacebookFriend> data {get; set;}
}
public class FacebookFriend
{
public string id {get; set;}
public string name {get; set;}
}
</code></pre>
<p>Then you should be able to do:</p>
<pre><code>Friends facebookFriends = new JavaScriptSerializer().Deserialize<Friends>(result);
</code></pre>
<p>The names of my classes are just an example. You should use proper names.</p>
<p>Adding a sample test:</p>
<pre><code>string json =
@"{""data"":[{""id"":""518523721"",""name"":""ftyft""}, {""id"":""527032438"",""name"":""ftyftyf""}, {""id"":""527572047"",""name"":""ftgft""}, {""id"":""531141884"",""name"":""ftftft""}]}";
Friends facebookFriends = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Friends>(json);
foreach(var item in facebookFriends.data)
{
Console.WriteLine("id: {0}, name: {1}", item.id, item.name);
}
</code></pre>
<p>Produces:</p>
<pre><code>id: 518523721, name: ftyft
id: 527032438, name: ftyftyf
id: 527572047, name: ftgft
id: 531141884, name: ftftft
</code></pre> | {
"question_id": 7895105,
"question_date": "2011-10-25T20:00:12.403Z",
"question_score": 230,
"tags": "c#|json",
"answer_id": 7895168,
"answer_date": "2011-10-25T20:04:50.753Z",
"answer_score": 289
} |
Please answer the following Stack Overflow question:
Title: Serializing a list to JSON
<p>I have an object model that looks like this:</p>
<pre><code>public MyObjectInJson
{
public long ObjectID {get;set;}
public string ObjectInJson {get;set;}
}
</code></pre>
<p>The property <code>ObjectInJson</code> is an already serialized version an object that contains nested lists. For the moment, I'm serializing the list of <code>MyObjectInJson</code> manually like this:</p>
<pre><code>StringBuilder TheListBuilder = new StringBuilder();
TheListBuilder.Append("[");
int TheCounter = 0;
foreach (MyObjectInJson TheObject in TheList)
{
TheCounter++;
TheListBuilder.Append(TheObject.ObjectInJson);
if (TheCounter != TheList.Count())
{
TheListBuilder.Append(",");
}
}
TheListBuilder.Append("]");
return TheListBuilder.ToString();
</code></pre>
<p>I wonder if I can replace this sort of dangerous code with <code>JavascriptSerializer</code> and get the same results.
How would I do this?</p> | <h2>If using .Net Core 3.0 or later;</h2>
<p>Default to using the built in <code>System.Text.Json</code> parser implementation.</p>
<p>e.g.</p>
<pre><code>using System.Text.Json;
var json = JsonSerializer.Serialize(aList);
</code></pre>
<p>alternatively, other, less mainstream options are available like <a href="https://github.com/neuecc/Utf8Json" rel="noreferrer">Utf8Json</a> parser and <a href="https://github.com/kevin-montrose/Jil" rel="noreferrer">Jil</a>: These may offer <a href="https://michaelscodingspot.com/the-battle-of-c-to-json-serializers-in-net-core-3/" rel="noreferrer">superior performance</a>, if you really need it but, you will need to install their respective packages.</p>
<h2>If stuck using .Net Core 2.2 or earlier;</h2>
<p>Default to using Newtonsoft JSON.Net as your first choice JSON Parser.</p>
<p>e.g.</p>
<pre><code>using Newtonsoft.Json;
var json = JsonConvert.SerializeObject(aList);
</code></pre>
<p>you may need to install the package first.</p>
<pre><code>PM> Install-Package Newtonsoft.Json
</code></pre>
<p>For more details <a href="https://stackoverflow.com/a/15239542/659190">see and upvote the answer that is the source of this information</a>.</p>
<h2>For reference only, this was the original answer, many years ago;</h2>
<pre><code>// you need to reference System.Web.Extensions
using System.Web.Script.Serialization;
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(aList);
</code></pre> | {
"question_id": 9110724,
"question_date": "2012-02-02T10:28:39.777Z",
"question_score": 230,
"tags": "c#|asp.net|json",
"answer_id": 9110986,
"answer_date": "2012-02-02T10:46:27.437Z",
"answer_score": 429
} |
Please answer the following Stack Overflow question:
Title: Import Maven dependencies in IntelliJ IDEA
<p>I just imported a project from subversion to IntelliJ IDEA 11 - it's a maven project. But I have a problem in maven library dependencies so that I can't include all maven dependencies automatically - IDEA shows dependency errors only when I open that class/ Thats what I get here:</p>
<p><img src="https://i.stack.imgur.com/v5K5p.png" alt="enter image description here" /></p>
<p>So I want all dependencies to be added automatically - is that possible or do I have to go through all class files to identify and add maven dependencies?!</p>
<p>UPDATE: After doing some modifications I found how to resolve my problem in some way. Thats what I did:
<img src="https://i.stack.imgur.com/KslcB.png" alt="enter image description here" /></p>
<p>but I think logically it will not include and check new dependencies ahead?!... Is there any settings area for this in intelliJ - auto export dependencies to classpath?</p> | <p>IntelliJ should download and add all your dependencies to the project's classpath automatically as long as your POM is compliant and all the dependencies are available.</p>
<p>When importing Maven projects into IntelliJ an information box usually comes up asking you if you want to configure <em>Auto-Import</em> for Maven projects. That means that if you make any changes to your POM those changes will be loaded automatically.</p>
<p>You can enable such feature going to File > Settings > Maven > Importing, there is a checkbox that says "Import Maven projects automatically".</p>
<p>If that doesn't help, then I would suggest to make a full clean-up and start again:</p>
<ul>
<li>Close your project window (and IntelliJ) and remove all <code>*.iml</code> files and all <code>.idea</code> folders (there should be one per module)</li>
<li>Run <code>mvn clean install</code> from the command line</li>
<li>Re-import the project into IntelliJ and pay attention when it asks you to enable auto-import</li>
</ul>
<p><strong>IntelliJ 2016 Update</strong>:</p>
<p>The <em>Import Maven Projects automatically</em> setting has been moved to <strong>Build, Execution, Deployment > Build Tools > Maven > Importing</strong> in your IntelliJ preferences.</p> | {
"question_id": 11454822,
"question_date": "2012-07-12T15:06:21.343Z",
"question_score": 230,
"tags": "java|maven|intellij-idea|maven-3",
"answer_id": 11467266,
"answer_date": "2012-07-13T08:59:16.617Z",
"answer_score": 311
} |
Please answer the following Stack Overflow question:
Title: Div height 100% and expands to fit content
<p>I have a div element on my page with its height set to 100%. The height of the body is also set to 100%. The inner div has a background and all that and is different from the body background. This works for making the div height 100% of the browser screen height, but the problem is I have content inside that div that extends vertically beyond the browser screen height. When I scroll down, the div ends at the point at which you had to begin scrolling the page, but the content overflows beyond that. How do I make the div always go all the way to the bottom to fit the inner content?</p>
<p>Here's a simplification of my CSS:</p>
<pre><code>body {
height:100%;
background:red;
}
#some_div {
height:100%;
background:black;
}
</code></pre>
<p>Once I scroll the page, the blackness ends and the content flows onto the red background. It doesn't seem to matter whether I set the positon to relative or absolute on the #some_div, the problem occurs either way. The content inside the #some_div is mostly absolutely positioned, and it is dynamically generated from a database so its height can't be known in advance.</p>
<p>Edit: Here is a screenshot of the problem:
<img src="https://i.stack.imgur.com/0EZlD.jpg" alt="div problem"></p> | <p>Here is what you should do in the CSS style, on the main <code>div</code></p>
<pre><code>display: block;
overflow: auto;
</code></pre>
<p>And do not touch <code>height</code></p> | {
"question_id": 9537838,
"question_date": "2012-03-02T17:38:41.840Z",
"question_score": 230,
"tags": "css|html|height|overflow",
"answer_id": 17807687,
"answer_date": "2013-07-23T10:33:04.490Z",
"answer_score": 377
} |
Please answer the following Stack Overflow question:
Title: plot a circle with pyplot
<p>surprisingly I didn't find a straight-forward description on how to draw a circle with matplotlib.pyplot (please no pylab) taking as input center (x,y) and radius r. I tried some variants of this:</p>
<pre><code>import matplotlib.pyplot as plt
circle=plt.Circle((0,0),2)
# here must be something like circle.plot() or not?
plt.show()
</code></pre>
<p>... but still didn't get it working. </p> | <p>You need to add it to an axes. A <a href="https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.patches.Circle.html" rel="noreferrer"><code>Circle</code></a> is a subclass of an <a href="https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.patches.Patch.html" rel="noreferrer"><code>Patch</code></a>, and an <code>axes</code> has an <a href="https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.add_patch.html" rel="noreferrer"><code>add_patch</code></a> method. (You can also use <a href="https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.axes.Axes.add_artist.html" rel="noreferrer"><code>add_artist</code></a> but it's not recommended.)</p>
<p>Here's an example of doing this:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
circle1 = plt.Circle((0, 0), 0.2, color='r')
circle2 = plt.Circle((0.5, 0.5), 0.2, color='blue')
circle3 = plt.Circle((1, 1), 0.2, color='g', clip_on=False)
fig, ax = plt.subplots() # note we must use plt.subplots, not plt.subplot
# (or if you have an existing figure)
# fig = plt.gcf()
# ax = fig.gca()
ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)
fig.savefig('plotcircles.png')
</code></pre>
<p>This results in the following figure:</p>
<p><img src="https://i.stack.imgur.com/6Wq0M.png" alt="" /></p>
<p>The first circle is at the origin, but by default <code>clip_on</code> is <code>True</code>, so the circle is clipped when ever it extends beyond the <code>axes</code>. The third (green) circle shows what happens when you don't clip the <code>Artist</code>. It extends beyond the axes (but not beyond the figure, ie the figure size is <em>not</em> automatically adjusted to plot all of your artists).</p>
<p>The units for x, y and radius correspond to data units by default. In this case, I didn't plot anything on my axes (<code>fig.gca()</code> returns the current axes), and since the limits have never been set, they defaults to an x and y range from 0 to 1.</p>
<p>Here's a continuation of the example, showing how units matter:</p>
<pre class="lang-py prettyprint-override"><code>circle1 = plt.Circle((0, 0), 2, color='r')
# now make a circle with no fill, which is good for hi-lighting key results
circle2 = plt.Circle((5, 5), 0.5, color='b', fill=False)
circle3 = plt.Circle((10, 10), 2, color='g', clip_on=False)
ax = plt.gca()
ax.cla() # clear things for fresh plot
# change default range so that new circles will work
ax.set_xlim((0, 10))
ax.set_ylim((0, 10))
# some data
ax.plot(range(11), 'o', color='black')
# key data point that we are encircling
ax.plot((5), (5), 'o', color='y')
ax.add_patch(circle1)
ax.add_patch(circle2)
ax.add_patch(circle3)
fig.savefig('plotcircles2.png')
</code></pre>
<p>which results in:</p>
<p><img src="https://i.stack.imgur.com/DAssu.png" alt="" /></p>
<p>You can see how I set the fill of the 2nd circle to <code>False</code>, which is useful for encircling key results (like my yellow data point).</p> | {
"question_id": 9215658,
"question_date": "2012-02-09T17:23:25.210Z",
"question_score": 230,
"tags": "python|matplotlib",
"answer_id": 9216646,
"answer_date": "2012-02-09T18:32:25.893Z",
"answer_score": 288
} |
Please answer the following Stack Overflow question:
Title: Get selected option text with JavaScript
<p>I have a dropdown list like this:</p>
<pre><code><select id="box1">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>
</code></pre>
<p>How can I get the actual option text rather than the value using JavaScript? I can get the value with something like:</p>
<pre><code><select id="box1" onChange="myNewFunction(this.selectedIndex);" >
</code></pre>
<p>But rather than <code>7122</code> I want <code>cat</code>.</p> | <p>Try options</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>function myNewFunction(sel) {
alert(sel.options[sel.selectedIndex].text);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="box1" onChange="myNewFunction(this);">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select></code></pre>
</div>
</div>
</p> | {
"question_id": 14976495,
"question_date": "2013-02-20T09:35:41.157Z",
"question_score": 230,
"tags": "javascript|html|dom|drop-down-menu",
"answer_id": 14976638,
"answer_date": "2013-02-20T09:42:24.693Z",
"answer_score": 372
} |
Please answer the following Stack Overflow question:
Title: How to declare an ArrayList with values?
<p><a href="https://stackoverflow.com/questions/12321177/arraylist-declaration-java">ArrayList or List declaration in Java</a> has questioned and answered how to declare an empty <code>ArrayList</code> but how do I declare an ArrayList with values?</p>
<p>I've tried the following but it returns a syntax error:</p>
<pre><code>import java.io.IOException;
import java.util.ArrayList;
public class test {
public static void main(String[] args) throws IOException {
ArrayList<String> x = new ArrayList<String>();
x = ['xyz', 'abc'];
}
}
</code></pre> | <p>In Java 9+ you can do:</p>
<pre><code>var x = List.of("xyz", "abc");
// 'var' works only for local variables
</code></pre>
<hr>
<p>Java 8 using <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html" rel="noreferrer"><code>Stream</code></a>:</p>
<pre><code>Stream.of("xyz", "abc").collect(Collectors.toList());
</code></pre>
<hr>
<p>And of course, you can create a new object using the constructor that accepts a <a href="http://docs.oracle.com/javase/8/docs/api/java/util/Collection.html" rel="noreferrer"><code>Collection</code></a>:</p>
<pre><code>List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));
</code></pre>
<hr>
<p>Tip: The <a href="http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html" rel="noreferrer">docs</a> contains very useful information that usually contains the answer you're looking for. For example, here are the constructors of the <code>ArrayList</code> class:</p>
<ul>
<li><p><a href="http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList--" rel="noreferrer"><code>ArrayList()</code></a></p>
<blockquote>
<p>Constructs an empty list with an initial capacity of ten.</p>
</blockquote></li>
<li><p><a href="http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-java.util.Collection-" rel="noreferrer"><code>ArrayList(Collection<? extends E> c)</code></a> (*)</p>
<blockquote>
<p>Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.</p>
</blockquote></li>
<li><p><a href="http://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html#ArrayList-int-" rel="noreferrer"><code>ArrayList(int initialCapacity)</code></a></p>
<blockquote>
<p>Constructs an empty list with the specified initial capacity.</p>
</blockquote></li>
</ul> | {
"question_id": 21696784,
"question_date": "2014-02-11T08:36:45.967Z",
"question_score": 230,
"tags": "java|arraylist|initialization|declare",
"answer_id": 21696844,
"answer_date": "2014-02-11T08:39:45.933Z",
"answer_score": 447
} |
Please answer the following Stack Overflow question:
Title: Drop all duplicate rows across multiple columns in Python Pandas
<p>The <code>pandas</code> <code>drop_duplicates</code> function is great for "uniquifying" a dataframe. However, one of the keyword arguments to pass is <code>take_last=True</code> or <code>take_last=False</code>, while I would like to drop all rows which are duplicates across a subset of columns. Is this possible?</p>
<pre><code> A B C
0 foo 0 A
1 foo 1 A
2 foo 1 B
3 bar 1 A
</code></pre>
<p>As an example, I would like to drop rows which match on columns <code>A</code> and <code>C</code> so this should drop rows 0 and 1.</p> | <p>This is much easier in pandas now with <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.drop_duplicates.html" rel="noreferrer">drop_duplicates</a> and the keep parameter.</p>
<pre><code>import pandas as pd
df = pd.DataFrame({"A":["foo", "foo", "foo", "bar"], "B":[0,1,1,1], "C":["A","A","B","A"]})
df.drop_duplicates(subset=['A', 'C'], keep=False)
</code></pre> | {
"question_id": 23667369,
"question_date": "2014-05-15T00:31:47.783Z",
"question_score": 230,
"tags": "python|pandas|duplicates|drop-duplicates",
"answer_id": 34272155,
"answer_date": "2015-12-14T16:38:02.883Z",
"answer_score": 327
} |
Please answer the following Stack Overflow question:
Title: How to plot in multiple subplots
<p>I am a little confused about how this code works:</p>
<pre><code>fig, axes = plt.subplots(nrows=2, ncols=2)
plt.show()
</code></pre>
<p>How does the fig, axes work in this case? What does it do?</p>
<p>Also why wouldn't this work to do the same thing:</p>
<pre><code>fig = plt.figure()
axes = fig.subplots(nrows=2, ncols=2)
</code></pre> | <p>There are several ways to do it. The <code>subplots</code> method creates the figure along with the subplots that are then stored in the <code>ax</code> array. For example:</p>
<pre><code>import matplotlib.pyplot as plt
x = range(10)
y = range(10)
fig, ax = plt.subplots(nrows=2, ncols=2)
for row in ax:
for col in row:
col.plot(x, y)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/2JxAs.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2JxAs.png" alt="enter image description here"></a></p>
<p>However, something like this will also work, it's not so "clean" though since you are creating a figure with subplots and then add on top of them:</p>
<pre><code>fig = plt.figure()
plt.subplot(2, 2, 1)
plt.plot(x, y)
plt.subplot(2, 2, 2)
plt.plot(x, y)
plt.subplot(2, 2, 3)
plt.plot(x, y)
plt.subplot(2, 2, 4)
plt.plot(x, y)
plt.show()
</code></pre>
<p><a href="https://i.stack.imgur.com/0EiUD.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0EiUD.png" alt="enter image description here"></a></p> | {
"question_id": 31726643,
"question_date": "2015-07-30T14:31:58.050Z",
"question_score": 230,
"tags": "python|pandas|matplotlib|seaborn|subplot",
"answer_id": 31728991,
"answer_date": "2015-07-30T16:14:39.477Z",
"answer_score": 304
} |
Please answer the following Stack Overflow question:
Title: How to split one string into multiple variables in bash shell?
<p>I've been looking for a solution and found similar questions, only they were attempting to split sentences with spaces between them, and the answers do not work for my situation.
</p>
<p>Currently a variable is being set to something a string like this:<br/>
<code>ABCDE-123456</code><br/>
and I would like to split that into 2 variables, while eliminating the "<b>-</b>". i.e.:<br/>
<code>var1=ABCDE</code><br/>
<code>var2=123456</code><br/></p>
<p>
How is it possible to accomplish this?
</p>
<hr />
<p>This is the solution that worked for me:<br/>
<code>var1=$(echo $STR | cut -f1 -d-)</code><br/>
<code>var2=$(echo $STR | cut -f2 -d-)</code><br/></p>
<p>Is it possible to use the <b>cut</b> command that will work without a delimiter (each character gets set as a variable)?</p>
<p><code>var1=$(echo $STR | cut -f1 -d?)</code><br/>
<code>var2=$(echo $STR | cut -f1 -d?)</code><br/>
<code>var3=$(echo $STR | cut -f1 -d?)</code><br/>
<code>etc.</code></p> | <p><em>If</em> your solution doesn't have to be general, i.e. only needs to work for strings like your example, you could do:</p>
<pre><code>var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)
</code></pre>
<p>I chose <code>cut</code> here because you could simply extend the code for a few more variables...</p> | {
"question_id": 10520623,
"question_date": "2012-05-09T16:54:57.317Z",
"question_score": 230,
"tags": "bash|shell|variables",
"answer_id": 10520697,
"answer_date": "2012-05-09T17:00:36.877Z",
"answer_score": 190
} |
Please answer the following Stack Overflow question:
Title: Encoding an image file with base64
<p>I want to encode an image into a string using the base64 module. I've ran into a problem though. How do I specify the image I want to be encoded? I tried using the directory to the image, but that simply leads to the directory being encoded. I want the actual image file to be encoded. </p>
<p><strong>EDIT</strong></p>
<p>I tried this snippet:</p>
<pre><code>with open("C:\Python26\seriph1.BMP", "rb") as f:
data12 = f.read()
UU = data12.encode("base64")
UUU = base64.b64decode(UU)
print UUU
self.image = ImageTk.PhotoImage(Image.open(UUU))
</code></pre>
<p>but I get the following error:</p>
<pre><code>Traceback (most recent call last):
File "<string>", line 245, in run_nodebug
File "C:\Python26\GUI1.2.9.py", line 473, in <module>
app = simpleapp_tk(None)
File "C:\Python26\GUI1.2.9.py", line 14, in __init__
self.initialize()
File "C:\Python26\GUI1.2.9.py", line 431, in initialize
self.image = ImageTk.PhotoImage(Image.open(UUU))
File "C:\Python26\lib\site-packages\PIL\Image.py", line 1952, in open
fp = __builtin__.open(fp, "rb")
TypeError: file() argument 1 must be encoded string without NULL bytes, not str
</code></pre>
<p>What am I doing wrong? </p> | <p>I'm not sure I understand your question. I assume you are doing something along the lines of:</p>
<pre><code>import base64
with open("yourfile.ext", "rb") as image_file:
encoded_string = base64.b64encode(image_file.read())
</code></pre>
<p>You have to open the file first of course, and read its contents - you cannot simply pass the path to the encode function.</p>
<p><strong>Edit:</strong>
Ok, here is an update after you have edited your original question.</p>
<p>First of all, remember to use raw strings (prefix the string with 'r') when using path delimiters on Windows, to prevent accidentally hitting an escape character. Second, PIL's Image.open either accepts a filename, or a file-like (that is, the object has to provide read, seek and tell methods). </p>
<p>That being said, you can use cStringIO to create such an object from a memory buffer:</p>
<pre><code>import cStringIO
import PIL.Image
# assume data contains your decoded image
file_like = cStringIO.StringIO(data)
img = PIL.Image.open(file_like)
img.show()
</code></pre> | {
"question_id": 3715493,
"question_date": "2010-09-15T07:24:48.533Z",
"question_score": 230,
"tags": "python|base64",
"answer_id": 3715530,
"answer_date": "2010-09-15T07:31:25.447Z",
"answer_score": 412
} |
Please answer the following Stack Overflow question:
Title: Storing images in SQL Server?
<p>I have made a small demo site and on it I am storing images within a image column on the sql server. A few questions I have are...</p>
<ul>
<li><p>Is this a bad idea? </p></li>
<li><p>Will it affect performance on my site when it grows?</p></li>
</ul>
<p>The alternative would be to store the image on disc and only store the reference to the image in the database. This must be a common dilemma many people have had. I'd welcome some advice and would actually be happy to make a less of a mistake if I could. </p> | <p>There's a really good paper by Microsoft Research called <a href="http://research.microsoft.com/apps/pubs/default.aspx?id=64525" rel="noreferrer">To Blob or Not To Blob</a>.</p>
<p>Their conclusion after a large number of performance tests and analysis is this:</p>
<ul>
<li><p>if your pictures or document are typically below 256KB in size, storing them in a database VARBINARY column is more efficient</p></li>
<li><p>if your pictures or document are typically over 1 MB in size, storing them in the filesystem is more efficient (and with SQL Server 2008's FILESTREAM attribute, they're still under transactional control and part of the database)</p></li>
<li><p>in between those two, it's a bit of a toss-up depending on your use</p></li>
</ul>
<p>If you decide to put your pictures into a SQL Server table, I would strongly recommend using a separate table for storing those pictures - do not store the employee photo in the employee table - keep them in a separate table. That way, the Employee table can stay lean and mean and very efficient, assuming you don't always need to select the employee photo, too, as part of your queries.</p>
<p>For filegroups, check out <a href="http://msdn.microsoft.com/en-us/library/ms179316.aspx" rel="noreferrer">Files and Filegroup Architecture</a> for an intro. Basically, you would either create your database with a separate filegroup for large data structures right from the beginning, or add an additional filegroup later. Let's call it "LARGE_DATA".</p>
<p>Now, whenever you have a new table to create which needs to store VARCHAR(MAX) or VARBINARY(MAX) columns, you can specify this file group for the large data:</p>
<pre><code> CREATE TABLE dbo.YourTable
(....... define the fields here ......)
ON Data -- the basic "Data" filegroup for the regular data
TEXTIMAGE_ON LARGE_DATA -- the filegroup for large chunks of data
</code></pre>
<p>Check out the MSDN intro on filegroups, and play around with it! </p> | {
"question_id": 5613898,
"question_date": "2011-04-10T18:40:12.870Z",
"question_score": 230,
"tags": "sql-server|image",
"answer_id": 5613926,
"answer_date": "2011-04-10T18:44:38.227Z",
"answer_score": 316
} |
Please answer the following Stack Overflow question:
Title: _tkinter.TclError: no display name and no $DISPLAY environment variable
<p>I am running a simple python script in the server:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
x = np.random.randn(60)
y = np.random.randn(60)
plt.scatter(x, y, s=20)
out_png = 'path/to/store/out_file.png'
plt.savefig(out_png, dpi=150)
</code></pre>
<p>I try to use the command <code>python example.py</code> in this server which has matplotlib 1.5.1 installed it fails with the error:</p>
<pre><code>Traceback (most recent call last):
File "example.py", line 7, in <module>
plt.scatter(x, y, s=20)
File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/pyplot.py", line 3241, in scatter
ax = gca()
File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/pyplot.py", line 928, in gca
return gcf().gca(**kwargs)
File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/pyplot.py", line 578, in gcf
return figure()
File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/pyplot.py", line 527, in figure
**kwargs)
File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 84, in new_figure_manager
return new_figure_manager_given_figure(num, figure)
File "/home/USER/.virtualenvs/nnet/lib/python2.7/site-packages/matplotlib/backends/backend_tkagg.py", line 92, in new_figure_manager_given_figure
window = Tk.Tk()
File "/usr/local/lib/python2.7/lib-tk/Tkinter.py", line 1810, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable
</code></pre>
<p>What is happening here?</p> | <p>Matplotlib chooses Xwindows backend by default.
You need to set matplotlib to not use the Xwindows backend. </p>
<p>Add this code to the start of your script (<strong>before importing pyplot</strong>) and try again:</p>
<pre><code>import matplotlib
matplotlib.use('Agg')
</code></pre>
<p>Or add to <code>.config/matplotlib/matplotlibrc</code> line <a href="https://matplotlib.org/faq/howto_faq.html#generate-images-without-having-a-window-appear" rel="noreferrer"><code>backend: Agg</code></a> to use non-interactive backend.</p>
<pre class="lang-sh prettyprint-override"><code>echo "backend: Agg" > ~/.config/matplotlib/matplotlibrc
</code></pre>
<p>Or when connect to server use <code>ssh -X remoteMachine</code> command to use Xwindows.</p>
<p>Also you may try to export display: <code>export DISPLAY=mymachine.com:0.0</code>.</p>
<p>For more info: <a href="https://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server" rel="noreferrer">https://matplotlib.org/faq/howto_faq.html#matplotlib-in-a-web-application-server</a></p> | {
"question_id": 37604289,
"question_date": "2016-06-03T00:45:45.673Z",
"question_score": 230,
"tags": "python|matplotlib|tkinter",
"answer_id": 37605654,
"answer_date": "2016-06-03T03:56:15.967Z",
"answer_score": 336
} |
Please answer the following Stack Overflow question:
Title: Browser detection in JavaScript?
<p>How do I determine the exact browser and version using JavaScript?</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>navigator.saysWho = (() => {
const { userAgent } = navigator
let match = userAgent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || []
let temp
if (/trident/i.test(match[1])) {
temp = /\brv[ :]+(\d+)/g.exec(userAgent) || []
return `IE ${temp[1] || ''}`
}
if (match[1] === 'Chrome') {
temp = userAgent.match(/\b(OPR|Edge)\/(\d+)/)
if (temp !== null) {
return temp.slice(1).join(' ').replace('OPR', 'Opera')
}
temp = userAgent.match(/\b(Edg)\/(\d+)/)
if (temp !== null) {
return temp.slice(1).join(' ').replace('Edg', 'Edge (Chromium)')
}
}
match = match[2] ? [ match[1], match[2] ] : [ navigator.appName, navigator.appVersion, '-?' ]
temp = userAgent.match(/version\/(\d+)/i)
if (temp !== null) {
match.splice(1, 1, temp[1])
}
return match.join(' ')
})()
console.log(navigator.saysWho) // outputs: `Chrome 89`</code></pre>
</div>
</div>
</p>
<p>As the name implies, this will tell you the name and version number supplied by the browser.</p>
<p>It is handy for sorting test and error results, when you are testing new code on multiple browsers.</p> | {
"question_id": 2400935,
"question_date": "2010-03-08T11:32:55.717Z",
"question_score": 230,
"tags": "javascript|browser-detection",
"answer_id": 2401861,
"answer_date": "2010-03-08T14:15:43.260Z",
"answer_score": 374
} |
Please answer the following Stack Overflow question:
Title: IntelliJ: Error:java: error: release version 5 not supported
<p>I'm using <strong>IntelliJ IDEA Ultimate 2019.3.1</strong>. Whenever I try to start any simple Java Maven project (may it be even a simple Hello World) I get the following error:</p>
<pre><code>Error:java: error: release version 5 not supported
</code></pre>
<p>Running <code>java --version</code> by terminal I get the following output:</p>
<pre><code>openjdk 11.0.5 2019-10-15
OpenJDK Runtime Environment (build 11.0.5+10-post-Ubuntu-0ubuntu1.1)
OpenJDK 64-Bit Server VM (build 11.0.5+10-post-Ubuntu-0ubuntu1.1, mixed mode, sharing)
</code></pre>
<p>Running <code>javac --version</code> by terminal I get the following output:</p>
<pre><code>javac 11.0.5
</code></pre>
<p>Going to the Settings of the Java Compiler ( as suggested <a href="https://stackoverflow.com/questions/52788743/intellij-error-java-release-version-10-not-supported">here</a> ) I see this:</p>
<p><a href="https://i.stack.imgur.com/WJdHN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WJdHN.png" alt="Java Compiler Settings"></a></p>
<p>I tried editing the "<strong>Target bytecode version</strong>" to <strong>1.8</strong> but I get the following errors:</p>
<pre><code>Error:(1, 26) java: package javafx.application does not exist
Error:(2, 20) java: package javafx.stage does not exist
Error:(4, 27) java: cannot find symbol
symbol: class Application
Error:(12, 23) java: cannot find symbol
symbol: class Stage
location: class Main
Error:(7, 9) java: cannot find symbol
symbol: method launch(java.lang.String[])
location: class Main
Error:(11, 5) java: method does not override or implement a method from a supertype
</code></pre>
<p>Changing it to version <strong>1.11</strong> I get this error instead:</p>
<pre><code>Error:java: Source option 5 is no longer supported. Use 6 or later.
</code></pre>
<p>What do you think is the problem? How may I solve it?</p> | <p>See <a href="https://stackoverflow.com/a/12900859/104891">https://stackoverflow.com/a/12900859/104891</a>. </p>
<p>First of all, set the <code>language level</code>/<code>release versions</code> in <code>pom.xml</code> like that: </p>
<pre><code><properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
</code></pre>
<p>Maven sets the default to 1.5 otherwise. You will also need to include the <code>maven-compiler-plugin</code> if you haven't already:</p>
<pre><code><dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
</dependency>
</code></pre>
<p>Also, try to change the Java version in each of these places:</p>
<p>File -> Project structure -> Project -> Project SDK -> 11.</p>
<p>File -> Project structure -> Project -> Project language level -> 11.</p>
<p>File -> Project structure -> Project -> Modules -> -> Sources --> 11</p>
<p>In project -> <kbd>ctrl</kbd> + <kbd>alt</kbd> + <kbd>s</kbd> -> Build, Execution, Deployment -> Compiler -> Java Compiler -> Project bytecode version -> 11</p>
<p>In project -> <kbd>ctrl</kbd> + <kbd>alt</kbd> + <kbd>s</kbd> -> Build, Execution, Deployment -> Compiler -> Java Compiler -> Module -> 1.11.</p> | {
"question_id": 59601077,
"question_date": "2020-01-05T14:54:15.577Z",
"question_score": 230,
"tags": "java|intellij-idea",
"answer_id": 59607812,
"answer_date": "2020-01-06T06:48:44.030Z",
"answer_score": 426
} |
Please answer the following Stack Overflow question:
Title: Getting permission denied (public key) on gitlab
<p>My problem is that I can't push or fetch from GitLab. However, I can clone (via HTTP or via SSH). I get this error when I try to push :</p>
<blockquote>
<p>Permission denied (publickey) fatal : Could not read from remote repository</p>
</blockquote>
<p>From all the threads I've looked, here is what I have done :</p>
<ul>
<li>Set up an SSH key on my computer and added the public key to GitLab</li>
<li>Done the config --global for username and email</li>
<li>Cloned via SSH and via HTTP to check if it would resolve the issue</li>
<li>Done the ssh -T [email protected] command</li>
</ul>
<p>If you have any insight about how to resolve my issue, it would be greatly appreciated.</p> | <p>I found this after searching a lot. It will work perfectly fine for me.</p>
<ol>
<li>Go to "Git Bash" just like cmd. Right click and "Run as Administrator".</li>
<li>Type <code>ssh-keygen</code></li>
<li>Press enter.</li>
<li>It will ask you to save the key to the specific directory.</li>
<li>Press enter. It will prompt you to type password or enter without password.</li>
<li>The public key will be created to the specific directory.</li>
<li>Now go to the directory and open <code>.ssh</code> folder.</li>
<li>You'll see a file <code>id_rsa.pub</code>. Open it on notepad. Copy all text from it.</li>
<li>Go to <a href="https://gitlab.com/-/profile/keys" rel="noreferrer">https://gitlab.com/-/profile/keys</a> or</li>
<li>Paste here in the "key" textfield.</li>
<li>Now click on the "Title" below. It will automatically get filled.</li>
<li>Then click "Add key".</li>
</ol>
<p>Now give it a shot and it will work for sure.</p> | {
"question_id": 40427498,
"question_date": "2016-11-04T16:26:07.960Z",
"question_score": 230,
"tags": "git|ubuntu|ssh|gitlab",
"answer_id": 42556216,
"answer_date": "2017-03-02T12:59:50.247Z",
"answer_score": 492
} |
Please answer the following Stack Overflow question:
Title: How do you get the Git repository's name in some Git repository?
<p>When you are working in some Git directory, how can you get the Git repository name in some Git repository? Are there any Git commands?</p>
<pre><code># I did check out bar repository and working in somewhere
# under bar directory at this moment such as below.
$ git clone git://github.com/foo/bar.git
$ cd bar/baz/qux/quux/corge/grault # and I am working in here!
$ git xxx # <- ???
bar
</code></pre> | <p>Well, if, for the repository name you mean the Git root directory name (the one that contains the <code>.git</code> directory) you can run this:</p>
<pre class="lang-bash prettyprint-override"><code>basename `git rev-parse --show-toplevel`
</code></pre>
<p>The <code>git rev-parse --show-toplevel</code> part gives you the path to that directory and <code>basename</code> strips the first part of the path.</p> | {
"question_id": 15715825,
"question_date": "2013-03-30T06:47:04.637Z",
"question_score": 230,
"tags": "git|repository",
"answer_id": 15716016,
"answer_date": "2013-03-30T07:09:46.490Z",
"answer_score": 228
} |
Please answer the following Stack Overflow question:
Title: jquery if div id has children
<p>This <code>if</code>-condition is what's giving me trouble:</p>
<pre><code>if (div id=myfav has children) {
do something
} else {
do something else
}
</code></pre>
<p>I tried all the following:</p>
<pre><code>if ( $('#myfav:hasChildren') ) { do something }
if ( $('#myfav').children() ) { do something }
if ( $('#myfav:empty') ) { do something }
if ( $('#myfav:not(:has(*))') ) { do something }
</code></pre> | <pre><code>if ( $('#myfav').children().length > 0 ) {
// do something
}
</code></pre>
<p>This should work. The <code>children()</code> function returns a JQuery object that contains the children. So you just need to check the size and see if it has at least one child.</p> | {
"question_id": 1526873,
"question_date": "2009-10-06T17:08:00.053Z",
"question_score": 230,
"tags": "jquery|children",
"answer_id": 1526986,
"answer_date": "2009-10-06T17:30:26.450Z",
"answer_score": 500
} |
Please answer the following Stack Overflow question:
Title: Convert string to Python class object?
<p>Given a string as user input to a Python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result:</p>
<pre><code>class Foo:
pass
str_to_class("Foo")
==> <class __main__.Foo at 0x69ba0>
</code></pre>
<p>Is this, at all, possible?</p> | <blockquote>
<p><strong>Warning</strong>: <code>eval()</code> can be used to execute arbitrary Python code. You should <strong><em>never</em></strong> use <code>eval()</code> with untrusted strings. (See <em><a href="https://stackoverflow.com/q/661084/3357935">Security of Python's eval() on untrusted strings?</a></em>)</p>
</blockquote>
<p>This seems simplest.</p>
<pre><code>>>> class Foo(object):
... pass
...
>>> eval("Foo")
<class '__main__.Foo'>
</code></pre> | {
"question_id": 1176136,
"question_date": "2009-07-24T07:01:23.990Z",
"question_score": 230,
"tags": "python",
"answer_id": 1178089,
"answer_date": "2009-07-24T14:32:24.617Z",
"answer_score": 141
} |
Please answer the following Stack Overflow question:
Title: iFrame src change event detection?
<p>Assuming I have no control over the content in the iframe, is there any way that I can detect a src change in it via the parent page? Some sort of onload maybe?</p>
<p>My last resort is to do a 1 second interval test if the iframe src is the same as it was before, but doing this hacky solution would suck.</p>
<p>I'm using the jQuery library if it helps.</p> | <p>You may want to use the <code>onLoad</code> event, as in the following example:</p>
<pre><code><iframe src="http://www.google.com/" onLoad="alert('Test');"></iframe>
</code></pre>
<p>The alert will pop-up whenever the location within the iframe changes. It works in all modern browsers, but may not work in some very older browsers like IE5 and early Opera. (<a href="http://www.tipstrs.com/tip/3126/Telling-when-an-iframe-is-done-loading" rel="noreferrer">Source</a>)</p>
<p><strong>If the iframe is showing a page within the same domain of the parent</strong>, you would be able to access the location with <code>contentWindow.location</code>, as in the following example:</p>
<pre><code><iframe src="/test.html" onLoad="alert(this.contentWindow.location);"></iframe>
</code></pre> | {
"question_id": 2429045,
"question_date": "2010-03-11T22:07:46.053Z",
"question_score": 230,
"tags": "javascript|jquery|iframe|onload",
"answer_id": 2429058,
"answer_date": "2010-03-11T22:10:50.230Z",
"answer_score": 238
} |
Please answer the following Stack Overflow question:
Title: Python csv string to array
<p>Anyone know of a simple library or function to parse a csv encoded string and turn it into an array or dictionary?</p>
<p>I don't think I want the built in <a href="http://docs.python.org/library/csv.html" rel="noreferrer">csv module</a> because in all the examples I've seen that takes filepaths, not strings.</p> | <p>You can convert a string to a file object using <a href="https://docs.python.org/library/io.html#io.StringIO" rel="noreferrer"><code>io.StringIO</code></a> and then pass that to the <code>csv</code> module:</p>
<pre><code>from io import StringIO
import csv
scsv = """text,with,Polish,non-Latin,letters
1,2,3,4,5,6
a,b,c,d,e,f
gęś,zółty,wąż,idzie,wąską,dróżką,
"""
f = StringIO(scsv)
reader = csv.reader(f, delimiter=',')
for row in reader:
print('\t'.join(row))
</code></pre>
<p>simpler version with <code>split()</code> on newlines:</p>
<pre><code>reader = csv.reader(scsv.split('\n'), delimiter=',')
for row in reader:
print('\t'.join(row))
</code></pre>
<p>Or you can simply <code>split()</code> this string into lines using <code>\n</code> as separator, and then <code>split()</code> each line into values, but this way you must be aware of quoting, so using <code>csv</code> module is preferred.</p>
<p>On <strong>Python 2</strong> you have to import <code>StringIO</code> as</p>
<pre><code>from StringIO import StringIO
</code></pre>
<p>instead.</p> | {
"question_id": 3305926,
"question_date": "2010-07-22T05:08:48.930Z",
"question_score": 230,
"tags": "python|string|arrays|csv",
"answer_id": 3305964,
"answer_date": "2010-07-22T05:18:14.030Z",
"answer_score": 334
} |
Please answer the following Stack Overflow question:
Title: Java associative-array
<p>How can I create and fetch associative arrays in Java like I can in PHP?</p>
<p>For example:</p>
<pre><code>$arr[0]['name'] = 'demo';
$arr[0]['fname'] = 'fdemo';
$arr[1]['name'] = 'test';
$arr[1]['fname'] = 'fname';
</code></pre> | <p>Java doesn't support associative arrays, however this could easily be achieved using a <code>Map</code>. E.g., </p>
<pre><code>Map<String, String> map = new HashMap<String, String>();
map.put("name", "demo");
map.put("fname", "fdemo");
// etc
map.get("name"); // returns "demo"
</code></pre>
<p>Even more accurate to your example (since you can replace String with any object that meet your needs) would be to declare: </p>
<pre><code>List<Map<String, String>> data = new ArrayList<>();
data.add(0, map);
data.get(0).get("name");
</code></pre>
<p><a href="http://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html">See the official documentation for more information</a></p> | {
"question_id": 5122913,
"question_date": "2011-02-25T21:31:23.403Z",
"question_score": 230,
"tags": "java|hashmap|associative-array",
"answer_id": 5122948,
"answer_date": "2011-02-25T21:34:12.603Z",
"answer_score": 383
} |
Please answer the following Stack Overflow question:
Title: Node.js Mongoose.js string to ObjectId function
<p>Is there a function to turn a string into an objectId in node using mongoose? The schema specifies that something is an ObjectId, but when it is saved from a string, mongo tells me it is still just a string. The _id of the object, for instance, is displayed as <code>objectId("blah")</code>.</p> | <p>You can do it like so:</p>
<pre><code>var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');
</code></pre> | {
"question_id": 6578178,
"question_date": "2011-07-05T05:15:19.623Z",
"question_score": 230,
"tags": "mongodb|node.js|mongoose",
"answer_id": 8393613,
"answer_date": "2011-12-05T23:56:29.380Z",
"answer_score": 533
} |
Please answer the following Stack Overflow question:
Title: How to find a hash key containing a matching value
<p>Given I have the below <strong>clients</strong> hash, is there a quick ruby way (without having to write a multi-line script) to obtain the key given I want to match the client_id? E.g. How to get the key for <code>client_id == "2180"</code>?</p>
<pre><code>clients = {
"yellow"=>{"client_id"=>"2178"},
"orange"=>{"client_id"=>"2180"},
"red"=>{"client_id"=>"2179"},
"blue"=>{"client_id"=>"2181"}
}
</code></pre> | <p>You could use <a href="http://rubydoc.info/docs/ruby-core/1.9.2/Enumerable:select" rel="noreferrer">Enumerable#select</a>:</p>
<pre><code>clients.select{|key, hash| hash["client_id"] == "2180" }
#=> [["orange", {"client_id"=>"2180"}]]
</code></pre>
<p>Note that the result will be an array of all the matching values, where each is an array of the key and value.</p> | {
"question_id": 3794039,
"question_date": "2010-09-25T13:38:18.963Z",
"question_score": 230,
"tags": "ruby",
"answer_id": 3794053,
"answer_date": "2010-09-25T13:43:11.247Z",
"answer_score": 193
} |
Please answer the following Stack Overflow question:
Title: How to include another XHTML in XHTML using JSF 2.0 Facelets?
<p>What is the most correct way to include another XHTML page in an XHTML page? I have been trying different ways, none of them are working.</p> | <h2><code><ui:include></code></h2>
<p>Most basic way is <a href="https://docs.oracle.com/javaee/7/javaserver-faces-2-2/vdldocs-facelets/ui/include.html" rel="noreferrer"><code><ui:include></code></a>. The included content must be placed inside <a href="https://docs.oracle.com/javaee/7/javaserver-faces-2-2/vdldocs-facelets/ui/composition.html" rel="noreferrer"><code><ui:composition></code></a>.</p>
<p>Kickoff example of the master page <code>/page.xhtml</code>:</p>
<pre><code><!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title>Include demo</title>
</h:head>
<h:body>
<h1>Master page</h1>
<p>Master page blah blah lorem ipsum</p>
<ui:include src="/WEB-INF/include.xhtml" />
</h:body>
</html>
</code></pre>
<p>The include page <code>/WEB-INF/include.xhtml</code> (yes, this is the file in its entirety, any tags outside <code><ui:composition></code> are unnecessary as they are ignored by Facelets anyway):</p>
<pre><code><ui:composition
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h2>Include page</h2>
<p>Include page blah blah lorem ipsum</p>
</ui:composition>
</code></pre>
<p>This needs to be opened by <code>/page.xhtml</code>. Do note that you don't need to repeat <code><html></code>, <code><h:head></code> and <code><h:body></code> inside the include file as that would otherwise result in <a href="http://validator.w3.org" rel="noreferrer">invalid HTML</a>.</p>
<p>You can use a dynamic EL expression in <code><ui:include src></code>. See also <a href="https://stackoverflow.com/questions/7108668/how-to-ajax-refresh-dynamic-include-content-by-navigation-menu-jsf-spa">How to ajax-refresh dynamic include content by navigation menu? (JSF SPA)</a>.</p>
<hr />
<h2><code><ui:define></code>/<code><ui:insert></code></h2>
<p>A more advanced way of including is <em>templating</em>. This includes basically the other way round. The master template page should use <a href="https://docs.oracle.com/javaee/7/javaserver-faces-2-2/vdldocs-facelets/ui/insert.html" rel="noreferrer"><code><ui:insert></code></a> to declare places to insert defined template content. The template client page which is using the master template page should use <a href="https://docs.oracle.com/javaee/7/javaserver-faces-2-2/vdldocs-facelets/ui/define.html" rel="noreferrer"><code><ui:define></code></a> to define the template content which is to be inserted.</p>
<p>Master template page <code>/WEB-INF/template.xhtml</code> (as a design hint: the header, menu and footer can in turn even be <code><ui:include></code> files):</p>
<pre><code><!DOCTYPE html>
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title><ui:insert name="title">Default title</ui:insert></title>
</h:head>
<h:body>
<div id="header">Header</div>
<div id="menu">Menu</div>
<div id="content"><ui:insert name="content">Default content</ui:insert></div>
<div id="footer">Footer</div>
</h:body>
</html>
</code></pre>
<p>Template client page <code>/page.xhtml</code> (note the <code>template</code> attribute; also here, this is the file in its entirety):</p>
<pre><code><ui:composition template="/WEB-INF/template.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<ui:define name="title">
New page title here
</ui:define>
<ui:define name="content">
<h1>New content here</h1>
<p>Blah blah</p>
</ui:define>
</ui:composition>
</code></pre>
<p>This needs to be opened by <code>/page.xhtml</code>. If there is no <code><ui:define></code>, then the default content inside <code><ui:insert></code> will be displayed instead, if any.</p>
<hr />
<h2><code><ui:param></code></h2>
<p>You can pass parameters to <code><ui:include></code> or <code><ui:composition template></code> by <a href="https://docs.oracle.com/javaee/7/javaserver-faces-2-2/vdldocs-facelets/ui/param.html" rel="noreferrer"><code><ui:param></code></a>.</p>
<pre><code><ui:include ...>
<ui:param name="foo" value="#{bean.foo}" />
</ui:include>
</code></pre>
<pre><code><ui:composition template="...">
<ui:param name="foo" value="#{bean.foo}" />
...
</ui:composition >
</code></pre>
<p>Inside the include/template file, it'll be available as <code>#{foo}</code>. In case you need to pass "many" parameters to <code><ui:include></code>, then you'd better consider registering the include file as a tagfile, so that you can ultimately use it like so <code><my:tagname foo="#{bean.foo}"></code>. See also <a href="https://stackoverflow.com/questions/6822000">When to use <ui:include>, tag files, composite components and/or custom components?</a></p>
<p>You can even pass whole beans, methods and parameters via <code><ui:param></code>. See also <a href="https://stackoverflow.com/questions/8004233/jsf-2-how-to-pass-an-action-including-an-argument-to-be-invoked-to-a-facelets-s">JSF 2: how to pass an action including an argument to be invoked to a Facelets sub view (using ui:include and ui:param)?</a></p>
<hr />
<h2>Design hints</h2>
<p>The files which aren't supposed to be publicly accessible by just entering/guessing its URL, need to be placed in <code>/WEB-INF</code> folder, like as the include file and the template file in above example. See also <a href="https://stackoverflow.com/questions/9031811">Which XHTML files do I need to put in /WEB-INF and which not?</a></p>
<p>There doesn't need to be any markup (HTML code) outside <code><ui:composition></code> and <code><ui:define></code>. You can put any, but they will be <strong>ignored</strong> by Facelets. Putting markup in there is only useful for web designers. See also <a href="https://stackoverflow.com/questions/10504190">Is there a way to run a JSF page without building the whole project?</a></p>
<p>The HTML5 doctype is the recommended doctype these days, "in spite of" that it's a XHTML file. You should see XHTML as a language which allows you to produce HTML output using a XML based tool. See also <a href="https://stackoverflow.com/questions/2935759/is-it-possible-to-use-jsffacelets-with-html-4-5">Is it possible to use JSF+Facelets with HTML 4/5?</a> and <a href="https://stackoverflow.com/questions/19189372/javaserver-faces-2-2-and-html5-support-why-is-xhtml-still-being-used">JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used</a>.</p>
<p>CSS/JS/image files can be included as dynamically relocatable/localized/versioned resources. See also <a href="https://stackoverflow.com/questions/8367421/how-to-reference-css-js-image-resource-in-facelets-template">How to reference CSS / JS / image resource in Facelets template?</a></p>
<p>You can put Facelets files in a reusable JAR file. See also <a href="https://stackoverflow.com/questions/8320486">Structure for multiple JSF projects with shared code</a>.</p>
<p>For real world examples of advanced Facelets templating, check the <code>src/main/webapp</code> folder of <a href="https://github.com/javaeekickoff/java-ee-kickoff-app" rel="noreferrer">Java EE Kickoff App source code</a> and <a href="https://github.com/omnifaces/showcase" rel="noreferrer">OmniFaces showcase site source code</a>.</p> | {
"question_id": 4792862,
"question_date": "2011-01-25T11:19:42.633Z",
"question_score": 230,
"tags": "jsf|xhtml|include|jsf-2|facelets",
"answer_id": 4793959,
"answer_date": "2011-01-25T13:17:25.627Z",
"answer_score": 444
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.