input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: How to list the properties of a JavaScript object?
<p>Say I create an object thus:</p>
<pre><code>var myObject =
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
</code></pre>
<p>What is the best way to retrieve a list of the property names? i.e. I would like to end up with some variable 'keys' such that:</p>
<pre><code>keys == ["ircEvent", "method", "regex"]
</code></pre> | <p>In modern browsers (IE9+, FF4+, Chrome5+, Opera12+, Safari5+) you can use the built in <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys" rel="noreferrer">Object.keys</a> method:</p>
<pre><code>var keys = Object.keys(myObject);
</code></pre>
<p>The above has a full polyfill but a simplified version is:</p>
<pre><code>var getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
</code></pre>
<p>Alternatively replace <code>var getKeys</code> with <code>Object.prototype.keys</code> to allow you to call <code>.keys()</code> on any object. Extending the prototype has some side effects and I wouldn't recommend doing it.</p> | {
"question_id": 208016,
"question_date": "2008-10-16T10:08:18.190Z",
"question_score": 938,
"tags": "javascript",
"answer_id": 208020,
"answer_date": "2008-10-16T10:12:04.237Z",
"answer_score": 1182
} |
Please answer the following Stack Overflow question:
Title: Count number of lines in a git repository
<p>How would I count the total number of lines present in all the files in a git repository?</p>
<p><code>git ls-files</code> gives me a list of files tracked by git.</p>
<p>I'm looking for a command to <code>cat</code> all those files. Something like</p>
<pre><code>git ls-files | [cat all these files] | wc -l
</code></pre> | <p><code>xargs</code> will let you <code>cat</code> all the files together before passing them to <code>wc</code>, like you asked:</p>
<pre><code>git ls-files | xargs cat | wc -l
</code></pre>
<p>But skipping the intermediate <code>cat</code> gives you more information and is probably better:</p>
<pre><code>git ls-files | xargs wc -l
</code></pre> | {
"question_id": 4822471,
"question_date": "2011-01-27T22:07:06.330Z",
"question_score": 938,
"tags": "bash|git|shell|line-count",
"answer_id": 4822516,
"answer_date": "2011-01-27T22:11:03.600Z",
"answer_score": 1451
} |
Please answer the following Stack Overflow question:
Title: CSS opacity only to background color, not the text on it?
<p>Can I assign the <code>opacity</code> property to the <code>background</code> property of a <code>div</code> only and not to the text on it?</p>
<p>I've tried:</p>
<pre><code>background: #CCC;
opacity: 0.6;
</code></pre>
<p>but this doesn't change the opacity.</p> | <p>It sounds like you want to use a transparent background, in which case you could try using the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/color_value#rgb()_and_rgba()" rel="noreferrer"><code>rgba()</code></a> function:</p>
<blockquote>
<h3><code>rgba(R, G, B, A)</code></h3>
<p>R (red), G (green), and B (blue) can be either <code><integer></code>s or <code><percentage></code>s, where the number 255 corresponds to 100%. A (alpha) can be a <code><number></code> between 0 and 1, or a <code><percentage></code>, where the number 1 corresponds to 100% (full opacity).</p>
<h3>RGBa example</h3>
<pre><code>background: rgba(51, 170, 51, .1) /* 10% opaque green */
background: rgba(51, 170, 51, .4) /* 40% opaque green */
background: rgba(51, 170, 51, .7) /* 70% opaque green */
background: rgba(51, 170, 51, 1) /* full opaque green */
</code></pre>
</blockquote>
<p>A small <a href="http://jsfiddle.net/swQx2/" rel="noreferrer">example</a> showing how <code>rgba</code> can be used.</p>
<p>As of 2018, practically <a href="https://caniuse.com/#feat=css3-colors" rel="noreferrer"><strong>every browser supports the <code>rgba</code> syntax</strong></a>.</p> | {
"question_id": 5135019,
"question_date": "2011-02-27T18:30:06.703Z",
"question_score": 937,
"tags": "css|opacity",
"answer_id": 5135033,
"answer_date": "2011-02-27T18:32:42.113Z",
"answer_score": 1548
} |
Please answer the following Stack Overflow question:
Title: Get month name from Date
<p>How can I generate the name of the month (e.g: Oct/October) from this date object in JavaScript?</p>
<pre><code>var objDate = new Date("10/11/2009");
</code></pre> | <p>Shorter version:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
const d = new Date();
document.write("The current month is " + monthNames[d.getMonth()]);</code></pre>
</div>
</div>
</p>
<p><strong>Note</strong> (2019-03-08) - This answer by me which I originally wrote in 2009 is outdated. See <a href="https://stackoverflow.com/a/18648314/6086226">David Storey's answer</a> for a better solution.</p> | {
"question_id": 1643320,
"question_date": "2009-10-29T12:19:14.497Z",
"question_score": 937,
"tags": "javascript|date|date-format|time-format",
"answer_id": 1643468,
"answer_date": "2009-10-29T12:45:41.380Z",
"answer_score": 1415
} |
Please answer the following Stack Overflow question:
Title: "code ." is not working in on the command line for Visual Studio Code on OS X/Mac
<p>The command <code>code .</code> doesn't work in <a href="https://code.visualstudio.com/docs/nodejs" rel="noreferrer">this manual</a>.</p>
<p>All the other steps before that worked. How can I call the Visual Studio Code in an OS X terminal?</p>
<pre><code>pwd
</code></pre>
<blockquote>
<p>/Users/mona/nodejs/myExpressApp</p>
</blockquote>
<pre><code>code .
</code></pre>
<blockquote>
<p>-bash: code: command not found</p>
</blockquote>
<hr/>
<p>I ended up opening it from within Visual Code Studio by changing the workspace, but why won't that command <code>code .</code> part work?</p>
<p><img src="https://i.stack.imgur.com/EbtmG.png" alt="Enter image description here" /></p> | <h3>1. Make sure you drag the Visual Studio Code application into the <em>Applications</em> folder</h3>
<p><em>Otherwise (as noted in the comments), you'll have to go through this process again after a reboot.</em></p>
<hr />
<h3>2. Next, open Visual Studio Code</h3>
<p>Open the <strong>Command Palette</strong> via <kbd>⇧</kbd> + <kbd>⌘</kbd> + <kbd>P</kbd> and type <code>shell command</code> to find the Shell Command:</p>
<p>Use the Uninstall 'code' command in the PATH command before the <em>"Install 'code' command in PATH"</em> command.</p>
<p><a href="https://i.stack.imgur.com/3gYHb.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3gYHb.png" alt="
</code></pre>
<p>where <code>MyTitle</code> is a title within the document but this didn't work.</p> | <p>In <a href="http://johnmacfarlane.net/pandoc/" rel="nofollow noreferrer">pandoc</a>, if you use the option <code>--toc</code> in producing html, a table of contents will be produced with links to the sections, and back to the table of contents from the section headings. It is similar with the other formats pandoc writes, like LaTeX, rtf, rst, etc. So with the command</p>
<pre><code>pandoc --toc happiness.txt -o happiness.html
</code></pre>
<p>this bit of markdown:</p>
<pre><code>% True Happiness
Introduction
------------
Many have posed the question of true happiness. In this blog post we propose to
solve it.
First Attempts
--------------
The earliest attempts at attaining true happiness of course aimed at pleasure.
Soon, though, the downside of pleasure was revealed.
</code></pre>
<p>will yield this as the body of the html:</p>
<pre class="lang-html prettyprint-override"><code><h1 class="title">
True Happiness
</h1>
<div id="TOC">
<ul>
<li>
<a href="#introduction">Introduction</a>
</li>
<li>
<a href="#first-attempts">First Attempts</a>
</li>
</ul>
</div>
<div id="introduction">
<h2>
<a href="#TOC">Introduction</a>
</h2>
<p>
Many have posed the question of true happiness. In this blog post we propose to solve it.
</p>
</div>
<div id="first-attempts">
<h2>
<a href="#TOC">First Attempts</a>
</h2>
<p>
The earliest attempts at attaining true happiness of course aimed at pleasure. Soon, though, the downside of pleasure was revealed.
</p>
</div>
</code></pre> | {
"question_id": 2822089,
"question_date": "2010-05-12T19:24:51.850Z",
"question_score": 936,
"tags": "markdown|multimarkdown",
"answer_id": 2823945,
"answer_date": "2010-05-13T01:33:15.287Z",
"answer_score": 33
} |
Please answer the following Stack Overflow question:
Title: Git ignore file for Xcode projects
<p>Which files should I include in <code>.gitignore</code> when using <em>Git</em> in conjunction with <em>Xcode</em>?</p> | <p>I was previously using the top-voted answer, but it needs a bit of cleanup, so here it is redone for Xcode 4, with some improvements.</p>
<p>I've researched <em>every</em> file in this list, but several of them do not exist in Apple's official Xcode documentation, so I had to go on Apple mailing lists.</p>
<p>Apple continues to add undocumented files, potentially corrupting our live projects. This IMHO is unacceptable, and I've now started logging bugs against it each time they do so. I know they don't care, but maybe it'll shame one of them into treating developers more fairly.</p>
<hr>
<p>If you need to customize, here's a gist you can fork: <a href="https://gist.github.com/3786883" rel="noreferrer">https://gist.github.com/3786883</a></p>
<hr>
<pre><code>#########################
# .gitignore file for Xcode4 and Xcode5 Source projects
#
# Apple bugs, waiting for Apple to fix/respond:
#
# 15564624 - what does the xccheckout file in Xcode5 do? Where's the documentation?
#
# Version 2.6
# For latest version, see: http://stackoverflow.com/questions/49478/git-ignore-file-for-xcode-projects
#
# 2015 updates:
# - Fixed typo in "xccheckout" line - thanks to @lyck for pointing it out!
# - Fixed the .idea optional ignore. Thanks to @hashier for pointing this out
# - Finally added "xccheckout" to the ignore. Apple still refuses to answer support requests about this, but in practice it seems you should ignore it.
# - minor tweaks from Jona and Coeur (slightly more precise xc* filtering/names)
# 2014 updates:
# - appended non-standard items DISABLED by default (uncomment if you use those tools)
# - removed the edit that an SO.com moderator made without bothering to ask me
# - researched CocoaPods .lock more carefully, thanks to Gokhan Celiker
# 2013 updates:
# - fixed the broken "save personal Schemes"
# - added line-by-line explanations for EVERYTHING (some were missing)
#
# NB: if you are storing "built" products, this WILL NOT WORK,
# and you should use a different .gitignore (or none at all)
# This file is for SOURCE projects, where there are many extra
# files that we want to exclude
#
#########################
#####
# OS X temporary files that should never be committed
#
# c.f. http://www.westwind.com/reference/os-x/invisibles.html
.DS_Store
# c.f. http://www.westwind.com/reference/os-x/invisibles.html
.Trashes
# c.f. http://www.westwind.com/reference/os-x/invisibles.html
*.swp
#
# *.lock - this is used and abused by many editors for many different things.
# For the main ones I use (e.g. Eclipse), it should be excluded
# from source-control, but YMMV.
# (lock files are usually local-only file-synchronization on the local FS that should NOT go in git)
# c.f. the "OPTIONAL" section at bottom though, for tool-specific variations!
#
# In particular, if you're using CocoaPods, you'll want to comment-out this line:
*.lock
#
# profile - REMOVED temporarily (on double-checking, I can't find it in OS X docs?)
#profile
####
# Xcode temporary files that should never be committed
#
# NB: NIB/XIB files still exist even on Storyboard projects, so we want this...
*~.nib
####
# Xcode build files -
#
# NB: slash on the end, so we only remove the FOLDER, not any files that were badly named "DerivedData"
DerivedData/
# NB: slash on the end, so we only remove the FOLDER, not any files that were badly named "build"
build/
#####
# Xcode private settings (window sizes, bookmarks, breakpoints, custom executables, smart groups)
#
# This is complicated:
#
# SOMETIMES you need to put this file in version control.
# Apple designed it poorly - if you use "custom executables", they are
# saved in this file.
# 99% of projects do NOT use those, so they do NOT want to version control this file.
# ..but if you're in the 1%, comment out the line "*.pbxuser"
# .pbxuser: http://lists.apple.com/archives/xcode-users/2004/Jan/msg00193.html
*.pbxuser
# .mode1v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html
*.mode1v3
# .mode2v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html
*.mode2v3
# .perspectivev3: http://stackoverflow.com/questions/5223297/xcode-projects-what-is-a-perspectivev3-file
*.perspectivev3
# NB: also, whitelist the default ones, some projects need to use these
!default.pbxuser
!default.mode1v3
!default.mode2v3
!default.perspectivev3
####
# Xcode 4 - semi-personal settings
#
# Apple Shared data that Apple put in the wrong folder
# c.f. http://stackoverflow.com/a/19260712/153422
# FROM ANSWER: Apple says "don't ignore it"
# FROM COMMENTS: Apple is wrong; Apple code is too buggy to trust; there are no known negative side-effects to ignoring Apple's unofficial advice and instead doing the thing that actively fixes bugs in Xcode
# Up to you, but ... current advice: ignore it.
*.xccheckout
#
#
# OPTION 1: ---------------------------------
# throw away ALL personal settings (including custom schemes!
# - unless they are "shared")
# As per build/ and DerivedData/, this ought to have a trailing slash
#
# NB: this is exclusive with OPTION 2 below
xcuserdata/
# OPTION 2: ---------------------------------
# get rid of ALL personal settings, but KEEP SOME OF THEM
# - NB: you must manually uncomment the bits you want to keep
#
# NB: this *requires* git v1.8.2 or above; you may need to upgrade to latest OS X,
# or manually install git over the top of the OS X version
# NB: this is exclusive with OPTION 1 above
#
#xcuserdata/**/*
# (requires option 2 above): Personal Schemes
#
#!xcuserdata/**/xcschemes/*
####
# Xcode 4 workspaces - more detailed
#
# Workspaces are important! They are a core feature of Xcode - don't exclude them :)
#
# Workspace layout is quite spammy. For reference:
#
# /(root)/
# /(project-name).xcodeproj/
# project.pbxproj
# /project.xcworkspace/
# contents.xcworkspacedata
# /xcuserdata/
# /(your name)/xcuserdatad/
# UserInterfaceState.xcuserstate
# /xcshareddata/
# /xcschemes/
# (shared scheme name).xcscheme
# /xcuserdata/
# /(your name)/xcuserdatad/
# (private scheme).xcscheme
# xcschememanagement.plist
#
#
####
# Xcode 4 - Deprecated classes
#
# Allegedly, if you manually "deprecate" your classes, they get moved here.
#
# We're using source-control, so this is a "feature" that we do not want!
*.moved-aside
####
# OPTIONAL: Some well-known tools that people use side-by-side with Xcode / iOS development
#
# NB: I'd rather not include these here, but gitignore's design is weak and doesn't allow
# modular gitignore: you have to put EVERYTHING in one file.
#
# COCOAPODS:
#
# c.f. http://guides.cocoapods.org/using/using-cocoapods.html#what-is-a-podfilelock
# c.f. http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control
#
#!Podfile.lock
#
# RUBY:
#
# c.f. http://yehudakatz.com/2010/12/16/clarifying-the-roles-of-the-gemspec-and-gemfile/
#
#!Gemfile.lock
#
# IDEA:
#
# c.f. https://www.jetbrains.com/objc/help/managing-projects-under-version-control.html?search=workspace.xml
#
#.idea/workspace.xml
#
# TEXTMATE:
#
# -- UNVERIFIED: c.f. http://stackoverflow.com/a/50283/153422
#
#tm_build_errors
####
# UNKNOWN: recommended by others, but I can't discover what these files are
#
</code></pre> | {
"question_id": 49478,
"question_date": "2008-09-08T11:07:49.953Z",
"question_score": 936,
"tags": "xcode|git|macos|version-control|gitignore",
"answer_id": 12021580,
"answer_date": "2012-08-18T19:22:10.663Z",
"answer_score": 724
} |
Please answer the following Stack Overflow question:
Title: How can I get column names from a table in SQL Server?
<p>I want to query the name of all columns of a table. I found how to do this in:</p>
<ul>
<li><a href="https://stackoverflow.com/q/452464/419956">Oracle</a></li>
<li><a href="https://stackoverflow.com/q/193780/419956">MySQL</a></li>
<li><a href="https://dba.stackexchange.com/q/22362/5089">PostgreSQL</a></li>
</ul>
<p>But I also need to know: <strong>how can this be done in <em>Microsoft SQL Server</em> (2008 in my case)?</strong></p> | <p>You can obtain this information and much, much more by querying the <a href="http://msdn.microsoft.com/en-us/library/aa933204%28SQL.80%29.aspx" rel="noreferrer">Information Schema views</a>.</p>
<p>This sample query: </p>
<pre><code>SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'Customers'
</code></pre>
<p>Can be made over all these DB objects: </p>
<ul>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/check-constraints-transact-sql" rel="noreferrer">CHECK_CONSTRAINTS</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/column-domain-usage-transact-sql" rel="noreferrer">COLUMN_DOMAIN_USAGE</a></li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/column-privileges-transact-sql" rel="noreferrer">COLUMN_PRIVILEGES</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/columns-transact-sql" rel="noreferrer">COLUMNS</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/constraint-column-usage-transact-sql" rel="noreferrer">CONSTRAINT_COLUMN_USAGE</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/constraint-table-usage-transact-sql" rel="noreferrer">CONSTRAINT_TABLE_USAGE</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/domain-constraints-transact-sql" rel="noreferrer">DOMAIN_CONSTRAINTS</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/domains-transact-sql" rel="noreferrer">DOMAINS</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/key-column-usage-transact-sql" rel="noreferrer">KEY_COLUMN_USAGE</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/parameters-transact-sql" rel="noreferrer">PARAMETERS</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/referential-constraints-transact-sql" rel="noreferrer">REFERENTIAL_CONSTRAINTS</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/routines-transact-sql" rel="noreferrer">ROUTINES</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/routine-columns-transact-sql" rel="noreferrer">ROUTINE_COLUMNS</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/schemata-transact-sql" rel="noreferrer">SCHEMATA</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/table-constraints-transact-sql" rel="noreferrer">TABLE_CONSTRAINTS</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/table-privileges-transact-sql" rel="noreferrer">TABLE_PRIVILEGES</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/tables-transact-sql" rel="noreferrer">TABLES</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/view-column-usage-transact-sql" rel="noreferrer">VIEW_COLUMN_USAGE</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/view-table-usage-transact-sql" rel="noreferrer">VIEW_TABLE_USAGE</a> </li>
<li><a href="https://docs.microsoft.com/en-us/sql/relational-databases/system-information-schema-views/views-transact-sql" rel="noreferrer">VIEWS</a> </li>
</ul> | {
"question_id": 1054984,
"question_date": "2009-06-28T14:05:50.193Z",
"question_score": 935,
"tags": "sql|sql-server|sql-server-2008|tsql",
"answer_id": 1054988,
"answer_date": "2009-06-28T14:08:35.727Z",
"answer_score": 1147
} |
Please answer the following Stack Overflow question:
Title: How to change the color of an svg element?
<p>I want to <a href="http://css-tricks.com/svg-fallbacks/" rel="noreferrer">use this technique</a> and change the SVG color, but so far I haven't been able to do so. I put this in the CSS, but my image is always black, no matter what.</p>
<p>My code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.change-my-color {
fill: green;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg>
<image class="change-my-color" xlink:href="https://svgur.com/i/AFM.svg" width="96" height="96" src="ppngfallback.png" />
</svg></code></pre>
</div>
</div>
</p> | <p>You can't change the color of an image that way. If you load SVG as an image, you can't change how it is displayed using CSS or Javascript in the browser.</p>
<p>If you want to change your SVG image, you have to load it using <code><object></code>, <code><iframe></code> or using <code><svg></code> inline.</p>
<p>If you want to use the techniques in the page, you need the Modernizr library, where you can check for SVG support and conditionally display or not a fallback image. You can then inline your SVG and apply the styles you need.</p>
<p>See :</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-css lang-css prettyprint-override"><code>#time-3-icon {
fill: green;
}
.my-svg-alternate {
display: none;
}
.no-svg .my-svg-alternate {
display: block;
width: 100px;
height: 100px;
background-image: url(image.png);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg width="96px" height="96px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
<path id="time-3-icon" d="M256,50C142.229,50,50,142.229,50,256c0,113.77,92.229,206,206,206c113.77,0,206-92.23,206-206
C462,142.229,369.77,50,256,50z M256,417c-88.977,0-161-72.008-161-161c0-88.979,72.008-161,161-161c88.977,0,161,72.007,161,161
C417,344.977,344.992,417,256,417z M382.816,265.785c1.711,0.297,2.961,1.781,2.961,3.518v0.093c0,1.72-1.223,3.188-2.914,3.505
c-37.093,6.938-124.97,21.35-134.613,21.35c-13.808,0-25-11.192-25-25c0-9.832,14.79-104.675,21.618-143.081
c0.274-1.542,1.615-2.669,3.181-2.669h0.008c1.709,0,3.164,1.243,3.431,2.932l18.933,119.904L382.816,265.785z"/>
</svg>
<image class="my-svg-alternate" width="96" height="96" src="ppngfallback.png" /></code></pre>
</div>
</div>
</p>
<p>You can inline your SVG, tag your fallback image with a class name (<code>my-svg-alternate</code>):</p>
<pre><code><svg width="96px" height="96px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
<path id="time-3-icon" .../>
</svg>
<image class="my-svg-alternate" width="96" height="96" src="ppngfallback.png" />
</code></pre>
<p>And in CSS use the <code>no-svg</code> class from Modernizr (CDN: <a href="http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.7.2.js" rel="noreferrer">http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.7.2.js</a> ) to check for SVG support. If there is no SVG support the SVG block will be ignored and the image will be displayed, otherwise the image will be removed from the DOM tree (<code>display: none</code>):</p>
<pre><code>.my-svg-alternate {
display: none;
}
.no-svg .my-svg-alternate {
display: block;
width: 100px;
height: 100px;
background-image: url(image.png);
}
</code></pre>
<p>Then you can change the color of your inlined element:</p>
<pre><code>#time-3-icon {
fill: green;
}
</code></pre> | {
"question_id": 22252472,
"question_date": "2014-03-07T14:15:03.877Z",
"question_score": 935,
"tags": "css|svg|colors",
"answer_id": 22253046,
"answer_date": "2014-03-07T14:39:04.750Z",
"answer_score": 324
} |
Please answer the following Stack Overflow question:
Title: How do I get the Git commit count?
<p>I'd like to get the number of commits of my Git repository, a bit like SVN revision numbers.</p>
<p>The goal is to use it as a unique, incrementing build number.</p>
<p>I currently do like that, on Unix/Cygwin/msysGit:</p>
<pre><code>git log --pretty=format:'' | wc -l
</code></pre>
<p>But I feel it's a bit of a hack.</p>
<p>Is there a better way to do that? It would be cool if I actually didn't need <code>wc</code> or even Git, so it could work on a bare Windows. Just read a file or a directory structure...</p> | <p>To get a commit count for a revision (<code>HEAD</code>, <code>master</code>, a commit hash):</p>
<pre><code>git rev-list --count <revision>
</code></pre>
<p>To get the commit count across all branches:</p>
<pre><code>git rev-list --all --count
</code></pre>
<p>I recommend against using this for build identifier, but if you must, it's probably best to use the count for the branch you're building against. That way the same revision will always have the same number. If you use the count for all branches, activity on other branches could change the number.</p> | {
"question_id": 677436,
"question_date": "2009-03-24T13:38:55.390Z",
"question_score": 935,
"tags": "git|build-process|revision",
"answer_id": 4061706,
"answer_date": "2010-10-31T03:21:03.933Z",
"answer_score": 1432
} |
Please answer the following Stack Overflow question:
Title: What's the difference between an argument and a parameter?
<p>When verbally talking about methods, I'm never sure whether to use the word <em>argument</em> or <em>parameter</em> or something else. Either way the other people know what I mean, but what's correct, and what's the history of the terms?</p>
<p>I'm a C# programmer, but I also wonder whether people use different terms in different languages.</p>
<p>For the record I'm self-taught without a background in Computer Science. (Please don't tell me to read <a href="http://www.amazon.co.uk/Code-Complete-Practical-Handbook-Construction/dp/0735619670/" rel="noreferrer">Code Complete</a> because I'm asking this for the benefit of other people who don't already have a copy of <a href="http://www.stevemcconnell.com/" rel="noreferrer">Steve McConnell</a>'s marvellous book.)</p>
<h3>Summary</h3>
<p>The general consensus seems to be that it's OK to use these terms interchangeably in a team environment. Except perhaps when you're defining the precise terminology; then you can also use "<em>formal</em> argument/parameter" and "<em>actual</em> argument/parameter" to disambiguate.</p> | <p>A parameter is a variable in a method definition. When a method is called, the arguments are the data you pass into the method's parameters.</p>
<pre><code>public void MyMethod(string myParam) { }
...
string myArg1 = "this is my argument";
myClass.MyMethod(myArg1);
</code></pre> | {
"question_id": 156767,
"question_date": "2008-10-01T08:57:20.130Z",
"question_score": 935,
"tags": "parameters|language-agnostic|arguments|terminology",
"answer_id": 156787,
"answer_date": "2008-10-01T09:03:34.763Z",
"answer_score": 1211
} |
Please answer the following Stack Overflow question:
Title: How do I remove version tracking from a project cloned from git?
<p>I want to remove all version tracking from a project's directory.</p>
<p>What is the correct method to do this?</p>
<p>Can I do a shell command such as:</p>
<pre><code>rm -rf .git
</code></pre>
<p>from my projects directory or is there a way to do this as a Git command?</p>
<p>I used this project to learn Git and realize I made some mistakes early on in the project with moved, renamed and deleted files. I'd like to remove all Git tracking and start fresh with <code>git init</code>.</p> | <p>All the data Git uses for information is stored in <code>.git/</code>, so removing it should work just fine. Of course, make sure that your working copy is in the exact state that you want it, because everything else will be lost. <code>.git</code> folder is hidden so make sure you turn on the "Show hidden files, folders and disks" option.</p>
<p>From there, you can run <code>git init</code> to create a fresh repository.</p> | {
"question_id": 4754152,
"question_date": "2011-01-21T00:12:09.380Z",
"question_score": 934,
"tags": "git|git-track",
"answer_id": 4754175,
"answer_date": "2011-01-21T00:15:56.247Z",
"answer_score": 937
} |
Please answer the following Stack Overflow question:
Title: How to get first N number of elements from an array
<p>I am working with Javascript(ES6) /FaceBook react and trying to get the first 3 elements of an array that varies in size. I would like do the equivalent of Linq take(n).</p>
<p>In my Jsx file I have the following:</p>
<pre><code>var items = list.map(i => {
return (
<myview item={i} key={i.id} />
);
});
</code></pre>
<p>Then to get the first 3 items I tried</p>
<pre><code> var map = new Map(list);
map.size = 3;
var items = map(i => {
return (<SpotlightLandingGlobalInboxItem item={i} key={i.id} />);
});
</code></pre>
<p>This didn't work as map doesn't have a set function.</p>
<p>Can you please help?</p> | <p>I believe what you're looking for is:</p>
<pre><code>// ...inside the render() function
var size = 3;
var items = list.slice(0, size).map(i => {
return <myview item={i} key={i.id} />
});
return (
<div>
{items}
</div>
)
</code></pre> | {
"question_id": 34883068,
"question_date": "2016-01-19T17:19:18.270Z",
"question_score": 934,
"tags": "javascript|arrays|filtering|slice|extract",
"answer_id": 34883368,
"answer_date": "2016-01-19T17:33:37.723Z",
"answer_score": 814
} |
Please answer the following Stack Overflow question:
Title: Prevent users from submitting a form by hitting Enter
<p>I have a survey on a website, and there seems to be some issues with the users hitting enter (I don't know why) and accidentally submitting the survey (form) without clicking the submit button. Is there a way to prevent this? </p>
<p>I'm using HTML, PHP 5.2.9, and jQuery on the survey.</p> | <p>You can use a method such as</p>
<pre><code>$(document).ready(function() {
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
});
</code></pre>
<p>In reading the comments on the original post, to make it more usable and allow people to press <kbd>Enter</kbd> if they have completed all the fields:</p>
<pre><code>function validationFunction() {
$('input').each(function() {
...
}
if(good) {
return true;
}
return false;
}
$(document).ready(function() {
$(window).keydown(function(event){
if( (event.keyCode == 13) && (validationFunction() == false) ) {
event.preventDefault();
return false;
}
});
});
</code></pre> | {
"question_id": 895171,
"question_date": "2009-05-21T21:09:25.070Z",
"question_score": 934,
"tags": "jquery|html|forms|form-submit",
"answer_id": 895231,
"answer_date": "2009-05-21T21:19:10.760Z",
"answer_score": 1008
} |
Please answer the following Stack Overflow question:
Title: psql: FATAL: database "<user>" does not exist
<p>I'm using the PostgreSql app for mac (<a href="http://postgresapp.com/" rel="noreferrer">http://postgresapp.com/</a>). I've used it in the past on other machines but it's giving me some trouble when installing on my macbook. I've installed the application and I ran:</p>
<pre><code>psql -h localhost
</code></pre>
<p>It returns:</p>
<pre><code>psql: FATAL: database "<user>" does not exist
</code></pre>
<p>It seems I can't even run the console to create the database that it's attempting to find. The same thing happens when I just run:</p>
<pre><code>psql
</code></pre>
<p>or if I launch psql from the application drop down menu:</p>
<p>Machine stats:</p>
<ul>
<li><p>OSX 10.8.4</p></li>
<li><p>psql (PostgreSQL) 9.2.4</p></li>
</ul>
<p>Any help is appreciated. </p>
<p>I've also attempted to install PostgreSql via homebrew and I'm getting the same issue. I've also read the applications documentation page that states: </p>
<blockquote>
<p>When Postgres.app first starts up, it creates the $USER database,
which is the default database for psql when none is specified. The
default user is $USER, with no password.</p>
</blockquote>
<p>So it would seem the application is not creating $USER however I've installed->uninstalled-reinstalled several times now so it must be something with my machine.</p>
<p>I found the answer but I'm not sure exactly how it works as the user who answered on this thread -> <a href="https://stackoverflow.com/questions/13515834/getting-postgresql-running-in-mac-database-postgres-does-not-exist">Getting Postgresql Running In Mac: Database "postgres" does not exist</a> didn't follow up. I used the following command to get psql to open: </p>
<pre><code>psql -d template1
</code></pre>
<p><em>I'll leave this one unanswered until someone can provide an explanation for why this works.</em></p> | <p>It appears that your package manager failed to create the database named $user for you. The reason that</p>
<pre><code>psql -d template1
</code></pre>
<p>works for you is that template1 is a database created by postgres itself, and is present on all installations.
You are apparently able to log in to template1, so you must have some rights assigned to you by the database. Try this at a shell prompt:</p>
<pre><code>createdb
</code></pre>
<p>and then see if you can log in again with </p>
<pre><code>psql -h localhost
</code></pre>
<p>This will simply create a database for your login user, which I think is what you are looking for. If createdb fails, then you don't have enough rights to make your own database, and you will have to figure out how to fix the homebrew package.</p> | {
"question_id": 17633422,
"question_date": "2013-07-13T19:18:24.400Z",
"question_score": 934,
"tags": "postgresql|psql",
"answer_id": 17936043,
"answer_date": "2013-07-29T23:40:57.067Z",
"answer_score": 1418
} |
Please answer the following Stack Overflow question:
Title: How to open a Bootstrap modal window using jQuery?
<p>I'm using Twitter Bootstrap modal window functionality. When someone clicks submit on my form, I want to show the modal window upon clicking the "submit button" in the form.</p>
<pre><code><form id="myform" class="form-wizard">
<h2 class="form-wizard-heading">BootStap Wizard Form</h2>
<input type="text" value=""/>
<input type="submit"/>
</form>
<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<p>One fine body…</p>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
</code></pre>
<p>jQuery:</p>
<pre><code>$('#myform').on('submit', function(ev) {
$('#my-modal').modal({
show: 'false'
});
var data = $(this).serializeObject();
json_data = JSON.stringify(data);
$("#results").text(json_data);
$(".modal-body").text(json_data);
// $("#results").text(data);
ev.preventDefault();
});
</code></pre> | <p>Bootstrap has a few functions that can be called manually on modals:</p>
<pre><code>$('#myModal').modal('toggle');
$('#myModal').modal('show');
$('#myModal').modal('hide');
</code></pre>
<p>You can see more here: <a href="https://getbootstrap.com/docs/3.4/javascript/#modals" rel="noreferrer">Bootstrap modal component</a></p>
<p>Specifically the <a href="http://getbootstrap.com/javascript/#modals-methods" rel="noreferrer">methods section</a>.</p>
<p>So you would need to change:</p>
<pre><code>$('#my-modal').modal({
show: 'false'
});
</code></pre>
<p>to:</p>
<pre><code>$('#myModal').modal('show');
</code></pre>
<p>If you're looking to make a custom popup of your own, here's a suggested video from another community member:</p>
<p><a href="https://www.youtube.com/watch?v=zK4nXa84Km4" rel="noreferrer">https://www.youtube.com/watch?v=zK4nXa84Km4</a></p> | {
"question_id": 13183630,
"question_date": "2012-11-01T18:52:18.547Z",
"question_score": 933,
"tags": "javascript|jquery|twitter-bootstrap",
"answer_id": 13183713,
"answer_date": "2012-11-01T18:57:05.317Z",
"answer_score": 1704
} |
Please answer the following Stack Overflow question:
Title: How to remove items from a list while iterating?
<p>I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. </p>
<pre><code>for tup in somelist:
if determine(tup):
code_to_remove_tup
</code></pre>
<p>What should I use in place of <code>code_to_remove_tup</code>? I can't figure out how to remove the item in this fashion.</p> | <p>You can use a list comprehension to create a new list containing only the elements you don't want to remove:</p>
<pre><code>somelist = [x for x in somelist if not determine(x)]
</code></pre>
<p>Or, by assigning to the slice <code>somelist[:]</code>, you can mutate the existing list to contain only the items you want:</p>
<pre><code>somelist[:] = [x for x in somelist if not determine(x)]
</code></pre>
<p>This approach could be useful if there are other references to <code>somelist</code> that need to reflect the changes.</p>
<p>Instead of a comprehension, you could also use <code>itertools</code>. In Python 2:</p>
<pre><code>from itertools import ifilterfalse
somelist[:] = ifilterfalse(determine, somelist)
</code></pre>
<p>Or in Python 3:</p>
<pre><code>from itertools import filterfalse
somelist[:] = filterfalse(determine, somelist)
</code></pre> | {
"question_id": 1207406,
"question_date": "2009-07-30T15:36:42.273Z",
"question_score": 933,
"tags": "python|iteration",
"answer_id": 1207461,
"answer_date": "2009-07-30T15:41:33.183Z",
"answer_score": 1041
} |
Please answer the following Stack Overflow question:
Title: How do I change Eclipse to use spaces instead of tabs?
<p>By default <a href="http://en.wikipedia.org/wiki/Eclipse_%28software%29" rel="noreferrer">Eclipse</a> indents with a hard tab character. How do I change it to spaces?</p> | <h3>Java Editor</h3>
<ol>
<li>Click <strong>Window</strong> » <strong>Preferences</strong></li>
<li>Expand <strong>Java</strong> » <strong>Code Style</strong></li>
<li>Click <strong>Formatter</strong></li>
<li>Click the <strong>Edit</strong> button</li>
<li>Click the <strong>Indentation</strong> tab</li>
<li>Under <strong>General Settings</strong>, set <strong>Tab policy</strong> to: <code>Spaces only</code></li>
<li>Click <strong>OK</strong> ad nauseam to apply the changes.</li>
</ol>
<p>[<strong><em>Note</em></strong>: If necessary save profile with a new name as the default profile cannot be overwritten.]</p>
<h3>Default Text Editor</h3>
<p>Before version 3.6:</p>
<pre><code>Window->Preferences->Editors->Text Editors->Insert spaces for tabs
</code></pre>
<p>Version 3.6 and later:</p>
<ol>
<li>Click <strong>Window</strong> » <strong>Preferences</strong></li>
<li>Expand <strong>General</strong> » <strong>Editors</strong></li>
<li>Click <strong>Text Editors</strong></li>
<li>Check <strong>Insert spaces for tabs</strong></li>
<li>Click <strong>OK</strong> ad nauseam to apply the changes.</li>
</ol>
<p>Note that the default text editor is used as the basis for many non-Java editors in Eclipse. It's astonishing that this setting wasn't available until 3.3.</p>
<h3>C / C++</h3>
<ol>
<li>Click <strong>Window</strong> » <strong>Preferences</strong></li>
<li>Expand <strong>C/C++</strong> » <strong>Code Style</strong></li>
<li>Click <strong>Formatter</strong></li>
<li>Click the <strong>New</strong> button to create a new profile, then <strong>OK</strong> to continue</li>
<li>Click the <strong>Indentation</strong> tab</li>
<li>Under <strong>General Settings</strong>, set <strong>Tab policy</strong> to: <code>Spaces only</code></li>
<li>Click <strong>OK</strong> ad nauseam to apply the changes.</li>
</ol>
<h3>HTML</h3>
<ol>
<li>Click <strong>Window</strong> » <strong>Preferences</strong></li>
<li>Expand <strong>Web</strong> » <strong>HTML Files</strong></li>
<li>Click <strong>Editor</strong></li>
<li>Under <strong>Formatting</strong>, select the <strong>Indent using spaces</strong> radio button</li>
<li>Click <strong>OK</strong> to apply the changes.</li>
</ol>
<h3>CSS</h3>
<p>Follow the same instructions for HTML, but select <strong>CSS Files</strong> instead of <strong>HTML Files</strong>.</p>
<h3>JSP</h3>
<p>By default, JSP files follow the formatting preferences for HTML Files.</p>
<h3>XML</h3>
<p>XML files spacing is configured in Preferences.</p>
<ol>
<li>Click <strong>Window</strong> » <strong>Preferences</strong></li>
<li>Expand <strong>XML</strong> » <strong>XML Files</strong></li>
<li>Click <strong>Editor</strong></li>
<li>Select <strong>Indent using spaces</strong></li>
<li>You can specify the <strong>Indentation size</strong> if needed: number of spaces to indent.</li>
</ol> | {
"question_id": 407929,
"question_date": "2009-01-02T20:21:47.543Z",
"question_score": 933,
"tags": "eclipse|formatting|tabs|whitespace",
"answer_id": 408449,
"answer_date": "2009-01-03T01:32:54.310Z",
"answer_score": 1283
} |
Please answer the following Stack Overflow question:
Title: Unit Testing C Code
<p>I worked on an embedded system this summer written in straight C. It was an existing project that the company I work for had taken over. I have become quite accustomed to writing unit tests in Java using JUnit but was at a loss as to the best way to write unit tests for existing code (which needed refactoring) as well as new code added to the system.</p>
<p>Are there any projects out there that make unit testing plain C code as easy as unit testing Java code with JUnit? Any insight that would apply specifically to embedded development (cross-compiling to arm-linux platform) would be greatly appreciated.</p> | <p>One unit testing framework in C is <a href="https://libcheck.github.io/check/" rel="noreferrer">Check</a>; a list of unit testing frameworks in C can be found <a href="http://check.sourceforge.net/doc/check_html/check_2.html#SEC3" rel="noreferrer">here</a> and is reproduced below. Depending on how many standard library functions your runtime has, you may or not be able to use one of those.</p>
<blockquote>
<h3>AceUnit</h3>
<p>AceUnit (Advanced C and Embedded Unit) bills itself as a comfortable C code unit test framework. It tries to mimick JUnit 4.x and includes reflection-like capabilities. AceUnit can be used in resource constraint environments, e.g. embedded software development, and importantly it runs fine in environments where you cannot include a single standard header file and cannot invoke a single standard C function from the ANSI / ISO C libraries. It also has a Windows port. It does not use forks to trap signals, although the authors have expressed interest in adding such a feature. See the <a href="http://aceunit.sourceforge.net/" rel="noreferrer">AceUnit homepage</a>.</p>
<h3>GNU Autounit</h3>
<p>Much along the same lines as Check, including forking to run unit tests in a separate address space (in fact, the original author of Check borrowed the idea from GNU Autounit). GNU Autounit uses GLib extensively, which means that linking and such need special options, but this may not be a big problem to you, especially if you are already using GTK or GLib. See the <a href="http://autounit.tigris.org/" rel="noreferrer">GNU Autounit homepage</a>.</p>
<h3>cUnit</h3>
<p>Also uses GLib, but does not fork to protect the address space of unit tests.</p>
<h3>CUnit</h3>
<p>Standard C, with plans for a Win32 GUI implementation. Does not currently fork or otherwise protect the address space of unit tests. In early development. See the <a href="http://cunit.sourceforge.net/" rel="noreferrer">CUnit homepage</a>.</p>
<h3>CuTest</h3>
<p>A simple framework with just one .c and one .h file that you drop into your source tree. See the <a href="http://cutest.sourceforge.net/" rel="noreferrer">CuTest homepage</a>.</p>
<h3>CppUnit</h3>
<p>The premier unit testing framework for C++; you can also use it to test C code. It is stable, actively developed, and has a GUI interface. The primary reasons not to use CppUnit for C are first that it is quite big, and second you have to write your tests in C++, which means you need a C++ compiler. If these don’t sound like concerns, it is definitely worth considering, along with other C++ unit testing frameworks. See the <a href="http://cppunit.sourceforge.net/doc/cvs/index.html" rel="noreferrer">CppUnit homepage</a>.</p>
<h3>embUnit</h3>
<p>embUnit (Embedded Unit) is another unit test framework for embedded systems. This one appears to be superseded by AceUnit. <a href="http://sourceforge.net/projects/embunit/" rel="noreferrer">Embedded Unit homepage</a>.</p>
<h3>MinUnit</h3>
<p>A minimal set of macros and that’s it! The point is to show how easy it is to unit test your code. See the <a href="http://www.jera.com/techinfo/jtns/jtn002.html" rel="noreferrer">MinUnit homepage</a>.</p>
<h3>CUnit for Mr. Ando</h3>
<p>A CUnit implementation that is fairly new, and apparently still in early development. See the <a href="http://park.ruru.ne.jp/ando/work/CUnitForAndo/html/" rel="noreferrer">CUnit for Mr. Ando homepage</a>.</p>
<p><em>This list was last updated in March 2008.</em></p>
</blockquote>
<h2>More frameworks:</h2>
<h3>CMocka</h3>
<p>CMocka is a test framework for C with support for mock objects. It's easy to use and setup.</p>
<p>See <a href="https://cmocka.org/" rel="noreferrer">the CMocka homepage</a>.</p>
<h3>Criterion</h3>
<p>Criterion is a cross-platform C unit testing framework supporting automatic test registration, parameterized tests, theories, and that can output to multiple formats, including TAP and JUnit XML. Each test is run in its own process, so signals and crashes can be reported or tested if needed.</p>
<p>See the <a href="https://github.com/Snaipe/Criterion" rel="noreferrer">Criterion homepage</a> for more information.</p>
<h3>HWUT</h3>
<p>HWUT is a general Unit Test tool with great support for C. It can help to create Makefiles, generate massive test cases coded in minimal 'iteration tables', walk along state machines, generate C-stubs and more. The general approach is pretty unique: Verdicts are based on 'good stdout/bad stdout'. The comparison function, though, is flexible. Thus, any type of script may be used for checking. It may be applied to any language that can produce standard output.</p>
<p>See <a href="http://hwut.sourceforge.net/" rel="noreferrer">the HWUT homepage</a>.</p>
<h3>CGreen</h3>
<p>A modern, portable, cross-language unit testing and mocking framework for C and C++. It offers an optional BDD notation, a mocking library, the ability to run it in a single process (to make debugging easier). A test runner which discover automatically the test functions is available. But you can create your own programmatically.</p>
<p>All those features (and more) are explained in <a href="https://cgreen-devs.github.io/" rel="noreferrer">the CGreen manual</a>.</p>
<p>Wikipedia gives a detailed list of C unit testing frameworks under <a href="https://en.wikipedia.org/wiki/List_of_unit_testing_frameworks#C" rel="noreferrer">List of unit testing frameworks: C</a></p> | {
"question_id": 65820,
"question_date": "2008-09-15T19:12:00.383Z",
"question_score": 933,
"tags": "c|unit-testing|testing|embedded",
"answer_id": 65845,
"answer_date": "2008-09-15T19:14:36.837Z",
"answer_score": 546
} |
Please answer the following Stack Overflow question:
Title: How can I parse a YAML file in Python
<p>How can I parse a YAML file in Python?</p> | <p>The easiest and purest method without relying on C headers is PyYaml (<a href="http://pyyaml.org/wiki/PyYAMLDocumentation" rel="noreferrer">documentation</a>), which can be installed via <strong><code>pip install pyyaml</code></strong>:</p>
<pre><code>#!/usr/bin/env python
import yaml
with open("example.yaml", "r") as stream:
try:
print(yaml.safe_load(stream))
except yaml.YAMLError as exc:
print(exc)
</code></pre>
<p>And that's it. A plain <code>yaml.load()</code> function also exists, but <code>yaml.safe_load()</code> should always be preferred to avoid introducing the possibility for arbitrary code execution. So unless you explicitly need the arbitrary object serialization/deserialization use <code>safe_load</code>.</p>
<p>Note the PyYaml project supports versions up through the <a href="https://yaml.org/spec/1.1/spec.html" rel="noreferrer">YAML 1.1 specification</a>. If <a href="https://yaml.org/spec/1.2/spec.html" rel="noreferrer">YAML 1.2 specification</a> support is needed, see <a href="https://yaml.readthedocs.io/" rel="noreferrer">ruamel.yaml</a> as noted in <a href="https://stackoverflow.com/a/38922434/313192">this answer</a>.</p>
<p>Also, you could also use a drop in replacement for pyyaml, that keeps your yaml file ordered <em>the same way you had it</em>, called <a href="https://github.com/wimglenn/oyaml" rel="noreferrer">oyaml</a>. View <a href="https://snyk.io/advisor/python/oyaml" rel="noreferrer">synk of oyaml here</a></p> | {
"question_id": 1773805,
"question_date": "2009-11-20T23:16:16Z",
"question_score": 932,
"tags": "python|yaml",
"answer_id": 1774043,
"answer_date": "2009-11-21T00:23:34.290Z",
"answer_score": 1243
} |
Please answer the following Stack Overflow question:
Title: How to hide the title bar for an Activity in XML with existing custom theme
<p>I want to hide the titlebar for some of my activities. The problem is that I applied a style to all my activities, therefore I can't simply set the theme to <code>@android:style/Theme.NoTitleBar</code>. </p>
<p>Using the <strong>NoTitleBar</strong> theme as a parent for my style would remove the title bar from all of my activities.</p>
<p>Can I set a no title style item somewhere?</p> | <p>I now did the following. </p>
<p>I declared a style inheriting everything from my general style and then disabling the titleBar.</p>
<pre><code><style name="generalnotitle" parent="general">
<item name="android:windowNoTitle">true</item>
</style>
</code></pre>
<p>Now I can set this style to every Activity in which I want to hide the title bar overwriting the application wide style and inheriting all the other style informations, therefor no duplication in the style code.</p>
<p>To apply the style to a particular Activity, open <code>AndroidManifest.xml</code> and add the following attribute to the <code>activity</code> tag;</p>
<pre><code><activity
android:theme="@style/generalnotitle">
</code></pre> | {
"question_id": 2591036,
"question_date": "2010-04-07T08:48:22.113Z",
"question_score": 932,
"tags": "android|android-layout|titlebar",
"answer_id": 2627952,
"answer_date": "2010-04-13T08:15:29.667Z",
"answer_score": 404
} |
Please answer the following Stack Overflow question:
Title: Sorting object property by values
<p>If I have a JavaScript object such as:</p>
<pre><code>var list = {
"you": 100,
"me": 75,
"foo": 116,
"bar": 15
};
</code></pre>
<p>Is there a way to sort the properties based on value? So that I end up with</p>
<pre><code>list = {
"bar": 15,
"me": 75,
"you": 100,
"foo": 116
};
</code></pre> | <p>Move them to an array, sort that array, and then use that array for your purposes. Here's a solution:</p>
<pre><code>let maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
let sortable = [];
for (var vehicle in maxSpeed) {
sortable.push([vehicle, maxSpeed[vehicle]]);
}
sortable.sort(function(a, b) {
return a[1] - b[1];
});
// [["bike", 60], ["motorbike", 200], ["car", 300],
// ["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]
</code></pre>
<hr />
<p>Once you have the array, you could rebuild the object from the array in the order you like, thus achieving exactly what you set out to do. That would work in all the browsers I know of, but it would be dependent on an implementation quirk, and could break at any time. You should never make assumptions about the order of elements in a JavaScript object.</p>
<pre><code>let objSorted = {}
sortable.forEach(function(item){
objSorted[item[0]]=item[1]
})
</code></pre>
<hr />
<p>In ES8, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce" rel="noreferrer"><code>Object.entries()</code></a> to convert the object into an array:</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>const maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
const sortable = Object.entries(maxSpeed)
.sort(([,a],[,b]) => a-b)
.reduce((r, [k, v]) => ({ ...r, [k]: v }), {});
console.log(sortable);</code></pre>
</div>
</div>
</p>
<hr />
<p>In ES10, you can use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries" rel="noreferrer"><code>Object.fromEntries()</code></a> to convert array to object. Then the code can be simplified to this:</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>const maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
const sortable = Object.fromEntries(
Object.entries(maxSpeed).sort(([,a],[,b]) => a-b)
);
console.log(sortable);</code></pre>
</div>
</div>
</p> | {
"question_id": 1069666,
"question_date": "2009-07-01T15:06:40.677Z",
"question_score": 931,
"tags": "javascript|sorting|properties|object",
"answer_id": 1069840,
"answer_date": "2009-07-01T15:33:11.497Z",
"answer_score": 999
} |
Please answer the following Stack Overflow question:
Title: Remove blue border from css custom-styled button in Chrome
<p>I'm working on a web page, and I want custom-styled <code><button></code> tags. So with CSS, I said: <code>border: none</code>. Now it works perfectly in safari, but in chrome, when I click one of the buttons, it puts an annoying blue border around it. I thought <code>button:active { outline: none }</code> or <code>button:focus { outline:none }</code> would work, but neither do. Any ideas? </p>
<p>This is what it looks like before being clicked (and how I want it to still look after being clicked):</p>
<p><img src="https://i.stack.imgur.com/WVZZe.png" alt=""></p>
<p>And this is the border I'm talking about:</p>
<p><img src="https://i.stack.imgur.com/XwWNF.png" alt="enter image description here"></p>
<p>Here is my CSS:</p>
<pre><code>button.launch {
background-color: #F9A300;
border: none;
height: 40px;
padding: 5px 15px;
color: #ffffff;
font-size: 16px;
font-weight: 300;
margin-top: 10px;
margin-right: 10px;
}
button.launch:hover {
cursor: pointer;
background-color: #FABD44;
}
button.change {
background-color: #F88F00;
border: none;
height: 40px;
padding: 5px 15px;
color: #ffffff;
font-size: 16px;
font-weight: 300;
margin-top: 10px;
margin-right: 10px;
}
button.change:hover {
cursor: pointer;
background-color: #F89900;
}
button:active {
outline: none;
border: none;
}
</code></pre> | <p>Doing this is <strong>not recommended</strong> as it regresses the <a href="https://developer.mozilla.org/en-US/docs/Learn/Accessibility/What_is_accessibility" rel="noreferrer">accessibility</a> of your site; for more info, see this <a href="https://a11yproject.com/posts/never-remove-css-outlines/" rel="noreferrer">post</a>.</p>
<p>That said, if you insist, this CSS should work:</p>
<pre><code>button:focus {outline:0;}
</code></pre>
<p>Check it out or JSFiddle: <a href="http://jsfiddle.net/u4pXu/" rel="noreferrer">http://jsfiddle.net/u4pXu/</a></p>
<p>Or in this snippet:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>button.launch {
background-color: #F9A300;
border: none;
height: 40px;
padding: 5px 15px;
color: #ffffff;
font-size: 16px;
font-weight: 300;
margin-top: 10px;
margin-right: 10px;
}
button.launch:hover {
cursor: pointer;
background-color: #FABD44;
}
button.launch {
background-color: #F9A300;
border: none;
height: 40px;
padding: 5px 15px;
color: #ffffff;
font-size: 16px;
font-weight: 300;
margin-top: 10px;
margin-right: 10px;
}
button.launch:hover {
cursor: pointer;
background-color: #FABD44;
}
button.change {
background-color: #F88F00;
border: none;
height: 40px;
padding: 5px 15px;
color: #ffffff;
font-size: 16px;
font-weight: 300;
margin-top: 10px;
margin-right: 10px;
}
button.change:hover {
cursor: pointer;
background-color: #F89900;
}
button:active {
outline: none;
border: none;
}
button:focus {outline:0;}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="launch">Launch with these ads</button>
<button class="change">Change</button></code></pre>
</div>
</div>
</p> | {
"question_id": 20340138,
"question_date": "2013-12-02T23:45:23.927Z",
"question_score": 931,
"tags": "css|google-chrome",
"answer_id": 21758143,
"answer_date": "2014-02-13T15:15:15.833Z",
"answer_score": 1733
} |
Please answer the following Stack Overflow question:
Title: Is there any way to kill a Thread?
<p>Is it possible to terminate a running thread without setting/checking any flags/semaphores/etc.?</p> | <p>It is generally a bad pattern to kill a thread abruptly, in Python, and in any language. Think of the following cases:</p>
<ul>
<li>the thread is holding a critical resource that must be closed properly</li>
<li>the thread has created several other threads that must be killed as well.</li>
</ul>
<p>The nice way of handling this, if you can afford it (if you are managing your own threads), is to have an exit_request flag that each thread checks on a regular interval to see if it is time for it to exit.</p>
<p><strong>For example:</strong></p>
<pre><code>import threading
class StoppableThread(threading.Thread):
"""Thread class with a stop() method. The thread itself has to check
regularly for the stopped() condition."""
def __init__(self, *args, **kwargs):
super(StoppableThread, self).__init__(*args, **kwargs)
self._stop_event = threading.Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
</code></pre>
<p>In this code, you should call <code>stop()</code> on the thread when you want it to exit, and wait for the thread to exit properly using <code>join()</code>. The thread should check the stop flag at regular intervals.</p>
<p>There are cases, however, when you really need to kill a thread. An example is when you are wrapping an external library that is busy for long calls, and you want to interrupt it.</p>
<p>The following code allows (with some restrictions) to raise an Exception in a Python thread:</p>
<pre><code>def _async_raise(tid, exctype):
'''Raises an exception in the threads with id tid'''
if not inspect.isclass(exctype):
raise TypeError("Only types can be raised (not instances)")
res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid),
ctypes.py_object(exctype))
if res == 0:
raise ValueError("invalid thread id")
elif res != 1:
# "if it returns a number greater than one, you're in trouble,
# and you should call it again with exc=NULL to revert the effect"
ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)
raise SystemError("PyThreadState_SetAsyncExc failed")
class ThreadWithExc(threading.Thread):
'''A thread class that supports raising an exception in the thread from
another thread.
'''
def _get_my_tid(self):
"""determines this (self's) thread id
CAREFUL: this function is executed in the context of the caller
thread, to get the identity of the thread represented by this
instance.
"""
if not self.isAlive():
raise threading.ThreadError("the thread is not active")
# do we have it cached?
if hasattr(self, "_thread_id"):
return self._thread_id
# no, look for it in the _active dict
for tid, tobj in threading._active.items():
if tobj is self:
self._thread_id = tid
return tid
# TODO: in python 2.6, there's a simpler way to do: self.ident
raise AssertionError("could not determine the thread's id")
def raiseExc(self, exctype):
"""Raises the given exception type in the context of this thread.
If the thread is busy in a system call (time.sleep(),
socket.accept(), ...), the exception is simply ignored.
If you are sure that your exception should terminate the thread,
one way to ensure that it works is:
t = ThreadWithExc( ... )
...
t.raiseExc( SomeException )
while t.isAlive():
time.sleep( 0.1 )
t.raiseExc( SomeException )
If the exception is to be caught by the thread, you need a way to
check that your thread has caught it.
CAREFUL: this function is executed in the context of the
caller thread, to raise an exception in the context of the
thread represented by this instance.
"""
_async_raise( self._get_my_tid(), exctype )
</code></pre>
<p>(Based on <a href="http://tomerfiliba.com/recipes/Thread2/" rel="noreferrer">Killable Threads</a> by Tomer Filiba. The quote about the return value of <code>PyThreadState_SetAsyncExc</code> appears to be from an <a href="https://svn.python.org/projects/stackless/Python-2.4.3/dev/Python/pystate.c" rel="noreferrer">old version of Python</a>.)</p>
<p>As noted in the documentation, this is not a magic bullet because if the thread is busy outside the Python interpreter, it will not catch the interruption.</p>
<p>A good usage pattern of this code is to have the thread catch a specific exception and perform the cleanup. That way, you can interrupt a task and still have proper cleanup.</p> | {
"question_id": 323972,
"question_date": "2008-11-27T14:55:53.973Z",
"question_score": 930,
"tags": "python|multithreading|kill|terminate",
"answer_id": 325528,
"answer_date": "2008-11-28T11:19:54.063Z",
"answer_score": 804
} |
Please answer the following Stack Overflow question:
Title: Reverse / invert a dictionary mapping
<p>Given a dictionary like so:</p>
<pre><code>my_map = {'a': 1, 'b': 2}
</code></pre>
<p>How can one invert this map to get:</p>
<pre><code>inv_map = {1: 'a', 2: 'b'}
</code></pre> | <p>Python 3+:</p>
<pre><code>inv_map = {v: k for k, v in my_map.items()}
</code></pre>
<p>Python 2:</p>
<pre><code>inv_map = {v: k for k, v in my_map.iteritems()}
</code></pre> | {
"question_id": 483666,
"question_date": "2009-01-27T14:46:09.893Z",
"question_score": 930,
"tags": "python|dictionary|mapping|reverse",
"answer_id": 483833,
"answer_date": "2009-01-27T15:24:56.603Z",
"answer_score": 1342
} |
Please answer the following Stack Overflow question:
Title: What is the role of the bias in neural networks?
<p>I'm aware of the gradient descent and the back-propagation algorithm. What I don't get is: when is using a bias important and how do you use it?</p>
<p>For example, when mapping the <code>AND</code> function, when I use two inputs and one output, it does not give the correct weights. However, when I use three inputs (one of which is a bias), it gives the correct weights.</p> | <p>I think that biases are almost always helpful. In effect, <strong>a bias value allows you to shift the activation function to the left or right</strong>, which may be critical for successful learning.</p>
<p>It might help to look at a simple example. Consider this 1-input, 1-output network that has no bias:</p>
<p><img src="https://i.stack.imgur.com/bI2Tm.gif" alt="simple network"></p>
<p>The output of the network is computed by multiplying the input (x) by the weight (w<sub>0</sub>) and passing the result through some kind of activation function (e.g. a sigmoid function.)</p>
<p>Here is the function that this network computes, for various values of w<sub>0</sub>:</p>
<p><img src="https://i.stack.imgur.com/ddyfr.png" alt="network output, given different w0 weights"></p>
<p>Changing the weight w<sub>0</sub> essentially changes the "steepness" of the sigmoid. That's useful, but what if you wanted the network to output 0 when x is 2? Just changing the steepness of the sigmoid won't really work -- <strong>you want to be able to shift the entire curve to the right</strong>.</p>
<p>That's exactly what the bias allows you to do. If we add a bias to that network, like so:</p>
<p><img src="https://i.stack.imgur.com/oapHD.gif" alt="simple network with a bias"></p>
<p>...then the output of the network becomes sig(w<sub>0</sub>*x + w<sub>1</sub>*1.0). Here is what the output of the network looks like for various values of w<sub>1</sub>:</p>
<p><img src="https://i.stack.imgur.com/t2mC3.png" alt="network output, given different w1 weights"></p>
<p>Having a weight of -5 for w<sub>1</sub> shifts the curve to the right, which allows us to have a network that outputs 0 when x is 2.</p> | {
"question_id": 2480650,
"question_date": "2010-03-19T21:18:12.770Z",
"question_score": 930,
"tags": "machine-learning|neural-network|artificial-intelligence|backpropagation",
"answer_id": 2499936,
"answer_date": "2010-03-23T12:50:07.420Z",
"answer_score": 1528
} |
Please answer the following Stack Overflow question:
Title: Format JavaScript date as yyyy-mm-dd
<p>I have a date with the format <code>Sun May 11,2014</code>. How can I convert it to <code>2014-05-11</code> 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>function taskDate(dateMilli) {
var d = (new Date(dateMilli) + '').split(' ');
d[2] = d[2] + ',';
return [d[0], d[1], d[2], d[3]].join(' ');
}
var datemilli = Date.parse('Sun May 11,2014');
console.log(taskDate(datemilli));</code></pre>
</div>
</div>
</p>
<p>The code above gives me the same date format, <code>sun may 11,2014</code>. How can I fix this?</p> | <p>You can do:</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 formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
console.log(formatDate('Sun May 11,2014'));</code></pre>
</div>
</div>
</p>
<p>Usage example:</p>
<pre><code>console.log(formatDate('Sun May 11,2014'));
</code></pre>
<p>Output:</p>
<pre><code>2014-05-11
</code></pre>
<p>Demo on JSFiddle: <a href="http://jsfiddle.net/abdulrauf6182012/2Frm3/" rel="noreferrer">http://jsfiddle.net/abdulrauf6182012/2Frm3/</a></p> | {
"question_id": 23593052,
"question_date": "2014-05-11T13:13:16.763Z",
"question_score": 929,
"tags": "javascript|date|formatting|datetime-format|date-format",
"answer_id": 23593099,
"answer_date": "2014-05-11T13:18:18.870Z",
"answer_score": 906
} |
Please answer the following Stack Overflow question:
Title: How to make IPython notebook matplotlib plot inline
<p>I am trying to use IPython notebook on MacOS X with Python 2.7.2 and IPython 1.1.0.</p>
<p>I cannot get matplotlib graphics to show up inline.</p>
<pre><code>import matplotlib
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
</code></pre>
<p>I have also tried <code>%pylab inline</code> and the ipython command line arguments <code>--pylab=inline</code> but this makes no difference.</p>
<pre><code>x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp')
plt.show()
</code></pre>
<p>Instead of inline graphics, I get this:</p>
<pre><code><matplotlib.figure.Figure at 0x110b9c450>
</code></pre>
<p>And <code>matplotlib.get_backend()</code> shows that I have the <code>'module://IPython.kernel.zmq.pylab.backend_inline'</code> backend.</p> | <p>I used <code>%matplotlib inline</code> in the first cell of the notebook and it works. I think you should try:</p>
<pre><code>%matplotlib inline
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
</code></pre>
<p>You can also always start all your IPython kernels in inline mode by default by setting the following config options in your config files:</p>
<pre><code>c.IPKernelApp.matplotlib=<CaselessStrEnum>
Default: None
Choices: ['auto', 'gtk', 'gtk3', 'inline', 'nbagg', 'notebook', 'osx', 'qt', 'qt4', 'qt5', 'tk', 'wx']
Configure matplotlib for interactive use with the default matplotlib backend.
</code></pre> | {
"question_id": 19410042,
"question_date": "2013-10-16T17:34:42.860Z",
"question_score": 929,
"tags": "python|matplotlib|jupyter-notebook|ipython|data-visualization",
"answer_id": 24884342,
"answer_date": "2014-07-22T10:01:24.730Z",
"answer_score": 1225
} |
Please answer the following Stack Overflow question:
Title: Update a table using JOIN in SQL Server?
<p>I want to update a column in a table making a join on other table e.g.:</p>
<pre><code>UPDATE table1 a
INNER JOIN table2 b ON a.commonfield = b.[common field]
SET a.CalculatedColumn= b.[Calculated Column]
WHERE
b.[common field]= a.commonfield
AND a.BatchNO = '110'
</code></pre>
<p>But it is complaining :</p>
<blockquote>
<p>Msg 170, Level 15, State 1, Line 2<br>
Line 2: Incorrect syntax near 'a'.</p>
</blockquote>
<p>What is wrong here?</p> | <p>You don't quite have SQL Server's proprietary <code>UPDATE FROM</code> syntax down. Also not sure why you needed to join on the <code>CommonField</code> and also filter on it afterward. Try this:</p>
<pre><code>UPDATE t1
SET t1.CalculatedColumn = t2.[Calculated Column]
FROM dbo.Table1 AS t1
INNER JOIN dbo.Table2 AS t2
ON t1.CommonField = t2.[Common Field]
WHERE t1.BatchNo = '110';
</code></pre>
<p>If you're doing something silly - like constantly trying to set the value of one column to the aggregate of another column (which violates the principle of avoiding storing redundant data), you can use a CTE (common table expression) - see <a href="http://technet.microsoft.com/en-us/library/ms190766.aspx" rel="noreferrer">here</a> and <a href="https://blogs.sentryone.com/aaronbertrand/backtobasics-ctes/" rel="noreferrer">here</a> for more details:</p>
<pre><code>;WITH t2 AS
(
SELECT [key], CalculatedColumn = SUM(some_column)
FROM dbo.table2
GROUP BY [key]
)
UPDATE t1
SET t1.CalculatedColumn = t2.CalculatedColumn
FROM dbo.table1 AS t1
INNER JOIN t2
ON t1.[key] = t2.[key];
</code></pre>
<p>The reason this is silly, is that you're going to have to re-run this entire update every single time any row in <code>table2</code> changes. A <code>SUM</code> is something you can always calculate at runtime and, in doing so, never have to worry that the result is stale.</p> | {
"question_id": 1604091,
"question_date": "2009-10-21T22:48:11.393Z",
"question_score": 929,
"tags": "sql-server|tsql|join|sql-update",
"answer_id": 1604212,
"answer_date": "2009-10-21T23:26:03.607Z",
"answer_score": 1752
} |
Please answer the following Stack Overflow question:
Title: Convert hex string to integer in Python
<p>How do I convert a hex string to an integer?</p>
<pre><code>"0xffff" ⟶ 65535
"ffff" ⟶ 65535
</code></pre> | <p><strong>Without</strong> the <code>0x</code> prefix, you need to specify the base explicitly, otherwise there's no way to tell:</p>
<pre><code>x = int("deadbeef", 16)
</code></pre>
<p><strong>With</strong> the <code>0x</code> prefix, Python can distinguish hex and decimal automatically:</p>
<pre><code>>>> print(int("0xdeadbeef", 0))
3735928559
>>> print(int("10", 0))
10
</code></pre>
<p>(You <em>must</em> specify <code>0</code> as the base in order to invoke this prefix-guessing behavior; if you omit the second parameter, <a href="https://docs.python.org/library/functions.html#int" rel="noreferrer"><code>int()</code></a> will assume base-10.)</p> | {
"question_id": 209513,
"question_date": "2008-10-16T17:28:03.497Z",
"question_score": 928,
"tags": "python|string|hex",
"answer_id": 209550,
"answer_date": "2008-10-16T17:37:52.340Z",
"answer_score": 1352
} |
Please answer the following Stack Overflow question:
Title: How do I use Assert to verify that an exception has been thrown?
<p>How do I use <code>Assert</code> (or other Test class) to verify that an exception has been thrown?</p> | <p>For "Visual Studio Team Test" it appears you apply the ExpectedException attribute to the test's method.</p>
<p>Sample from the documentation here: <a href="http://msdn.microsoft.com/en-us/library/ms379625(VS.80).aspx#vstsunittesting_topic5" rel="noreferrer">A Unit Testing Walkthrough with Visual Studio Team Test</a></p>
<pre><code>[TestMethod]
[ExpectedException(typeof(ArgumentException),
"A userId of null was inappropriately allowed.")]
public void NullUserIdInConstructor()
{
LogonInfo logonInfo = new LogonInfo(null, "P@ss0word");
}
</code></pre> | {
"question_id": 933613,
"question_date": "2009-06-01T05:01:53.873Z",
"question_score": 928,
"tags": "c#|unit-testing|mstest|assert|vs-unit-testing-framework",
"answer_id": 933627,
"answer_date": "2009-06-01T05:09:23.320Z",
"answer_score": 1070
} |
Please answer the following Stack Overflow question:
Title: Is there a git-merge --dry-run option?
<p>I'm merging in a remote branch that may have a lot of conflicts. How can I tell if it will have conflicts or not?</p>
<p>I don't see anything like a <code>--dry-run</code> on <code>git-merge</code>. </p> | <p>As noted previously, pass in the <code>--no-commit</code> flag, but to avoid a fast-forward commit, also pass in <code>--no-ff</code>, like so:</p>
<pre><code>$ git merge --no-commit --no-ff $BRANCH
</code></pre>
<p>To examine the staged changes:</p>
<pre><code>$ git diff --cached
</code></pre>
<p>And you can undo the merge, even if it is a fast-forward merge:</p>
<pre><code>$ git merge --abort
</code></pre> | {
"question_id": 501407,
"question_date": "2009-02-01T19:18:26.810Z",
"question_score": 928,
"tags": "git|git-merge",
"answer_id": 501461,
"answer_date": "2009-02-01T19:57:26.980Z",
"answer_score": 1043
} |
Please answer the following Stack Overflow question:
Title: Error java.lang.OutOfMemoryError: GC overhead limit exceeded
<p>I get this error message as I execute my <code>JUnit</code> tests:</p>
<pre><code>java.lang.OutOfMemoryError: GC overhead limit exceeded
</code></pre>
<p>I know what an <code>OutOfMemoryError</code> is, but what does GC overhead limit mean? How can I solve this?</p> | <p>This message means that for some reason the garbage collector is taking an excessive amount of time (by default 98% of all CPU time of the process) and recovers very little memory in each run (by default 2% of the heap).</p>
<p>This effectively means that your program stops doing any progress and is busy running only the garbage collection at all time.</p>
<p>To prevent your application from soaking up CPU time without getting anything done, the JVM throws this <code>Error</code> so that you have a chance of diagnosing the problem.</p>
<p>The rare cases where I've seen this happen is where some code was creating tons of temporary objects and tons of weakly-referenced objects in an already very memory-constrained environment.</p>
<p>Check out the Java GC tuning guide, which is available for various Java versions and contains sections about this specific problem:</p>
<ul>
<li><a href="https://docs.oracle.com/en/java/javase/11/gctuning/" rel="noreferrer">Java 11 tuning guide</a> has dedicated sections on excessive GC for different garbage collectors:
<ul>
<li>for the <a href="https://docs.oracle.com/en/java/javase/11/gctuning/parallel-collector1.html#GUID-31F3D722-5F93-41D6-817A-C6B91C095B6F" rel="noreferrer">Parallel Collector</a></li>
<li>for the <a href="https://docs.oracle.com/en/java/javase/11/gctuning/concurrent-mark-sweep-cms-collector.html#GUID-8A7DC9B6-0448-4AC5-8F6D-41C83B6C618E" rel="noreferrer">Concurrent Mark Sweep (CMS) Collector</a></li>
<li>there is no mention of this specific error condition for the Garbage First (G1) collector.</li>
</ul></li>
<li><a href="https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/index.html" rel="noreferrer">Java 8 tuning guide</a> and its <a href="https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/parallel.html#parallel_collector_excessive_gc" rel="noreferrer">Excessive GC section</a></li>
<li><a href="http://www.oracle.com/technetwork/java/javase/gc-tuning-6-140523.html" rel="noreferrer">Java 6 tuning guide</a> and its <a href="http://www.oracle.com/technetwork/java/javase/gc-tuning-6-140523.html#par_gc.oom" rel="noreferrer">Excessive GC section</a>.</li>
</ul> | {
"question_id": 1393486,
"question_date": "2009-09-08T11:34:28.137Z",
"question_score": 927,
"tags": "java|garbage-collection|out-of-memory|heap-memory",
"answer_id": 1393503,
"answer_date": "2009-09-08T11:39:14.837Z",
"answer_score": 844
} |
Please answer the following Stack Overflow question:
Title: How can I force gradle to redownload dependencies?
<p>How can I tell gradle to redownload dependencies from repositories?</p> | <p>Generally, you can refresh dependencies in your cache with the command line option <a href="https://docs.gradle.org/current/userguide/dependency_management.html#sec:refreshing-dependencies" rel="noreferrer">--refresh-dependencies</a>. You can also delete the cached files under <code>~/.gradle/caches</code>. With the next build Gradle would attempt to download them again.</p>
<p>What is your specific use case? Do you use dynamic dependency versions or SNAPSHOT versions?</p>
<hr />
<p>On Unix systems, you can delete all the existing artifacts (artifacts and metadata) Gradle has downloaded using:</p>
<pre><code>rm -rf $HOME/.gradle/caches/
</code></pre>
<hr />
<p>Note that --refresh-dependencies won't always re-download every artifact; it will use existing copies if they match what exists in the repository. From the Gradle User Guide, <a href="https://docs.gradle.org/current/userguide/dependency_management.html#sec:refreshing-dependencies" rel="noreferrer">refreshing dependencies</a>:</p>
<blockquote>
<p>The --refresh-dependencies option tells Gradle to ignore all cached entries for resolved modules and artifacts. A fresh resolve will be performed against all configured repositories, with dynamic versions recalculated, modules refreshed, and artifacts downloaded. However, where possible Gradle will check if the previously downloaded artifacts are valid before downloading again. This is done by comparing published SHA1 values in the repository with the SHA1 values for existing downloaded artifacts.</p>
<p>[...]</p>
<p>It’s a common misconception to think that using --refresh-dependencies will force download of dependencies. This is not the case: Gradle will only perform what is strictly required to refresh the dynamic dependencies. This may involve downloading new listing or metadata files, or even artifacts, but if nothing changed, the impact is minimal.</p>
</blockquote> | {
"question_id": 13565082,
"question_date": "2012-11-26T12:42:41.970Z",
"question_score": 927,
"tags": "gradle",
"answer_id": 13567793,
"answer_date": "2012-11-26T15:21:12.527Z",
"answer_score": 1010
} |
Please answer the following Stack Overflow question:
Title: Easiest way to split a string on newlines in .NET?
<p>I need to split a string into newlines in .NET and the only way I know of to split strings is with the <a href="https://msdn.microsoft.com/en-us/library/system.string.split%28v=vs.110%29.aspx" rel="noreferrer">Split</a> method. However that will not allow me to (easily) split on a newline, so what is the best way to do it?</p> | <p>To split on a string you need to use the overload that takes an array of strings:</p>
<pre><code>string[] lines = theText.Split(
new string[] { Environment.NewLine },
StringSplitOptions.None
);
</code></pre>
<p>Edit:<br />
If you want to handle different types of line breaks in a text, you can use the ability to match more than one string. This will correctly split on either type of line break, and preserve empty lines and spacing in the text:</p>
<pre><code>string[] lines = theText.Split(
new string[] { "\r\n", "\r", "\n" },
StringSplitOptions.None
);
</code></pre> | {
"question_id": 1547476,
"question_date": "2009-10-10T09:25:56.787Z",
"question_score": 927,
"tags": "c#|.net|string|split",
"answer_id": 1547483,
"answer_date": "2009-10-10T09:29:42.473Z",
"answer_score": 1622
} |
Please answer the following Stack Overflow question:
Title: Given two directory trees, how can I find out which files differ by content?
<p>If I want find the differences between two directory trees, I usually just execute:</p>
<pre><code>diff -r dir1/ dir2/
</code></pre>
<p>This outputs exactly what the differences are between corresponding files. I'm interested in just getting a list of corresponding files whose content differs. I assumed that this would simply be a matter of passing a command line option to <code>diff</code>, but I couldn't find anything on the man page.</p>
<p>Any suggestions?</p> | <p>Try:</p>
<pre class="lang-sh prettyprint-override"><code>diff --brief --recursive dir1/ dir2/
</code></pre>
<p>Or alternatively, with the short flags <code>-qr</code>:</p>
<pre class="lang-sh prettyprint-override"><code>diff -qr dir1/ dir2/
</code></pre>
<p>If you also want to see differences for files that may not exist in either directory:</p>
<pre class="lang-sh prettyprint-override"><code>diff --brief --recursive --new-file dir1/ dir2/ # with long options
diff -qrN dir1/ dir2/ # with short flag aliases
</code></pre> | {
"question_id": 4997693,
"question_date": "2011-02-14T21:52:07.650Z",
"question_score": 927,
"tags": "linux|bash|shell|unix|diff",
"answer_id": 4997724,
"answer_date": "2011-02-14T21:55:39.540Z",
"answer_score": 1333
} |
Please answer the following Stack Overflow question:
Title: Check number of arguments passed to a Bash script
<p>I would like my Bash script to print an error message if the required argument count is not met.</p>
<p>I tried the following code:</p>
<pre><code>#!/bin/bash
echo Script name: $0
echo $# arguments
if [$# -ne 1];
then echo "illegal number of parameters"
fi
</code></pre>
<p>For some unknown reason I've got the following error:</p>
<pre><code>test: line 4: [2: command not found
</code></pre>
<p>What am I doing wrong?</p> | <p>Just like any other simple command, <code>[ ... ]</code> or <code>test</code> requires spaces between its arguments.</p>
<pre class="lang-bash prettyprint-override"><code>if [ "$#" -ne 1 ]; then
echo "Illegal number of parameters"
fi
</code></pre>
<p>Or</p>
<pre class="lang-bash prettyprint-override"><code>if test "$#" -ne 1; then
echo "Illegal number of parameters"
fi
</code></pre>
<h3>Suggestions</h3>
<p>When in Bash, prefer using <code>[[ ]]</code> instead as it doesn't do word splitting and pathname expansion to its variables that quoting may not be necessary unless it's part of an expression.</p>
<pre class="lang-none prettyprint-override"><code>[[ $# -ne 1 ]]
</code></pre>
<p>It also has some other features like unquoted condition grouping, pattern matching (extended pattern matching with <code>extglob</code>) and regex matching.</p>
<p>The following example checks if arguments are valid. It allows a single argument or two.</p>
<pre class="lang-none prettyprint-override"><code>[[ ($# -eq 1 || ($# -eq 2 && $2 == <glob pattern>)) && $1 =~ <regex pattern> ]]
</code></pre>
<p>For pure arithmetic expressions, using <code>(( ))</code> to some may still be better, but they are still possible in <code>[[ ]]</code> with its arithmetic operators like <code>-eq</code>, <code>-ne</code>, <code>-lt</code>, <code>-le</code>, <code>-gt</code>, or <code>-ge</code> by placing the expression as a single string argument:</p>
<pre class="lang-none prettyprint-override"><code>A=1
[[ 'A + 1' -eq 2 ]] && echo true ## Prints true.
</code></pre>
<p>That should be helpful if you would need to combine it with other features of <code>[[ ]]</code> as well.</p>
<p>Take note that <code>[[ ]]</code> and <code>(( ))</code> are keywords which have same level of parsing as <code>if</code>, <code>case</code>, <code>while</code>, and <code>for</code>.</p>
<p>Also as <a href="https://stackoverflow.com/users/4412820/dave">Dave</a> suggested, error messages are better sent to stderr so they don't get included when stdout is redirected:</p>
<pre><code>echo "Illegal number of parameters" >&2
</code></pre>
<h3>Exiting the script</h3>
<p>It's also logical to make the script exit when invalid parameters are passed to it. This has already been suggested in the <a href="https://stackoverflow.com/questions/18568706/check-number-of-arguments-passed-to-a-bash-script#comment50847987_18568706">comments</a> by <a href="https://stackoverflow.com/users/1102730/ekangas">ekangas</a> but someone edited this answer to have it with <code>-1</code> as the returned value, so I might as well do it right.</p>
<p><code>-1</code> though accepted by Bash as an argument to <code>exit</code> is not explicitly documented and is not right to be used as a common suggestion. <code>64</code> is also the most formal value since it's defined in <code>sysexits.h</code> with <code>#define EX_USAGE 64 /* command line usage error */</code>. Most tools like <code>ls</code> also return <code>2</code> on invalid arguments. I also used to return <code>2</code> in my scripts but lately I no longer really cared, and simply used <code>1</code> in all errors. But let's just place <code>2</code> here since it's most common and probably not OS-specific.</p>
<pre><code>if [[ $# -ne 1 ]]; then
echo "Illegal number of parameters" >&2
exit 2
fi
</code></pre>
<h3>References</h3>
<ul>
<li><a href="https://www.gnu.org/software/bash/manual/bash.html#Bash-Conditional-Expressions" rel="noreferrer">Bash Conditional Expressions</a></li>
<li><a href="https://www.gnu.org/software/bash/manual/bash.html#Conditional-Constructs" rel="noreferrer">Conditional Constructs</a></li>
<li><a href="https://www.gnu.org/software/bash/manual/bash.html#Pattern-Matching" rel="noreferrer">Pattern Matching</a></li>
<li><a href="https://www.gnu.org/software/bash/manual/bash.html#Word-Splitting" rel="noreferrer">Word Splitting</a></li>
<li><a href="https://www.gnu.org/software/bash/manual/bash.html#Filename-Expansion" rel="noreferrer">Filename Expansion (prev. Pathname Expansion)</a></li>
<li><a href="https://www.gnu.org/software/bash/manual/html_node/Simple-Commands.html" rel="noreferrer">Simple Commands</a></li>
</ul> | {
"question_id": 18568706,
"question_date": "2013-09-02T08:28:51.087Z",
"question_score": 926,
"tags": "bash|parameter-passing|command-line-arguments",
"answer_id": 18568726,
"answer_date": "2013-09-02T08:30:04.767Z",
"answer_score": 1424
} |
Please answer the following Stack Overflow question:
Title: Change the selected value of a drop-down list with jQuery
<p>I have a drop-down list with known values. What I'm trying to do is set the drop down list to a particular value that I know exists using <strong>jQuery</strong>.
Using regular <strong>JavaScript</strong>, I would do something like:</p>
<pre><code>ddl = document.getElementById("ID of element goes here");
ddl.value = 2; // 2 being the value I want to set it too.
</code></pre>
<p>However, I need to do this with <strong>jQuery</strong>, because I'm using a <strong>CSS</strong> class for my selector (stupid <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="noreferrer">ASP.NET</a> client ids...).</p>
<p>Here are a few things I've tried:</p>
<pre><code>$("._statusDDL").val(2); // Doesn't find 2 as a value.
$("._statusDDL").children("option").val(2) // Also failed.
</code></pre>
<blockquote>
<p>How can I do it with <strong>jQuery</strong>?</p>
</blockquote>
<hr>
<p><strong>Update</strong></p>
<p>So as it turns out, I had it right the first time with:</p>
<pre><code>$("._statusDDL").val(2);
</code></pre>
<p>When I put an alert just above it works fine, but when I remove the alert and let it run at full speed, I get the error</p>
<blockquote>
<p>Could not set the selected property. Invalid Index</p>
</blockquote>
<p>I'm not sure if it's a bug with jQuery or <strong>Internet Explorer 6</strong> (I'm guessing Internet <strong>Explorer 6</strong>), but it's terribly annoying.</p> | <p><a href="http://docs.jquery.com/Attributes/val#val" rel="noreferrer">jQuery's documentation</a> states:</p>
<blockquote>
<p>[jQuery.val] checks, or <em><strong>selects</strong></em>, all the radio buttons, checkboxes, and select options that match the set of values.</p>
</blockquote>
<p>This behavior is in <code>jQuery</code> versions <code>1.2</code> and above.</p>
<p>You most likely want this:</p>
<pre><code>$("._statusDDL").val('2');
</code></pre>
<p>Add <code>.change()</code> to see the option in the dropdown list frontend:</p>
<pre><code>$("._statusDDL").val('2').change();
</code></pre> | {
"question_id": 499405,
"question_date": "2009-01-31T19:39:01.823Z",
"question_score": 925,
"tags": "javascript|jquery|asp.net|html-select",
"answer_id": 499413,
"answer_date": "2009-01-31T19:43:42.750Z",
"answer_score": 1097
} |
Please answer the following Stack Overflow question:
Title: Upgrade Node.js to the latest version on Mac OS
<p>Currently I am using Node.js v0.6.16 on Mac OS X 10.7.4. Now I want to upgrade it to the latest Node.js v0.8.1. But after downloading and installing the latest package file from nodejs.org, I found that system is still using v0.6.16 instead of v0.8.1 when I typed "node -v" in a terminal. Is there any step that I have missed? Or, should I thoroughly uninstall the old version before installing the latest one?</p>
<p>BTW, I know that nvm can help to manage the nodejs package</p>
<p><a href="https://github.com/creationix/nvm/" rel="noreferrer">https://github.com/creationix/nvm/</a></p>
<p>Is there any way to upgrade the Node.js without using it?</p>
<p>I have googled this problem, but it seems to me that there is no very clear answer to this question for the latest Node.js.</p> | <p>Here's how I successfully upgraded from <code>v0.8.18</code> to <code>v0.10.20</code> <strong>without any other requirements</strong> like brew etc, (type these commands in the terminal):</p>
<ol>
<li><code>sudo npm cache clean -f</code> (force) clear you npm cache</li>
<li><code>sudo npm install -g n</code> install <a href="https://www.npmjs.com/package/n" rel="noreferrer">n</a> (this might take a while)</li>
<li><code>sudo n stable</code> upgrade to the current stable version</li>
</ol>
<p><em>Note that <code>sudo</code> might prompt your password.</em> </p>
<p><em>Additional note regarding step 3: <code>stable</code> can be exchanged for <code>latest</code>, <code>lts</code> (long term support) or any specific version number such as <code>0.10.20</code>.</em></p>
<p>If the version number doesn't show up when typing <code>node -v</code>, you might have to reboot.</p>
<p>These instructions are found here as well: <a href="https://davidwalsh.name/upgrade-nodejs" rel="noreferrer">davidwalsh.name/upgrade-nodejs</a><br>
More info about the <strong>n</strong> package found here: <a href="https://www.npmjs.com/package/n" rel="noreferrer">npmjs.com/package/n</a><br>
More info about Node.js' release schedule: <a href="https://github.com/nodejs/Release#release-schedule" rel="noreferrer">github.com/nodejs/Release</a></p> | {
"question_id": 11284634,
"question_date": "2012-07-01T18:33:31.910Z",
"question_score": 925,
"tags": "macos|node.js|upgrade",
"answer_id": 19333717,
"answer_date": "2013-10-12T11:36:37.400Z",
"answer_score": 1770
} |
Please answer the following Stack Overflow question:
Title: pip install mysql-python fails with EnvironmentError: mysql_config not found
<p><strong>This is the error I get</strong></p>
<pre><code>(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install mysql-python
Downloading/unpacking mysql-python
Downloading MySQL-python-1.2.3.tar.gz (70Kb): 70Kb downloaded
Running setup.py egg_info for package mysql-python
sh: mysql_config: not found
Traceback (most recent call last):
File "<string>", line 14, in <module>
File "/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py", line 15, in <module>
metadata, options = get_config()
File "setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "setup_posix.py", line 24, in mysql_config
raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found
Complete output from command python setup.py egg_info:
sh: mysql_config: not found
Traceback (most recent call last):
File "<string>", line 14, in <module>
File "/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py", line 15, in <module>
metadata, options = get_config()
File "setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "setup_posix.py", line 24, in mysql_config
raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found
----------------------------------------
Command python setup.py egg_info failed with error code 1
Storing complete log in /home/zjm1126/.pip/pip.log
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install mysql-python
Downloading/unpacking mysql-python
Running setup.py egg_info for package mysql-python
sh: mysql_config: not found
Traceback (most recent call last):
File "<string>", line 14, in <module>
File "/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py", line 15, in <module>
metadata, options = get_config()
File "setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "setup_posix.py", line 24, in mysql_config
raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found
Complete output from command python setup.py egg_info:
sh: mysql_config: not found
Traceback (most recent call last):
File "<string>", line 14, in <module>
File "/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py", line 15, in <module>
metadata, options = get_config()
File "setup_posix.py", line 43, in get_config
libs = mysql_config("libs_r")
File "setup_posix.py", line 24, in mysql_config
raise EnvironmentError("%s not found" % (mysql_config.path,))
EnvironmentError: mysql_config not found
----------------------------------------
Command python setup.py egg_info failed with error code 1
Storing complete log in /home/zjm1126/.pip/pip.log
</code></pre>
<p>What can I do to resolve this?</p> | <p>It seems mysql_config is missing on your system or the installer could not find it.
Be sure mysql_config is really installed.</p>
<p>For example on Debian/Ubuntu you must install the package:</p>
<pre><code>sudo apt-get install libmysqlclient-dev
</code></pre>
<p>Maybe the mysql_config is not in your path, it will be the case when you compile by yourself
the mysql suite.</p>
<p><strong>Update:</strong> For recent versions of debian/ubuntu (as of 2018) it is </p>
<pre><code>sudo apt install default-libmysqlclient-dev
</code></pre> | {
"question_id": 5178292,
"question_date": "2011-03-03T08:32:51.677Z",
"question_score": 925,
"tags": "python|pip|mysql-python",
"answer_id": 5178698,
"answer_date": "2011-03-03T09:15:32.110Z",
"answer_score": 1560
} |
Please answer the following Stack Overflow question:
Title: Difference between 'struct' and 'typedef struct' in C++?
<p>In <strong>C++</strong>, is there any difference between:</p>
<pre><code>struct Foo { ... };
</code></pre>
<p>and:</p>
<pre><code>typedef struct { ... } Foo;
</code></pre> | <p>In C++, there is only a subtle difference. It's a holdover from C, in which it makes a difference.</p>
<p>The C language standard (<a href="http://port70.net/~nsz/c/c89/c89-draft.txt" rel="noreferrer">C89 §3.1.2.3</a>, <a href="http://port70.net/~nsz/c/c99/n1256.html#6.2.3" rel="noreferrer">C99 §6.2.3</a>, and <a href="http://port70.net/~nsz/c/c11/n1570.html#6.2.3" rel="noreferrer">C11 §6.2.3</a>) mandates separate namespaces for different categories of identifiers, including <em>tag identifiers</em> (for <code>struct</code>/<code>union</code>/<code>enum</code>) and <em>ordinary identifiers</em> (for <code>typedef</code> and other identifiers). </p>
<p>If you just said:</p>
<pre><code>struct Foo { ... };
Foo x;
</code></pre>
<p>you would get a compiler error, because <code>Foo</code> is only defined in the tag namespace. </p>
<p>You'd have to declare it as:</p>
<pre><code>struct Foo x;
</code></pre>
<p>Any time you want to refer to a <code>Foo</code>, you'd always have to call it a <code>struct Foo</code>. This gets annoying fast, so you can add a <code>typedef</code>:</p>
<pre><code>struct Foo { ... };
typedef struct Foo Foo;
</code></pre>
<p>Now <code>struct Foo</code> (in the tag namespace) and just plain <code>Foo</code> (in the ordinary identifier namespace) both refer to the same thing, and you can freely declare objects of type <code>Foo</code> without the <code>struct</code> keyword.</p>
<hr>
<p>The construct:</p>
<pre><code>typedef struct Foo { ... } Foo;
</code></pre>
<p>is just an abbreviation for the declaration and <code>typedef</code>.</p>
<hr>
<p>Finally,</p>
<pre><code>typedef struct { ... } Foo;
</code></pre>
<p>declares an anonymous structure and creates a <code>typedef</code> for it. Thus, with this construct, it doesn't have a name in the tag namespace, only a name in the typedef namespace. This means it also cannot be forward-declared. <em>If you want to make a forward declaration, you have to give it a name in the tag namespace</em>.</p>
<hr>
<p>In C++, all <code>struct</code>/<code>union</code>/<code>enum</code>/<code>class</code> declarations act like they are implicitly <code>typedef</code>'ed, as long as the name is not hidden by another declaration with the same name. See <a href="https://stackoverflow.com/questions/612328/difference-between-struct-and-typedef-struct-in-c/612476#612476">Michael Burr's answer</a> for the full details.</p> | {
"question_id": 612328,
"question_date": "2009-03-04T20:41:12.047Z",
"question_score": 925,
"tags": "c++|struct|typedef",
"answer_id": 612350,
"answer_date": "2009-03-04T20:45:36.950Z",
"answer_score": 1321
} |
Please answer the following Stack Overflow question:
Title: What is the difference between React Native and React?
<p>I have started to learn <em>React</em> out of curiosity and wanted to know the difference between React and React Native - though could not find a satisfactory answer using Google. React and React Native seems to have the same format. Do they have completely different syntax?</p> | <p><a href="https://reactjs.org/" rel="noreferrer">ReactJS</a> is a JavaScript library, supporting both front-end web and being run on a server, for building user interfaces and web applications. It follows the concept of reusable components.</p>
<p><a href="https://reactnative.dev/" rel="noreferrer">React Native</a> is a mobile framework that makes use of the JavaScript engine available on the host, allowing you to build mobile applications for different platforms (iOS, Android, and Windows Mobile) in JavaScript that allows you to use ReactJS to build reusable components and communicate with native components <a href="https://stackoverflow.com/questions/41124338/does-react-native-compile-javascript-into-java-for-android">further explanation</a></p>
<p>Both follow the JSX syntax extension of JavaScript. Which compiles to <code>React.createElement</code> calls under the hood. <a href="https://reactjs.org/docs/jsx-in-depth.html" rel="noreferrer">JSX in-depth</a></p>
<p>Both are open-sourced by Facebook.</p> | {
"question_id": 34641582,
"question_date": "2016-01-06T19:51:57.457Z",
"question_score": 925,
"tags": "javascript|reactjs|react-native|javascript-framework",
"answer_id": 34641772,
"answer_date": "2016-01-06T20:04:14.743Z",
"answer_score": 1025
} |
Please answer the following Stack Overflow question:
Title: Remove credentials from Git
<p>I'm working with several repositories, but lately I was just working in our internal one and all was great.</p>
<p>Today I had to commit and push code into other one, but I'm having some troubles.</p>
<pre><code>$ git push appharbor master
error: The requested URL returned error: 403 while accessing https://[email protected]/mitivo.git/info/refs?service=git-receive-pack
fatal: HTTP request failed
</code></pre>
<p>There is nothing I can do, that would bring the password entry again.</p>
<p>How can I reset the credentials on my system so Git will ask me for the password of that repository?</p>
<p>I have tried:</p>
<ul>
<li><code>git config --global --unset core.askpass</code></li>
</ul>
<p>in order to unset the password</p>
<ul>
<li><code>git config credential.helper 'cache --timeout=1'</code></li>
</ul>
<p>in order to avoid credentials cache...</p>
<p>Nothing seems to work; does anyone have a better idea?</p> | <p>If this problem comes on a Windows machine, do the following.</p>
<ul>
<li><p>Go to Credential Manager</p>
<ul>
<li>in German, it is called: <em>Anmeldeinformationsverwaltung</em></li>
<li>in French, it is called: <em>Gestionnaire d'identification</em></li>
<li>in Polish, it is called: <em>Menedżer poświadczeń</em></li>
<li>in Portuguese, it is called: <em>Gerenciador de Credenciais</em></li>
<li>in Russian, it is called: <em>Диспетчер учётных данных</em></li>
<li>in Spanish, it is called: <em>Administrador de credenciales</em></li>
<li>in Norwegian, it is called: <em>Legitimasjonsbehandling</em></li>
</ul>
<p><a href="https://i.stack.imgur.com/5KePZ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/5KePZ.png" alt="Go to Credential Manager " /></a></p>
</li>
<li><p>Go to Windows Credentials</p>
</li>
<li><p>Delete the entries under Generic Credentials</p>
<p><a href="https://i.stack.imgur.com/kRdEv.png" rel="noreferrer"><img src="https://i.stack.imgur.com/kRdEv.png" alt="Go to Windows Credentials and Delete the entries under Generic Credentials " /></a></p>
</li>
<li><p>Try connecting again. This time, it should prompt you for the correct username and password.</p>
</li>
</ul> | {
"question_id": 15381198,
"question_date": "2013-03-13T09:20:21.760Z",
"question_score": 924,
"tags": "windows|git|credentials",
"answer_id": 39608906,
"answer_date": "2016-09-21T06:24:42.067Z",
"answer_score": 1166
} |
Please answer the following Stack Overflow question:
Title: How to play audio?
<p>I am making a game with HTML5 and JavaScript.</p>
<p>How could I play game audio via JavaScript?</p> | <p>If you don't want to mess with HTML elements:</p>
<pre class="lang-js prettyprint-override"><code>var audio = new Audio('audio_file.mp3');
audio.play();
</code></pre>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function play() {
var audio = new Audio('https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3');
audio.play();
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="play()">Play Audio</button></code></pre>
</div>
</div>
</p>
<p>This uses the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement" rel="noreferrer"><code>HTMLAudioElement</code></a> interface, which plays audio the same way as the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio" rel="noreferrer"><code><audio></code> element</a>.</p>
<hr />
<p>If you need more functionality, I used the <a href="https://howlerjs.com" rel="noreferrer">howler.js</a> library and found it simple and useful.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/howler/2.1.1/howler.min.js"></script>
<script>
var sound = new Howl({
src: ['https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3'],
volume: 0.5,
onend: function () {
alert('Finished!');
}
});
sound.play()
</script></code></pre>
</div>
</div>
</p> | {
"question_id": 9419263,
"question_date": "2012-02-23T18:49:06.780Z",
"question_score": 924,
"tags": "javascript|html|html5-audio",
"answer_id": 18628124,
"answer_date": "2013-09-05T05:03:32.260Z",
"answer_score": 1783
} |
Please answer the following Stack Overflow question:
Title: How do I measure request and response times at once using cURL?
<p>I have a web service that receives data in JSON format, processes the data, and then returns the result to the requester.</p>
<p>I want to measure the request, response, and total time using <code>cURL</code>.</p>
<p>My example request looks like:</p>
<pre><code>curl -X POST -d @file server:port
</code></pre>
<p>and I currently measure this using the <code>time</code> command in Linux:</p>
<pre><code>time curl -X POST -d @file server:port
</code></pre>
<p>The time command only measures <em>total</em> time, though - which isn't quite what I am looking for.</p>
<p>Is there any way to measure request and response times using <code>cURL</code>?</p> | <p><em>From this brilliant blog post... <a href="https://blog.josephscott.org/2011/10/14/timing-details-with-curl/" rel="noreferrer">https://blog.josephscott.org/2011/10/14/timing-details-with-curl/</a></em></p>
<p>cURL supports formatted output for the details of the request (see <a href="http://curl.haxx.se/docs/manpage.html" rel="noreferrer">the cURL manpage for details</a>, under <code>-w, –write-out <format></code>). For our purposes we’ll focus just on the timing details that are provided. Times below are in <strong>seconds</strong>.</p>
<ol>
<li><p><strong>Create a new file, <code>curl-format.txt</code>, and paste in:</strong></p>
<pre><code> time_namelookup: %{time_namelookup}s\n
time_connect: %{time_connect}s\n
time_appconnect: %{time_appconnect}s\n
time_pretransfer: %{time_pretransfer}s\n
time_redirect: %{time_redirect}s\n
time_starttransfer: %{time_starttransfer}s\n
----------\n
time_total: %{time_total}s\n
</code></pre>
</li>
<li><p><strong>Make a request:</strong></p>
<pre><code> curl -w "@curl-format.txt" -o /dev/null -s "http://wordpress.com/"
</code></pre>
<p>Or on Windows, it's...</p>
<pre><code> curl -w "@curl-format.txt" -o NUL -s "http://wordpress.com/"
</code></pre>
</li>
</ol>
<br>
<h2>What this does:</h2>
<p><code>-w "@curl-format.txt"</code> tells cURL to use our format file<br>
<code>-o /dev/null</code> redirects the output of the request to /dev/null<br>
<code>-s</code>
tells cURL not to show a progress meter<br>
<code>"http://wordpress.com/"</code> is
the URL we are requesting. Use quotes particularly if your URL has "&" query string parameters</p>
<br>
<h2>And here is what you get back:</h2>
<pre><code> time_namelookup: 0.001s
time_connect: 0.037s
time_appconnect: 0.000s
time_pretransfer: 0.037s
time_redirect: 0.000s
time_starttransfer: 0.092s
----------
time_total: 0.164s
</code></pre>
<p>I have not yet seen an option to output the results in microseconds, but if you're aware of one, post in the comments below.</p>
<br>
<h2>Make a Linux/Mac shortcut (alias)</h2>
<pre><code>alias curltime="curl -w \"@$HOME/.curl-format.txt\" -o /dev/null -s "
</code></pre>
<p>Then you can simply call...</p>
<pre><code>curltime wordpress.org
</code></pre>
<p><em>Thanks to commenter Pete Doyle!</em></p>
<br>
<h2>Make a Linux/Mac stand-alone script</h2>
<p>This script does not require a separate <code>.txt</code> file to contain the formatting.</p>
<p>Create a new file, <code>curltime</code>, somewhere in your executable path, and paste in:</p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/bash
curl -w @- -o /dev/null -s "$@" <<'EOF'
time_namelookup: %{time_namelookup}\n
time_connect: %{time_connect}\n
time_appconnect: %{time_appconnect}\n
time_pretransfer: %{time_pretransfer}\n
time_redirect: %{time_redirect}\n
time_starttransfer: %{time_starttransfer}\n
----------\n
time_total: %{time_total}\n
EOF
</code></pre>
<p>Then call it the same way as the alias:</p>
<pre><code>curltime wordpress.org
</code></pre>
<br>
<h2>Make a Windows shortcut (aka BAT file)</h2>
<p>Create a new text file called <code>curltime.bat</code> in the same folder as <code>curl.exe</code> and <code>curl-format.txt</code>, and paste in the following line:</p>
<pre><code>curl -w "@%~dp0curl-format.txt" -o NUL -s %*
</code></pre>
<p>Then from the command line you can simply call:</p>
<pre><code>curltime wordpress.org
</code></pre>
<p>(Make sure the folder is listed in your Windows <code>PATH</code> variable to be able to use the command from any folder.)</p> | {
"question_id": 18215389,
"question_date": "2013-08-13T17:21:22.400Z",
"question_score": 924,
"tags": "curl|time|upload|download|measure",
"answer_id": 22625150,
"answer_date": "2014-03-25T03:55:39.617Z",
"answer_score": 2350
} |
Please answer the following Stack Overflow question:
Title: Xcode 10 Error: Multiple commands produce
<blockquote>
<p>error: Multiple commands produce '/Users/uesr/Library/Developer/Xcode/DerivedData/OptimalLive-fxatvygbofczeyhjsawtebkimvwx/Build/Products/Debug-iphoneos/OptimalLive.app/Info.plist':
1) Target 'OptimalLive' has copy command from '/Users/uesr/Desktop/workSpace/SEALIVE/SeaLive1.1/OptimalLive/Info.plist' to '/Users/uesr/Library/Developer/Xcode/DerivedData/OptimalLive-fxatvygbofczeyhjsawtebkimvwx/Build/Products/Debug-iphoneos/OptimalLive.app/Info.plist'
2) Target 'OptimalLive' has copy command from '/Users/uesr/Desktop/workSpace/SEALIVE/SeaLive1.1/OptimalLive/Server/Masonry/Info.plist' to '/Users/uesr/Library/Developer/Xcode/DerivedData/OptimalLive-fxatvygbofczeyhjsawtebkimvwx/Build/Products/Debug-iphoneos/OptimalLive.app/Info.plist'
3) Target 'OptimalLive' has process command with input '/Users/uesr/Desktop/workSpace/SEALIVE/SeaLive1.1/OptimalLive/Info.plist'</p>
</blockquote>
<p>Running the code in Xcode 9 works, but there is an error in Xcode 10.</p> | <p>The issue might be occurring because of multiple Plist or other files within App-</p>
<p><em>Solution -> Open target -> Build phases > Copy Bundle Resources</em> and remove <code>info.plist</code> from there.</p>
<p><a href="https://i.stack.imgur.com/whT0P.png" rel="noreferrer"><img src="https://i.stack.imgur.com/whT0P.png" alt="enter image description here"></a> </p>
<p><strong>Note:</strong> If you have developed a watch app too then you will have to remove the plist from the watch and watch-extension too.</p> | {
"question_id": 50718018,
"question_date": "2018-06-06T10:22:16.673Z",
"question_score": 924,
"tags": "xcode|xcode10|info.plist",
"answer_id": 50719379,
"answer_date": "2018-06-06T11:32:11.030Z",
"answer_score": 1794
} |
Please answer the following Stack Overflow question:
Title: Stretch and scale a CSS image in the background - with CSS only
<p>I want that my background image stretch and scale depending on the browser viewport size.</p>
<p>I've seen some questions on Stack Overflow that do the job, like <em><a href="https://stackoverflow.com/questions/376253/stretch-and-scale-css-background/388817#388817">Stretch and scale CSS background</a></em> for example. It works well, but I want to place the image using <code>background</code>, not with an <code>img</code> tag.</p>
<p>In that one an <code>img</code> tag is placed, and then with CSS we tribute to the <code>img</code> tag.</p>
<pre><code>width:100%; height:100%;
</code></pre>
<p>It works, but that question is a bit old, and states that in CSS 3 resizing a background image will work pretty well. I've tried this <a href="http://www.w3.org/TR/2002/WD-css3-background-20020802/#background-size" rel="noreferrer">example the first one</a>, but it didn't work out for me.</p>
<p>Is there a good method to do it with the <code>background-image</code> declaration?</p> | <p>CSS3 has a nice little attribute called <code>background-size:cover</code>.</p>
<p>This scales the image so that the background area is completely covered by the background image while maintaining the aspect ratio. The entire area will be covered. However, part of the image may not be visible if the width/height of the resized image is too large.</p> | {
"question_id": 1150163,
"question_date": "2009-07-19T15:51:52.857Z",
"question_score": 923,
"tags": "css|background",
"answer_id": 7372377,
"answer_date": "2011-09-10T14:28:56.163Z",
"answer_score": 1134
} |
Please answer the following Stack Overflow question:
Title: How do I get the application exit code from a Windows command line?
<p>I am running a program and want to see what its return code is (since it returns different codes based on different errors).</p>
<p>I know in Bash I can do this by running</p>
<blockquote>
<p>echo $?</p>
</blockquote>
<p>What do I do when using cmd.exe on Windows?</p> | <p>A pseudo environment variable named <code>errorlevel</code> stores the exit code:</p>
<pre><code>echo Exit Code is %errorlevel%
</code></pre>
<p>Also, the <code>if</code> command has a special syntax:</p>
<pre><code>if errorlevel
</code></pre>
<p>See <code>if /?</code> for details.</p>
<h1>Example</h1>
<pre><code>@echo off
my_nifty_exe.exe
if errorlevel 1 (
echo Failure Reason Given is %errorlevel%
exit /b %errorlevel%
)
</code></pre>
<p><em>Warning: If you set an environment variable name <code>errorlevel</code>, <code>%errorlevel%</code> will return that value and not the exit code. Use (<code>set errorlevel=</code>) to clear the environment variable, allowing access to the true value of <code>errorlevel</code> via the <code>%errorlevel%</code> environment variable.</em></p> | {
"question_id": 334879,
"question_date": "2008-12-02T18:04:17.773Z",
"question_score": 923,
"tags": "windows|command-line|process|cmd|exit-code",
"answer_id": 334890,
"answer_date": "2008-12-02T18:07:58.780Z",
"answer_score": 1130
} |
Please answer the following Stack Overflow question:
Title: How to recover stashed uncommitted changes
<p>I had some uncommitted changes in my development branch and I stashed them using <code>git stash</code>, but there were some changes which were very important among those stashed ones. Is there any way to get back those changes?</p>
<p>Also, I have made some changes on top of the stashed code files since. </p>
<p>Is there any chance I can retrieve the stashed changes to a new branch if possible?</p> | <h2>The easy answer to the easy question is <code>git stash apply</code></h2>
<p>Just check out the branch you want your changes on, and then <code>git stash apply</code>. Then use <code>git diff</code> to see the result.</p>
<p>After you're all done with your changes—the <code>apply</code> looks good and you're sure you don't need the stash any more—<em>then</em> use <code>git stash drop</code> to get rid of it.</p>
<p>I always suggest using <code>git stash apply</code> rather than <code>git stash pop</code>. The difference is that <code>apply</code> leaves the stash around for easy re-try of the <code>apply</code>, or for looking at, etc. If <code>pop</code> is able to extract the stash, it will immediately also <code>drop</code> it, and if you subsequently realize that you wanted to extract it somewhere else (in a different branch), or with <code>--index</code>, or some such, that's not so easy. If you <code>apply</code>, <em>you</em> get to choose when to <code>drop</code>.</p>
<p>It's all pretty minor one way or the other though, and for a newbie to Git, it should be about the same. (And you can skip all the rest of this!)</p>
<hr />
<h2>What if you're doing more-advanced or more-complicated stuff?</h2>
<p>There are at least three or four different "ways to use git stash", as it were. The above is for "way 1", the "easy way":</p>
<ol>
<li>You started with a clean branch, were working on some changes, and then realized you were doing them in the wrong branch. You just want to take the changes you have now and "move" them to another branch.</li>
</ol>
<p>This is the easy case, described above. Run <code>git stash save</code> (or plain <code>git stash</code>, same thing). Check out the other branch and use <code>git stash apply</code>. This gets Git to merge in your earlier changes, using Git's rather powerful merge mechanism. <em>Inspect the results carefully</em> (with <code>git diff</code>) to see if you like them, and if you do, use <code>git stash drop</code> to drop the stash. You're done!</p>
<ol start="2">
<li>You started some changes and stashed them. Then you switched to another branch and started more changes, forgetting that you had the stashed ones.</li>
</ol>
<p>Now you want to keep, or even move, <em>these</em> changes, <em>and</em> apply your stash too.</p>
<p>You can in fact <code>git stash save</code> again, as <code>git stash</code> makes a "stack" of changes. If you do that, you have two stashes, one just called <code>stash</code>—but you can also write <code>stash@{0}</code>—and one spelled <code>stash@{1}</code>. Use <code>git stash list</code> (at any time) to see them all. The newest is always the lowest-numbered. When you <code>git stash drop</code>, it drops the newest, and the one that was <code>stash@{1}</code> moves to the top of the stack. If you had, even more, the one that was <code>stash@{2}</code> becomes <code>stash@{1}</code>, and so on.</p>
<p>You can <code>apply</code> and then <code>drop</code> a specific stash, too: <code>git stash apply stash@{2}</code>, and so on. Dropping a specific stash renumbers only the higher-numbered ones. Again, the one without a number is also <code>stash@{0}</code>.</p>
<p>If you pile up a lot of stashes, it can get fairly messy (was the stash I wanted <code>stash@{7}</code> or was it <code>stash@{4}</code>? Wait, I just pushed another, now they're 8 and 5?). I personally prefer to transfer these changes to a new branch, because branches have names, and <code>cleanup-attempt-in-December</code> means a lot more to me than <code>stash@{12}</code>. (The <code>git stash</code> command takes an optional save-message, and those can help, but somehow, all my stashes just wind up named <code>WIP on branch</code>.)</p>
<ol start="3">
<li><p>(Extra-advanced) You've used <code>git stash save -p</code>, or carefully <code>git add</code>-ed and/or <code>git rm</code>-ed specific bits of your code before running <code>git stash save</code>. You had one version in the stashed index/staging area and another (different) version in the working tree. You want to preserve all this. So now you use <code>git stash apply --index</code>, and that sometimes fails with:</p>
<pre><code>Conflicts in index. Try without --index.
</code></pre>
</li>
<li><p>You're using <code>git stash save --keep-index</code> in order to test "what will be committed". This one is beyond the scope of this answer; see <a href="https://stackoverflow.com/a/20480591/1256452">this other StackOverflow answer</a> instead.</p>
</li>
</ol>
<p>For complicated cases, I recommend starting in a "clean" working tree first, by committing any changes you have now (on a new branch if you like). That way the "somewhere" that you are applying them, has nothing else in it, and you'll just be trying the stashed changes:</p>
<pre><code>git status # see if there's anything you need to commit
# uh oh, there is - let's put it on a new temp branch
git checkout -b temp # create new temp branch to save stuff
git add ... # add (and/or remove) stuff as needed
git commit # save first set of changes
</code></pre>
<p>Now you're on a "clean" starting point. Or maybe it goes more like this:</p>
<pre><code>git status # see if there's anything you need to commit
# status says "nothing to commit"
git checkout -b temp # optional: create a new branch for "apply"
git stash apply # apply stashed changes; see below about --index
</code></pre>
<p>The main thing to remember is that the "stash" <em>is</em> a commit, it's just a slightly "funny/weird" commit that's not "on a branch". The <code>apply</code> operation looks at what the commit changed and tries to repeat it wherever you are now. The stash will still be there (<code>apply</code> keeps it around), so you can look at it more, or decide this was the wrong place to <code>apply</code> it and try again differently, or whatever.</p>
<hr />
<p>Any time you have a stash, you can use <code>git stash show -p</code> to see a simplified version of what's in the stash. (This simplified version looks only at the "final work tree" changes, <em>not</em> the saved index changes that <code>--index</code> restores separately.) The command <code>git stash apply</code>, without <code>--index</code>, just tries to make those <em>same</em> changes in your working tree now.</p>
<p>This is true even if you already have some changes. The <code>apply</code> command is happy to apply a stash to a <em>modified</em> working tree (or at least, to try to apply it). You can, for instance, do this:</p>
<pre><code>git stash apply stash # apply top of stash stack
git stash apply stash@{1} # and mix in next stash stack entry too
</code></pre>
<p>You can choose the "apply" order here, picking out particular stashes to apply in a particular sequence. Note, however, that each time you're basically doing a "git merge", and as the merge documentation warns:</p>
<blockquote>
<p>Running git merge with non-trivial uncommitted changes is
discouraged: while possible, it may leave you in a state that is hard
to back out of in the case of a conflict.</p>
</blockquote>
<p><strong>If you start with a clean tree</strong> and are just doing several <code>git apply</code> operations, it's easy to back out: use <code>git reset --hard</code> to get back to the clean state, and change your <code>apply</code> operations. (That's why I recommend starting in a clean working tree first, for these complicated cases.)</p>
<hr />
<h2>What about the very worst possible case?</h2>
<p>Let's say you're doing Lots Of Advanced Git Stuff, and you've made a stash, and want to <code>git stash apply --index</code>, but it's no longer possible to apply the saved stash with <code>--index</code> because the branch has diverged too much since the time you saved it.</p>
<p>This is what <code>git stash branch</code> is for.</p>
<p>If you:</p>
<ol>
<li>check out the <em>exact commit</em> you were on when you did the original <code>stash</code>, then</li>
<li>create a new branch, and finally</li>
<li><code>git stash apply --index</code></li>
</ol>
<p>the attempt to re-create the changes definitely <em>will</em> work. This is what <code>git stash branch <em>newbranch</em></code> does. (And it then drops the stash since it was successfully applied.)</p>
<hr />
<h2>Some final words about <code>--index</code> (what the heck is it?)</h2>
<p>What the <code>--index</code> does is simple to explain, but a bit complicated internally:</p>
<ul>
<li>When you have changes, you have to <code>git add</code> (or "stage") them before <code>commit</code>-ing.</li>
<li>Thus, when you ran <code>git stash</code>, you <em>might</em> have edited both files <code>foo</code> and <code>zorg</code>, but only staged one of those.</li>
<li>So when you ask to get the stash back, it might be nice if it <code>git add</code>s the <code>added</code> things and does <em>not</em> <code>git add</code> the non-added things. That is, if you are <code>add</code>-ed <code>foo</code> but not <code>zorg</code> back before you did the <code>stash</code>, it might be nice to have that exact same setup. What was staged, should again be staged; what was modified but not staged, should again be modified but not staged.</li>
</ul>
<p>The <code>--index</code> flag to <code>apply</code> tries to set things up this way. If your working tree is clean, this usually just works. If your working tree already has stuff <code>add</code>-ed, though, you can see how there might be some problems here. If you leave out <code>--index</code>, the <code>apply</code> operation does not attempt to preserve the whole staged/unstaged setup. Instead, it just invokes Git's merge machinery, using the working tree commit in the <a href="https://stackoverflow.com/q/20409853/1256452">"stash bag"</a>. If you don't care about preserving staged/unstaged, leaving out <code>--index</code> makes it a lot easier for <code>git stash apply</code> to do its thing.</p> | {
"question_id": 19003009,
"question_date": "2013-09-25T10:56:21.237Z",
"question_score": 923,
"tags": "git|git-stash",
"answer_id": 19003191,
"answer_date": "2013-09-25T11:03:52.707Z",
"answer_score": 1572
} |
Please answer the following Stack Overflow question:
Title: addEventListener vs onclick
<p>What's the difference between <code>addEventListener</code> and <code>onclick</code>?</p>
<pre><code>var h = document.getElementById("a");
h.onclick = dothing1;
h.addEventListener("click", dothing2);
</code></pre>
<p>The code above resides together in a separate <code>.js</code> file, and they both work perfectly.</p> | <p>Both are correct, but none of them are "best" per se, and there may be a reason the developer chose to use both approaches.</p>
<p><strong>Event Listeners (addEventListener and IE's attachEvent)</strong></p>
<p>Earlier versions of Internet Explorer implement JavaScript differently from pretty much every other browser. With versions less than 9, you use the <code>attachEvent</code>[<a href="http://msdn.microsoft.com/en-us/library/ie/ms536343%28v=vs.85%29.aspx" rel="noreferrer">doc</a>] method, like this:</p>
<pre><code>element.attachEvent('onclick', function() { /* do stuff here*/ });
</code></pre>
<p>In most other browsers (including IE 9 and above), you use <code>addEventListener</code>[<a href="https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener" rel="noreferrer">doc</a>], like this:</p>
<pre><code>element.addEventListener('click', function() { /* do stuff here*/ }, false);
</code></pre>
<p>Using this approach (<a href="http://www.w3.org/wiki/Handling_events_with_JavaScript#The_evolution_of_events" rel="noreferrer">DOM Level 2 events</a>), you can attach a theoretically unlimited number of events to any single element. The only practical limitation is client-side memory and other performance concerns, which are different for each browser.</p>
<p>The examples above represent using an anonymous function[<a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope" rel="noreferrer">doc</a>]. You can also add an event listener using a function reference[<a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function" rel="noreferrer">doc</a>] or a closure[<a href="https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Closures" rel="noreferrer">doc</a>]:</p>
<pre><code>var myFunctionReference = function() { /* do stuff here*/ }
element.attachEvent('onclick', myFunctionReference);
element.addEventListener('click', myFunctionReference , false);
</code></pre>
<p>Another important feature of <code>addEventListener</code> is the final parameter, which controls how the listener reacts to bubbling events[<a href="http://www.w3.org/TR/DOM-Level-3-Events/#event-flow" rel="noreferrer">doc</a>]. I've been passing false in the examples, which is standard for probably 95% of use cases. There is no equivalent argument for <code>attachEvent</code>, or when using inline events.</p>
<p><strong>Inline events (HTML onclick="" property and element.onclick)</strong></p>
<p>In all browsers that support javascript, you can put an event listener inline, meaning right in the HTML code. You've probably seen this:</p>
<pre><code><a id="testing" href="#" onclick="alert('did stuff inline');">Click me</a>
</code></pre>
<p>Most experienced developers shun this method, but it does get the job done; it is simple and direct. You may not use closures or anonymous functions here (though the handler itself is an anonymous function of sorts), and your control of scope is limited.</p>
<p>The other method you mention:</p>
<pre><code>element.onclick = function () { /*do stuff here */ };
</code></pre>
<p>... is the equivalent of inline javascript except that you have more control of the scope (since you're writing a script rather than HTML) and can use anonymous functions, function references, and/or closures.</p>
<p>The significant drawback with inline events is that unlike event listeners described above, you may only have one inline event assigned. Inline events are stored as an attribute/property of the element[<a href="http://www.w3.org/wiki/HTML/Attributes/_Global#Event-handler_Attributes" rel="noreferrer">doc</a>], meaning that it can be overwritten.</p>
<p>Using the example <code><a></code> from the HTML above:</p>
<pre><code>var element = document.getElementById('testing');
element.onclick = function () { alert('did stuff #1'); };
element.onclick = function () { alert('did stuff #2'); };
</code></pre>
<p>... when you clicked the element, you'd <strong>only</strong> see "Did stuff #2" - you overwrote the first assigned of the <code>onclick</code> property with the second value, and you overwrote the original inline HTML <code>onclick</code> property too. Check it out here: <a href="http://jsfiddle.net/jpgah/" rel="noreferrer">http://jsfiddle.net/jpgah/</a>.</p>
<p>Broadly speaking, <strong>do not use inline events</strong>. There may be specific use cases for it, but if you are not 100% sure you have that use case, then you do not and should not use inline events.</p>
<p><strong>Modern Javascript (Angular and the like)</strong></p>
<p>Since this answer was originally posted, javascript frameworks like Angular have become far more popular. You will see code like this in an Angular template:</p>
<pre><code><button (click)="doSomething()">Do Something</button>
</code></pre>
<p>This looks like an inline event, but it isn't. This type of template will be transpiled into more complex code which uses event listeners behind the scenes. Everything I've written about events here still applies, but you are removed from the nitty gritty by at least one layer. You should understand the nuts and bolts, but if your modern JS framework best practices involve writing this kind of code in a template, don't feel like you're using an inline event -- you aren't.</p>
<p><strong>Which is Best?</strong></p>
<p>The question is a matter of browser compatibility and necessity. Do you need to attach more than one event to an element? Will you in the future? Odds are, you will. attachEvent and addEventListener are necessary. If not, an inline event may seem like they'd do the trick, but you're much better served preparing for a future that, though it may seem unlikely, is predictable at least. There is a chance you'll have to move to JS-based event listeners, so you may as well just start there. Don't use inline events.</p>
<p>jQuery and other javascript frameworks encapsulate the different browser implementations of DOM level 2 events in generic models so you can write cross-browser compliant code without having to worry about IE's history as a rebel. Same code with jQuery, all cross-browser and ready to rock:</p>
<pre><code>$(element).on('click', function () { /* do stuff */ });
</code></pre>
<p>Don't run out and get a framework just for this one thing, though. You can easily roll your own little utility to take care of the older browsers:</p>
<pre><code>function addEvent(element, evnt, funct){
if (element.attachEvent)
return element.attachEvent('on'+evnt, funct);
else
return element.addEventListener(evnt, funct, false);
}
// example
addEvent(
document.getElementById('myElement'),
'click',
function () { alert('hi!'); }
);
</code></pre>
<p>Try it: <a href="http://jsfiddle.net/bmArj/" rel="noreferrer">http://jsfiddle.net/bmArj/</a></p>
<p>Taking all of that into consideration, unless the script you're looking at took the browser differences into account some other way (in code not shown in your question), the part using <code>addEventListener</code> would not work in IE versions less than 9.</p>
<p><strong>Documentation and Related Reading</strong></p>
<ul>
<li><a href="http://www.w3.org/wiki/HTML/Attributes/_Global#Event-handler_Attributes" rel="noreferrer">W3 HTML specification, element Event Handler Attributes</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener" rel="noreferrer">element.addEventListener on MDN</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ie/ms536343%28v=vs.85%29.aspx" rel="noreferrer">element.attachEvent on MSDN</a></li>
<li><a href="http://api.jquery.com/on/" rel="noreferrer">Jquery.on</a></li>
<li><a href="http://www.quirksmode.org/js/introevents.html" rel="noreferrer">quirksmode blog "Introduction to Events"</a></li>
<li><a href="https://developers.google.com/speed/libraries/" rel="noreferrer">CDN-hosted javascript libraries at Google</a></li>
</ul> | {
"question_id": 6348494,
"question_date": "2011-06-14T18:49:54.307Z",
"question_score": 923,
"tags": "javascript|onclick|addeventlistener",
"answer_id": 6348597,
"answer_date": "2011-06-14T18:59:34.140Z",
"answer_score": 1185
} |
Please answer the following Stack Overflow question:
Title: Add a new element to an array without specifying the index in Bash
<p>Is there a way to do something like PHPs <code>$array[] = 'foo';</code> in bash vs doing:</p>
<pre><code>array[0]='foo'
array[1]='bar'
</code></pre> | <p>Yes there is:</p>
<pre><code>ARRAY=()
ARRAY+=('foo')
ARRAY+=('bar')
</code></pre>
<p><a href="http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameters" rel="noreferrer">Bash Reference Manual</a>:</p>
<blockquote>
<p>In the context where an assignment statement is assigning a value to a shell variable or array index (see Arrays), the ‘+=’ operator can be used to append to or add to the variable's previous value.</p>
</blockquote>
<p>Also:</p>
<blockquote>
<p>When += is applied to an array variable using compound assignment (see Arrays below), the variable's value is not unset (as it is when using =), and new values are appended to the array beginning at one greater than the array's maximum index (for indexed arrays)</p>
</blockquote> | {
"question_id": 1951506,
"question_date": "2009-12-23T08:59:32.787Z",
"question_score": 923,
"tags": "bash|arrays",
"answer_id": 1951523,
"answer_date": "2009-12-23T09:02:55.477Z",
"answer_score": 1775
} |
Please answer the following Stack Overflow question:
Title: Download old version of package with NuGet
<p>Is there a way to download a previous version of a package with <strong>NuGet</strong>, not the latest one?</p> | <p>Bring up the Package Manager Console in Visual Studio - it's in Tools / NuGet Package Manager / Package Manager Console. Then run the Install-Package command:</p>
<pre><code>Install-Package Common.Logging -Version 1.2.0
</code></pre>
<p>See the <a href="http://docs.nuget.org/docs/reference/package-manager-console-powershell-reference" rel="noreferrer">command reference</a> for details.</p>
<p>Edit:
In order to list versions of a package you can use the Get-Package command with <strike>the remote argument and</strike> a filter:</p>
<pre><code>Get-Package -ListAvailable -Filter Common.Logging -AllVersions
</code></pre>
<p>By pressing tab after the version option in the <code>Install-Package</code> command, you get a list of the latest available versions.</p> | {
"question_id": 5628689,
"question_date": "2011-04-11T23:18:54.703Z",
"question_score": 923,
"tags": "nuget",
"answer_id": 5635453,
"answer_date": "2011-04-12T12:50:42.373Z",
"answer_score": 1127
} |
Please answer the following Stack Overflow question:
Title: How to align a <div> to the middle (horizontally/width) of the page
<p>I have a <code>div</code> tag with <code>width</code> set to <strong>800 pixels</strong>. When the browser width is greater than <strong>800 pixels</strong>, it shouldn't stretch the <code>div</code>, but it should bring it to the middle of the page.</p> | <pre><code><body>
<div style="width:800px; margin:0 auto;">
centered content
</div>
</body>
</code></pre> | {
"question_id": 953918,
"question_date": "2009-06-05T01:44:38.433Z",
"question_score": 922,
"tags": "css|html|alignment|center",
"answer_id": 953934,
"answer_date": "2009-06-05T01:49:10.453Z",
"answer_score": 1214
} |
Please answer the following Stack Overflow question:
Title: Reading settings from app.config or web.config in .NET
<p>I'm working on a C# class library that needs to be able to read settings from the <code>web.config</code> or <code>app.config</code> file (depending on whether the DLL is referenced from an ASP.NET web application or a Windows Forms application).</p>
<p>I've found that</p>
<pre><code>ConfigurationSettings.AppSettings.Get("MySetting")
</code></pre>
<p>works, but that code has been marked as deprecated by Microsoft.</p>
<p>I've read that I should be using:</p>
<pre><code>ConfigurationManager.AppSettings["MySetting"]
</code></pre>
<p>However, the <code>System.Configuration.ConfigurationManager</code> class doesn't seem to be available from a C# Class Library project.</p>
<p>What is the best way to do this?</p> | <p>You'll need to <strong>add a reference</strong> to <code>System.Configuration</code> in your project's <strong>references folder</strong>. </p>
<p>You should definitely be using the <code>ConfigurationManager</code> over the obsolete <code>ConfigurationSettings</code>.</p> | {
"question_id": 1189364,
"question_date": "2009-07-27T16:58:44.830Z",
"question_score": 922,
"tags": "c#|.net|configuration|appsettings",
"answer_id": 1189369,
"answer_date": "2009-07-27T17:00:39.897Z",
"answer_score": 872
} |
Please answer the following Stack Overflow question:
Title: How do I convert a datetime to date?
<p>How do I convert a <code>datetime.datetime</code> object (e.g., the return value of <code>datetime.datetime.now())</code> to a <code>datetime.date</code> object in Python?</p> | <p>Use the <a href="https://docs.python.org/3/library/datetime.html#datetime.datetime.date" rel="noreferrer"><code>date()</code></a> method:</p>
<pre><code>datetime.datetime.now().date()
</code></pre> | {
"question_id": 3743222,
"question_date": "2010-09-18T19:44:01.293Z",
"question_score": 922,
"tags": "python|datetime",
"answer_id": 3743240,
"answer_date": "2010-09-18T19:47:40.633Z",
"answer_score": 1416
} |
Please answer the following Stack Overflow question:
Title: Why is null an object and what's the difference between null and undefined?
<p>Why is <code>null</code> considered an <code>object</code> in JavaScript?</p>
<p>Is checking </p>
<pre><code>if ( object == null )
Do something
</code></pre>
<p>the same as </p>
<pre><code>if ( !object )
Do something
</code></pre>
<p>?</p>
<p>And also:</p>
<p>What is the difference between <code>null</code> and <code>undefined</code>?</p> | <pre><code>(name is undefined)
</code></pre>
<p><strong>You:</strong> What is <code>name</code>?<sup> (*)</sup><br />
<strong>JavaScript:</strong> <code>name</code>? What's a <code>name</code>? I don't know what you're talking about. You haven't ever mentioned any <code>name</code> before. Are you seeing some other scripting language on the (client-)side?</p>
<pre><code>name = null;
</code></pre>
<p><strong>You:</strong> What is <code>name</code>?<br />
<strong>JavaScript:</strong> I don't know.</p>
<p>In short; <code>undefined</code> is where no notion of the thing exists; it has no type, and it's never been referenced before in that scope; <code>null</code> is where the thing is known to exist, but it's not known what the value is.</p>
<p>One thing to remember is that <code>null</code> is not, conceptually, the same as <code>false</code> or <code>""</code> or such, even if they equate after type casting, i.e.</p>
<pre><code>name = false;
</code></pre>
<p><strong>You:</strong> What is <code>name</code>?<br />
<strong>JavaScript:</strong> Boolean false.</p>
<pre><code>name = '';
</code></pre>
<p><strong>You:</strong> What is <code>name</code>?<br />
<strong>JavaScript:</strong> Empty string</p>
<hr />
<p><sup>*: <code>name</code> in this context is meant as a variable which has never been defined. It could be any undefined variable, however, name is a property of just about any HTML form element. It goes way, way back and was instituted well before id. It is useful because ids must be unique but names do not have to be.
</sup></p> | {
"question_id": 801032,
"question_date": "2009-04-29T05:47:08.843Z",
"question_score": 922,
"tags": "javascript|object|null|undefined|typeof",
"answer_id": 802371,
"answer_date": "2009-04-29T13:31:20.257Z",
"answer_score": 1525
} |
Please answer the following Stack Overflow question:
Title: Running unittest with typical test directory structure
<p>The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own <code>test</code> directory:</p>
<pre><code>new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
</code></pre>
<p>My question is simply <strong>What's the usual way of actually running the tests?</strong> I suspect this is obvious to everyone except me, but you can't just run <code>python test_antigravity.py</code> from the test directory as its <code>import antigravity</code> will fail as the module is not on the path.</p>
<p>I know I could modify PYTHONPATH and other search path related tricks, but I can't believe that's the simplest way - it's fine if you're the developer but not realistic to expect your users to use if they just want to check the tests are passing.</p>
<p>The other alternative is just to copy the test file into the other directory, but it seems a bit dumb and misses the point of having them in a separate directory to start with.</p>
<p>So, if you had just downloaded the source to my new project how would you run the unit tests? I'd prefer an answer that would let me say to my users: "To run the unit tests do X."</p> | <p>The best solution in my opinion is to use the <code>unittest</code> <a href="https://docs.python.org/2/library/unittest.html#command-line-interface" rel="noreferrer">command line interface</a> which will add the directory to the <code>sys.path</code> so you don't have to (done in the <code>TestLoader</code> class).</p>
<p>For example for a directory structure like this:</p>
<pre><code>new_project
├── antigravity.py
└── test_antigravity.py
</code></pre>
<p>You can just run:</p>
<pre><code>$ cd new_project
$ python -m unittest test_antigravity
</code></pre>
<p>For a directory structure like yours:</p>
<pre><code>new_project
├── antigravity
│ ├── __init__.py # make it a package
│ └── antigravity.py
└── test
├── __init__.py # also make test a package
└── test_antigravity.py
</code></pre>
<p>And in the test modules inside the <code>test</code> package, you can import the <code>antigravity</code> package and its modules as usual:</p>
<pre><code># import the package
import antigravity
# import the antigravity module
from antigravity import antigravity
# or an object inside the antigravity module
from antigravity.antigravity import my_object
</code></pre>
<p><strong>Running a single test module:</strong></p>
<p>To run a single test module, in this case <code>test_antigravity.py</code>:</p>
<pre><code>$ cd new_project
$ python -m unittest test.test_antigravity
</code></pre>
<p>Just reference the test module the same way you import it.</p>
<p><strong>Running a single test case or test method:</strong></p>
<p>Also you can run a single <code>TestCase</code> or a single test method:</p>
<pre><code>$ python -m unittest test.test_antigravity.GravityTestCase
$ python -m unittest test.test_antigravity.GravityTestCase.test_method
</code></pre>
<p><strong>Running all tests:</strong></p>
<p>You can also use <a href="https://docs.python.org/2/library/unittest.html#test-discovery" rel="noreferrer">test discovery</a> which will discover and run all the tests for you, they must be modules or packages named <code>test*.py</code> (can be changed with the <code>-p, --pattern</code> flag):</p>
<pre><code>$ cd new_project
$ python -m unittest discover
$ # Also works without discover for Python 3
$ # as suggested by @Burrito in the comments
$ python -m unittest
</code></pre>
<p>This will run all the <code>test*.py</code> modules inside the <code>test</code> package.</p> | {
"question_id": 1896918,
"question_date": "2009-12-13T16:10:23.637Z",
"question_score": 922,
"tags": "python|unit-testing",
"answer_id": 24266885,
"answer_date": "2014-06-17T14:49:19.903Z",
"answer_score": 845
} |
Please answer the following Stack Overflow question:
Title: Is there a list of Pytz Timezones?
<p>I would like to know what are all the possible values for the timezone argument in the Python library pytz. How to do it?</p> | <p>You can list all the available timezones with <code>pytz.all_timezones</code>:</p>
<pre><code>In [40]: import pytz
In [41]: pytz.all_timezones
Out[42]:
['Africa/Abidjan',
'Africa/Accra',
'Africa/Addis_Ababa',
...]
</code></pre>
<p>There is also <code>pytz.common_timezones</code>:</p>
<pre><code>In [45]: len(pytz.common_timezones)
Out[45]: 403
In [46]: len(pytz.all_timezones)
Out[46]: 563
</code></pre> | {
"question_id": 13866926,
"question_date": "2012-12-13T19:24:37.697Z",
"question_score": 921,
"tags": "python|django|pytz",
"answer_id": 13867319,
"answer_date": "2012-12-13T19:49:16.070Z",
"answer_score": 537
} |
Please answer the following Stack Overflow question:
Title: "Conversion to Dalvik format failed with error 1" on external JAR
<p>In my Android application in Eclipse, I get the following error.</p>
<blockquote>
<p>UNEXPECTED TOP-LEVEL EXCEPTION:<br/>
java.lang.IllegalArgumentException: already added: Lorg/xmlpull/v1/XmlPullParser;<br/>
....<br/>
Conversion to Dalvik format failed with error 1<br/></p>
</blockquote>
<p>This error only appears when I add a specific external JAR file to my project. I searched for a long time for a possible solution, but none of them work.</p>
<p>I even tried to change to Android 1.6 instead of 1.5 (the current version I use).</p> | <p>I solved the problem.</p>
<p>This is a JAR file conflict.</p>
<p>It seems that I have two JAR files on my buildpath that include the same package and classes.</p>
<p><code>smack.jar</code> and <code>android_maps_lib-1.0.2</code></p>
<p>Deleting this package from one of the JAR files solved the problem.</p> | {
"question_id": 2680827,
"question_date": "2010-04-21T06:47:05.563Z",
"question_score": 921,
"tags": "android|dalvik|illegalargumentexception|android-sdk-1.6",
"answer_id": 2681165,
"answer_date": "2010-04-21T07:55:13.320Z",
"answer_score": 274
} |
Please answer the following Stack Overflow question:
Title: What is the (function() { } )() construct in JavaScript?
<p>I would like to know what this means:</p>
<pre><code>(function () {
})();
</code></pre>
<p>Is this basically saying <code>document.onload</code>?</p> | <p>It’s an <a href="http://benalman.com/news/2010/11/immediately-invoked-function-expression/" rel="noreferrer">Immediately-Invoked Function Expression</a>, or <a href="https://en.wikipedia.org/wiki/Immediately-invoked_function_expression" rel="noreferrer"><strong>IIFE</strong></a> for short. It executes immediately after it’s created.</p>
<p>It has nothing to do with any event-handler for any events (such as <code>document.onload</code>).<br>
Consider the part within the first pair of parentheses: <code>(<b>function(){}</b>)();</code>....it is a regular function expression. Then look at the last pair <code>(function(){})<b>()</b>;</code>, this is normally added to an expression to call a function; in this case, our prior expression.</p>
<p>This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other <em>normal</em> function) are not visible outside its scope.<br>
This is why, maybe, you confused this construction with an event-handler for <code>window.onload</code>, because it’s often used as this: </p>
<pre><code>(function(){
// all your code here
var foo = function() {};
window.onload = foo;
// ...
})();
// foo is unreachable here (it’s undefined)
</code></pre>
<p><strong>Correction suggested by <a href="https://stackoverflow.com/users/69083/guffa">Guffa</a>:</strong></p>
<blockquote>
<p>The function is executed right after it's created, not after it is parsed. The entire script block is parsed before any code in it is executed. Also, parsing code doesn't automatically mean that it's executed, if for example the IIFE is inside a function then it won't be executed until the function is called.</p>
</blockquote>
<p><strong>Update</strong>
Since this is a pretty popular topic, it's worth mentioning that IIFE's can also be written with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions" rel="noreferrer">ES6's arrow function</a> (like <a href="https://stackoverflow.com/users/368691/gajus">Gajus</a> has pointed out <a href="https://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript/8228308#comment43521302_8228308">in a comment</a>) :</p>
<pre><code>((foo) => {
// do something with foo here foo
})('foo value')
</code></pre> | {
"question_id": 8228281,
"question_date": "2011-11-22T14:19:11.947Z",
"question_score": 921,
"tags": "javascript|iife",
"answer_id": 8228308,
"answer_date": "2011-11-22T14:21:01.617Z",
"answer_score": 964
} |
Please answer the following Stack Overflow question:
Title: How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?
<p>For some reason, when I initially did a pull from the repository for a git project of mine,
I got a ton of files in my working copy that have no discernible changes made to them, but keep showing up in my <code>unstaged changes</code> area. </p>
<p>I'm using Git Gui on Windows xp, and when I go to look at the file to see what has changed.
All I see is:</p>
<pre><code>old mode 100755
new mode 100644
</code></pre>
<p>Does anyone know what this means? </p>
<p>How can I get these files out of my list of unstaged changes? (Very annoying to have to go through 100's of files, just to pick out files I've recently edited and want to commit). </p> | <p>That looks like unix file permissions modes to me (<code>755</code>=<code>rwxr-xr-x</code>, <code>644</code>=<code>rw-r--r--</code>) - the old mode included the +x (executable) flag, the new mode doesn't.</p>
<p><a href="https://groups.google.com/forum/#!topic/msysgit/hrnEguNBNmw" rel="noreferrer">This msysgit issue's replies</a> suggests setting core.filemode to false in order to get rid of the issue:</p>
<pre><code>git config core.filemode false
</code></pre> | {
"question_id": 1257592,
"question_date": "2009-08-10T22:30:03.723Z",
"question_score": 921,
"tags": "git|git-gui",
"answer_id": 1257613,
"answer_date": "2009-08-10T22:34:45.897Z",
"answer_score": 1616
} |
Please answer the following Stack Overflow question:
Title: Simplest code for array intersection in javascript
<p>What's the simplest, library-free code for implementing array intersections in javascript? I want to write</p>
<pre><code>intersection([1,2,3], [2,3,4,5])
</code></pre>
<p>and get</p>
<pre><code>[2, 3]
</code></pre> | <p>Use a combination of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" rel="noreferrer"><code>Array.prototype.filter</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes" rel="noreferrer"><code>Array.prototype.includes</code></a>:</p>
<pre><code>const filteredArray = array1.filter(value => array2.includes(value));
</code></pre>
<p>For older browsers, with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf" rel="noreferrer"><code>Array.prototype.indexOf</code></a> and without an arrow function:</p>
<pre><code>var filteredArray = array1.filter(function(n) {
return array2.indexOf(n) !== -1;
});
</code></pre>
<p>NB! Both <code>.includes</code> and <code>.indexOf</code> internally compares elements in the array by using <code>===</code>, so if the array contains objects it will only compare object references (not their content). If you want to specify your own comparison logic, use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some" rel="noreferrer"><code>Array.prototype.some</code></a> instead.</p> | {
"question_id": 1885557,
"question_date": "2009-12-11T03:04:04.823Z",
"question_score": 920,
"tags": "javascript|data-structures|intersection",
"answer_id": 1885569,
"answer_date": "2009-12-11T03:08:37.137Z",
"answer_score": 1712
} |
Please answer the following Stack Overflow question:
Title: What's the difference between map() and flatMap() methods in Java 8?
<p>In Java 8, what's the difference between <a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#map-java.util.function.Function-" rel="noreferrer"><code>Stream.map()</code></a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#flatMap-java.util.function.Function-" rel="noreferrer"><code>Stream.flatMap()</code></a> methods?</p> | <p>Both <code>map</code> and <code>flatMap</code> can be applied to a <code>Stream<T></code> and they both return a <code>Stream<R></code>. The difference is that the <code>map</code> operation produces one output value for each input value, whereas the <code>flatMap</code> operation produces an arbitrary number (zero or more) values for each input value.</p>
<p>This is reflected in the arguments to each operation.</p>
<p>The <code>map</code> operation takes a <code>Function</code>, which is called for each value in the input stream and produces one result value, which is sent to the output stream.</p>
<p>The <code>flatMap</code> operation takes a function that conceptually wants to consume one value and produce an arbitrary number of values. However, in Java, it's cumbersome for a method to return an arbitrary number of values, since methods can return only zero or one value. One could imagine an API where the mapper function for <code>flatMap</code> takes a value and returns an array or a <code>List</code> of values, which are then sent to the output. Given that this is the streams library, a particularly apt way to represent an arbitrary number of return values is for the mapper function itself to return a stream! The values from the stream returned by the mapper are drained from the stream and are passed to the output stream. The "clumps" of values returned by each call to the mapper function are not distinguished at all in the output stream, thus the output is said to have been "flattened."</p>
<p>Typical use is for the mapper function of <code>flatMap</code> to return <code>Stream.empty()</code> if it wants to send zero values, or something like <code>Stream.of(a, b, c)</code> if it wants to return several values. But of course any stream can be returned.</p> | {
"question_id": 26684562,
"question_date": "2014-10-31T22:53:15.110Z",
"question_score": 920,
"tags": "java|java-8|java-stream",
"answer_id": 26684710,
"answer_date": "2014-10-31T23:11:42.697Z",
"answer_score": 1011
} |
Please answer the following Stack Overflow question:
Title: How to send an object from one Android Activity to another using Intents?
<blockquote>
<p>How can I pass an object of a custom type from one <a href="https://developer.android.com/reference/android/app/Activity.html" rel="noreferrer">Activity</a> to another using the <code>putExtra()</code> method of the class <a href="https://developer.android.com/reference/android/content/Intent.html" rel="noreferrer">Intent</a>?</p>
</blockquote> | <p>the most easiest solution i found is..
to create a class with static data members with getters setters.</p>
<p>set from one activity and get from another activity that object.</p>
<p>activity A</p>
<pre><code>mytestclass.staticfunctionSet("","",""..etc.);
</code></pre>
<p>activity b</p>
<pre><code>mytestclass obj= mytestclass.staticfunctionGet();
</code></pre> | {
"question_id": 2139134,
"question_date": "2010-01-26T11:52:01.567Z",
"question_score": 919,
"tags": "android|android-intent|android-activity",
"answer_id": 2236529,
"answer_date": "2010-02-10T11:52:00.863Z",
"answer_score": 5
} |
Please answer the following Stack Overflow question:
Title: How to run a PowerShell script
<p>How do I run a PowerShell script?</p>
<ul>
<li>I have a script named myscript.ps1</li>
<li>I have all the necessary frameworks installed</li>
<li>I set that <a href="https://stackoverflow.com/questions/10635/why-dont-my-powershell-scripts-run">execution policy</a> thing</li>
<li>I have followed the instructions on <a href="http://technet.microsoft.com/en-us/library/ee176949.aspx" rel="noreferrer">this MSDN help page</a>
and am trying to run it like so:
<code>powershell.exe 'C:\my_path\yada_yada\run_import_script.ps1'</code> (with or without <code>--noexit</code>)</li>
</ul>
<p>which returns exactly nothing, except that the file name is output.</p>
<p>No error, no message, nothing. Oh, when I add <code>-noexit</code>, the same thing happens, but I remain within PowerShell and have to exit manually.</p>
<p>The .ps1 file is supposed to run a program and return the error level dependent on that program's output. But I'm quite sure I'm not even getting there yet.</p>
<p>What am I doing wrong?</p> | <p>Prerequisites:</p>
<ul>
<li>You need to be able to run PowerShell as an administrator</li>
<li>You need to set your PowerShell execution policy to a permissive value or be able to bypass it</li>
</ul>
<p>Steps:</p>
<ol>
<li><p>Launch Windows PowerShell as an Administrator, and wait for the <code>PS></code> prompt to appear</p>
</li>
<li><p>Navigate within PowerShell to the directory where the script lives:</p>
<pre><code>PS> cd C:\my_path\yada_yada\ (enter)
</code></pre>
</li>
<li><p>Execute the script:</p>
<pre><code>PS> .\run_import_script.ps1 (enter)
</code></pre>
</li>
</ol>
<p>Or: you can run the PowerShell script from the Command Prompt (<code>cmd.exe</code>) like this:</p>
<pre><code>powershell -noexit "& ""C:\my_path\yada_yada\run_import_script.ps1""" (enter)
</code></pre>
<p>according to <a href="http://poshoholic.com/2007/09/27/invoking-a-powershell-script-from-cmdexe-or-start-run/" rel="noreferrer"><em>Invoking a PowerShell script from cmd.exe (or Start | Run)</em></a> by Kirk Munro.</p>
<p>Or you could even <a href="http://www.codeproject.com/KB/threads/AsyncPowerShell.aspx" rel="noreferrer">run your PowerShell script asynchronously from your C# application</a>.</p> | {
"question_id": 2035193,
"question_date": "2010-01-09T22:19:10.270Z",
"question_score": 918,
"tags": "windows|powershell|scripting",
"answer_id": 2035209,
"answer_date": "2010-01-09T22:24:43.230Z",
"answer_score": 934
} |
Please answer the following Stack Overflow question:
Title: What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?
<p>Can anybody give a clear explanation of how variable assignment really works in Makefiles. </p>
<p>What is the difference between :</p>
<pre><code> VARIABLE = value
VARIABLE ?= value
VARIABLE := value
VARIABLE += value
</code></pre>
<p>I have read the <a href="http://www.gnu.org/software/make/manual/make.html#Reading-Makefiles" rel="noreferrer">section</a> in GNU Make's manual, but it still doesn't make sense to me. </p> | <h3>Lazy Set</h3>
<pre><code>VARIABLE = value
</code></pre>
<p>Normal setting of a variable, but any other variables mentioned with the <code>value</code> field are recursively expanded with their value at the point at which the variable is used, not the one it had when it was declared</p>
<h3>Immediate Set</h3>
<pre><code>VARIABLE := value
</code></pre>
<p>Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.</p>
<h3>Lazy Set If Absent</h3>
<pre><code>VARIABLE ?= value
</code></pre>
<p>Setting of a variable only if it doesn't have a value. <code>value</code> is always evaluated when <code>VARIABLE</code> is accessed. It is equivalent to</p>
<pre><code>ifeq ($(origin VARIABLE), undefined)
VARIABLE = value
endif
</code></pre>
<p>See the <a href="https://www.gnu.org/software/make/manual/html_node/Flavors.html#Flavors" rel="noreferrer">documentation</a> for more details.</p>
<h3>Append</h3>
<pre><code>VARIABLE += value
</code></pre>
<p>Appending the supplied value to the existing value (or setting to that value if the variable didn't exist)</p> | {
"question_id": 448910,
"question_date": "2009-01-15T23:19:02.147Z",
"question_score": 918,
"tags": "makefile|gnu-make",
"answer_id": 448939,
"answer_date": "2009-01-15T23:25:35.207Z",
"answer_score": 1192
} |
Please answer the following Stack Overflow question:
Title: Strip all non-numeric characters from string in JavaScript
<p>Consider a non-DOM scenario where you'd want to remove all non-numeric characters from a string using JavaScript/ECMAScript. Any characters that are in range <code>0 - 9</code> should be kept.</p>
<pre><code>var myString = 'abc123.8<blah>';
//desired output is 1238
</code></pre>
<p>How would you achieve this in plain JavaScript? Please remember this is a non-DOM scenario, so jQuery and other solutions involving browser and keypress events aren't suitable.</p> | <p>Use the string's <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace" rel="noreferrer"><code>.replace</code></a> method with a regex of <code>\D</code>, which is a shorthand character class that matches all non-digits:</p>
<pre><code>myString = myString.replace(/\D/g,'');
</code></pre> | {
"question_id": 1862130,
"question_date": "2009-12-07T18:59:47.977Z",
"question_score": 917,
"tags": "javascript|string",
"answer_id": 1862219,
"answer_date": "2009-12-07T19:14:20.370Z",
"answer_score": 1850
} |
Please answer the following Stack Overflow question:
Title: In a Git repository, how to properly rename a directory?
<p>I think it should work to copy the directory to be renamed to a new directory with desired name, and <a href="https://stackoverflow.com/questions/1947430/git-remove-directory">delete the old directory</a>, and <code>git add</code>, <code>git commit</code> and <code>push</code> everything. But is this the best way?</p> | <p>Basic rename (or move):</p>
<pre><code>git mv <old name> <new name>
</code></pre>
<p>Case sensitive rename—eg. from <code>casesensitive</code> to <code>CaseSensitive</code>—you must use a two step:</p>
<pre><code>git mv casesensitive tmp
git mv tmp CaseSensitive
</code></pre>
<p>(<a href="https://stackoverflow.com/a/17688308/101290">More about case sensitivity in Git…</a>)</p>
<p>…followed by commit and push would be the simplest way to rename a directory in a git repo.</p> | {
"question_id": 11183788,
"question_date": "2012-06-25T05:15:06.927Z",
"question_score": 917,
"tags": "git|directory|rename",
"answer_id": 11183844,
"answer_date": "2012-06-25T05:22:38.827Z",
"answer_score": 1728
} |
Please answer the following Stack Overflow question:
Title: A for-loop to iterate over an enum in Java
<p>I have an <code>enum</code> in Java for the cardinal and intermediate directions:</p>
<pre><code>public enum Direction {
NORTH,
NORTHEAST,
EAST,
SOUTHEAST,
SOUTH,
SOUTHWEST,
WEST,
NORTHWEST
}
</code></pre>
<p>How can I write a <code>for</code> loop that iterates through each of these <code>enum</code> values?</p> | <h1><code>.values()</code></h1>
<p>You can call the <code>values()</code> method on your enum.</p>
<pre><code>for (Direction dir : Direction.values()) {
// do what you want
}
</code></pre>
<p>This <code>values()</code> method is <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.9.3" rel="noreferrer">implicitly declared by the compiler</a>. So it is not listed on <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html" rel="noreferrer"><code>Enum</code></a> doc. </p> | {
"question_id": 1104975,
"question_date": "2009-07-09T16:24:03.107Z",
"question_score": 917,
"tags": "java|loops|for-loop|enums",
"answer_id": 1104994,
"answer_date": "2009-07-09T16:27:15.737Z",
"answer_score": 1466
} |
Please answer the following Stack Overflow question:
Title: How do I hide certain files from the sidebar in Visual Studio Code?
<p>In <strong>Visual Studio Code</strong>, what setting can be configured, using file patterns, to hide files from view in the sidebar's file-explorer?</p>
<p>I would like to hide certain groups of files, like <code>.meta</code> and <code>.git</code> files.</p> | <p>You can configure patterns to hide files and folders from the explorer and searches. </p>
<ol>
<li>Open VS User Settings (Main menu: <code>File > Preferences > Settings</code>). This will open the setting screen.</li>
<li>Search for <code>files:exclude</code> in the search at the top.</li>
<li>Configure the User Setting with new glob patterns as needed. In this case add this pattern <code>node_modules/</code> then click OK. <em>The pattern syntax is powerful. You can find pattern matching details under the <a href="https://code.visualstudio.com/Docs/editor/codebasics#_search-across-files" rel="noreferrer">Search Across Files topic</a>.</em> </li>
</ol>
<p>When you are done it should look something like this:
<a href="https://i.stack.imgur.com/xHli0.png" rel="noreferrer"><img src="https://i.stack.imgur.com/xHli0.png" alt="enter image description here"></a></p>
<p>If you want to directly edit the settings file:
For example to hide a top level node_modules folder in your workspace:</p>
<pre><code>"files.exclude": {
"node_modules/": true
}
</code></pre>
<p>To hide all files that start with <code>._</code> such as <code>._.DS_Store</code> files found on OSX:</p>
<pre><code>"files.exclude": {
"**/._*": true
}
</code></pre>
<p>You also have the ability to change Workspace Settings (Main menu: <code>File > Preferences > Workspace Settings</code>). Workspace settings will create a <code>.vscode/settings.json</code> file in your current workspace and will only be applied to that workspace. User Settings will be applied globally to any instance of VS Code you open, but they won't override Workspace Settings if present. Read more on customizing <a href="https://code.visualstudio.com/Docs/customization/userandworkspace" rel="noreferrer">User and Workspace Settings</a>.</p> | {
"question_id": 30140112,
"question_date": "2015-05-09T12:48:42.370Z",
"question_score": 917,
"tags": "visual-studio-code|configuration",
"answer_id": 30142299,
"answer_date": "2015-05-09T16:18:54.567Z",
"answer_score": 1518
} |
Please answer the following Stack Overflow question:
Title: How to ignore certain files in Git
<p>I have a repository with a file, <code>Hello.java</code>. When I compile it, an additional <code>Hello.class</code> file is generated.</p>
<p>I created an entry for <code>Hello.class</code> in a <code>.gitignore</code> file. However, the file still appears to be tracked.</p>
<p>How can I make Git ignore <code>Hello.class</code>?</p> | <p>The problem is that <code>.gitignore</code> ignores just files that weren't tracked before (by <code>git add</code>). Run <code>git reset name_of_file</code> to unstage the file and keep it. In case you want to also remove the given file from the repository (after pushing), use <code>git rm --cached name_of_file</code>.</p> | {
"question_id": 4308610,
"question_date": "2010-11-29T22:12:24.377Z",
"question_score": 916,
"tags": "git|gitignore",
"answer_id": 4308645,
"answer_date": "2010-11-29T22:16:57.660Z",
"answer_score": 985
} |
Please answer the following Stack Overflow question:
Title: "INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
<p>While executing an <code>INSERT</code> statement with many rows, I want to skip duplicate entries that would otherwise cause failure. After some research, my options appear to be the use of either:</p>
<ul>
<li><code>ON DUPLICATE KEY UPDATE</code> which implies an unnecessary update at some cost, or</li>
<li><code>INSERT IGNORE</code> implies an invitation for other kinds of failure to slip in unannounced.</li>
</ul>
<p>Am I right in these assumptions? What's the best way to simply skip the rows that might cause duplicates and just continue on to the other rows?</p> | <p>I would recommend using <code>INSERT...ON DUPLICATE KEY UPDATE</code>.</p>
<p>If you use <code>INSERT IGNORE</code>, then the row won't actually be inserted if it results in a duplicate key. But the statement won't generate an error. It generates a warning instead. These cases include:</p>
<ul>
<li>Inserting a duplicate key in columns with <code>PRIMARY KEY</code> or <code>UNIQUE</code> constraints. </li>
<li>Inserting a NULL into a column with a <code>NOT NULL</code> constraint.</li>
<li>Inserting a row to a partitioned table, but the values you insert don't map to a partition.</li>
</ul>
<p>If you use <code>REPLACE</code>, MySQL actually does a <code>DELETE</code> followed by an <code>INSERT</code> internally, which has some unexpected side effects: </p>
<ul>
<li>A new auto-increment ID is allocated.</li>
<li>Dependent rows with foreign keys may be deleted (if you use cascading foreign keys) or else prevent the <code>REPLACE</code>.</li>
<li>Triggers that fire on <code>DELETE</code> are executed unnecessarily.</li>
<li>Side effects are propagated to replicas too.</li>
</ul>
<p><strong>correction:</strong> both <code>REPLACE</code> and <code>INSERT...ON DUPLICATE KEY UPDATE</code> are non-standard, proprietary inventions specific to MySQL. ANSI SQL 2003 defines a <code>MERGE</code> statement that can solve the same need (and more), but MySQL does not support the <code>MERGE</code> statement.</p>
<hr>
<p>A user tried to edit this post (the edit was rejected by moderators). The edit tried to add a claim that <code>INSERT...ON DUPLICATE KEY UPDATE</code> causes a new auto-increment id to be allocated. It's true that the new id is <em>generated</em>, but it is not used in the changed row.</p>
<p>See demonstration below, tested with Percona Server 5.5.28. The configuration variable <code>innodb_autoinc_lock_mode=1</code> (the default):</p>
<pre><code>mysql> create table foo (id serial primary key, u int, unique key (u));
mysql> insert into foo (u) values (10);
mysql> select * from foo;
+----+------+
| id | u |
+----+------+
| 1 | 10 |
+----+------+
mysql> show create table foo\G
CREATE TABLE `foo` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`u` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `u` (`u`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
mysql> insert into foo (u) values (10) on duplicate key update u = 20;
mysql> select * from foo;
+----+------+
| id | u |
+----+------+
| 1 | 20 |
+----+------+
mysql> show create table foo\G
CREATE TABLE `foo` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`u` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `u` (`u`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
</code></pre>
<p>The above demonstrates that the IODKU statement detects the duplicate, and invokes the update to change the value of <code>u</code>. Note the <code>AUTO_INCREMENT=3</code> indicates an id was generated, but not used in the row.</p>
<p>Whereas <code>REPLACE</code> does delete the original row and inserts a new row, generating <em>and</em> storing a new auto-increment id:</p>
<pre><code>mysql> select * from foo;
+----+------+
| id | u |
+----+------+
| 1 | 20 |
+----+------+
mysql> replace into foo (u) values (20);
mysql> select * from foo;
+----+------+
| id | u |
+----+------+
| 3 | 20 |
+----+------+
</code></pre> | {
"question_id": 548541,
"question_date": "2009-02-14T05:24:06.610Z",
"question_score": 916,
"tags": "mysql|insert",
"answer_id": 548570,
"answer_date": "2009-02-14T05:51:40.427Z",
"answer_score": 1082
} |
Please answer the following Stack Overflow question:
Title: Dynamically access object property using variable
<p>I'm trying to access a property of an object using a dynamic name. Is this possible?</p>
<pre><code>const something = { bar: "Foobar!" };
const foo = 'bar';
something.foo; // The idea is to access something.bar, getting "Foobar!"
</code></pre> | <p>There are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors" rel="noreferrer">two ways to access properties</a> of an object:</p>
<ul>
<li>Dot notation: <code>something.bar</code></li>
<li>Bracket notation: <code>something['bar']</code></li>
</ul>
<p>The value between the brackets can be any expression. Therefore, if the property name is stored in a variable, you have to use bracket notation:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var something = {
bar: 'foo'
};
var foo = 'bar';
// both x = something[foo] and something[foo] = x work as expected
console.log(something[foo]);
console.log(something.bar)</code></pre>
</div>
</div>
</p> | {
"question_id": 4244896,
"question_date": "2010-11-22T11:23:32.270Z",
"question_score": 916,
"tags": "javascript|object|properties",
"answer_id": 4244912,
"answer_date": "2010-11-22T11:25:44.507Z",
"answer_score": 1231
} |
Please answer the following Stack Overflow question:
Title: What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?
<p>There are three assembly version attributes. What are differences? Is it ok if I use <code>AssemblyVersion</code> and ignore the rest?</p>
<hr>
<p>MSDN says:</p>
<ul>
<li><p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assemblyversionattribute" rel="noreferrer">AssemblyVersion</a>:</p>
<blockquote>
<p>Specifies the version of the assembly being attributed. </p>
</blockquote></li>
<li><p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assemblyfileversionattribute" rel="noreferrer">AssemblyFileVersion</a>:</p>
<blockquote>
<p>Instructs a compiler to use a specific version number for the Win32 file version resource. The Win32 file version is not required to be the same as the assembly's version number. </p>
</blockquote></li>
<li><p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.reflection.assemblyinformationalversionattribute" rel="noreferrer">AssemblyInformationalVersion</a>:</p>
<blockquote>
<p>Defines additional version information for an assembly manifest. </p>
</blockquote></li>
</ul>
<hr>
<p><em>This is a follow-up to <a href="https://stackoverflow.com/questions/62353/what-are-the-best-practices-for-using-assembly-attributes">What are the best practices for using Assembly Attributes?</a></em></p> | <p><strong>AssemblyVersion</strong></p>
<p>Where other assemblies that reference your assembly will look. If this number changes, other assemblies must update their references to your assembly! Only update this version if it breaks backward compatibility. The <code>AssemblyVersion</code> is required.</p>
<p>I use the format: <em>major.minor</em> (and <em>major</em> for very stable codebases). This would result in:</p>
<pre><code>[assembly: AssemblyVersion("1.3")]
</code></pre>
<p>If you're following <a href="https://semver.org/" rel="noreferrer">SemVer</a> strictly then this means you only update when the <em>major</em> changes, so 1.0, 2.0, 3.0, etc.</p>
<p><strong>AssemblyFileVersion</strong></p>
<p>Used for deployment (like setup programs). You can increase this number for every deployment. Use it to mark assemblies that have the same <code>AssemblyVersion</code> but are generated from different builds and/or code.</p>
<p>In Windows, it can be viewed in the file properties.</p>
<p>The AssemblyFileVersion is optional. If not given, the AssemblyVersion is used.</p>
<p>I use the format: <em>major.minor.patch.build</em>, where I follow <a href="https://semver.org/" rel="noreferrer">SemVer</a> for the first three parts and use the buildnumber of the buildserver for the last part (0 for local build).
This would result in:</p>
<pre><code>[assembly: AssemblyFileVersion("1.3.2.42")]
</code></pre>
<p>Be aware that <a href="https://docs.microsoft.com/en-us/dotnet/api/system.version" rel="noreferrer">System.Version</a> names these parts as <code>major.minor.build.revision</code>!</p>
<p><strong>AssemblyInformationalVersion</strong></p>
<p>The Product version of the assembly. This is the version you would use when talking to customers or for display on your website. This version can be a string, like '<em>1.0 Release Candidate</em>'.</p>
<p>The <code>AssemblyInformationalVersion</code> is optional. If not given, the AssemblyFileVersion is used.</p>
<p>I use the format: <em>major.minor[.patch] [revision as string]</em>. This would result in:</p>
<pre><code>[assembly: AssemblyInformationalVersion("1.3 RC1")]
</code></pre> | {
"question_id": 64602,
"question_date": "2008-09-15T16:47:38.453Z",
"question_score": 916,
"tags": ".net|assemblies|attributes",
"answer_id": 65062,
"answer_date": "2008-09-15T17:46:57.767Z",
"answer_score": 962
} |
Please answer the following Stack Overflow question:
Title: Set environment variables from file of key/value pairs
<p><strong>TL;DR:</strong> How do I export a set of key/value pairs from a text file into the shell environment?</p>
<hr />
<p>For the record, below is the original version of the question, with examples.</p>
<p>I'm writing a script in bash which parses files with 3 variables in a certain folder, this is one of them:</p>
<pre><code>MINIENTREGA_FECHALIMITE="2011-03-31"
MINIENTREGA_FICHEROS="informe.txt programa.c"
MINIENTREGA_DESTINO="./destino/entrega-prac1"
</code></pre>
<p>This file is stored in <code>./conf/prac1</code></p>
<p>My script <code>minientrega.sh</code> then parses the file using this code:</p>
<pre><code>cat ./conf/$1 | while read line; do
export $line
done
</code></pre>
<p>But when I execute <code>minientrega.sh prac1</code> in the command line it doesn't set the environment variables</p>
<p>I also tried using <code>source ./conf/$1</code> but the same problem still applies</p>
<p>Maybe there is some other way to do this, I just need to use the environment variables of the file I pass as the argument of my script.</p> | <p>Problem with your approach is the <code>export</code> in the <code>while</code> loop is happening in a sub shell, and those variable will not be available in current shell (parent shell of while loop).</p>
<p>Add <code>export</code> command in the file itself:</p>
<pre><code>export MINIENTREGA_FECHALIMITE="2011-03-31"
export MINIENTREGA_FICHEROS="informe.txt programa.c"
export MINIENTREGA_DESTINO="./destino/entrega-prac1"
</code></pre>
<p>Then you need to source in the file in current shell using:</p>
<pre><code>. ./conf/prac1
</code></pre>
<p>OR</p>
<pre><code>source ./conf/prac1
</code></pre> | {
"question_id": 19331497,
"question_date": "2013-10-12T07:01:29.963Z",
"question_score": 915,
"tags": "bash|variables|environment-variables",
"answer_id": 19331521,
"answer_date": "2013-10-12T07:05:03.153Z",
"answer_score": 326
} |
Please answer the following Stack Overflow question:
Title: How to iterate a loop with index and element in Swift
<p>Is there a function that I can use to iterate over an array and have both index and element, like Python's <code>enumerate</code>?</p>
<pre><code>for index, element in enumerate(list):
...
</code></pre> | <p>Yes. As of Swift 3.0, if you need the index for each element along with its value, you can use the <a href="https://developer.apple.com/library/ios/documentation/swift/conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-XID_177" rel="noreferrer"><code>enumerated()</code> method</a> to iterate over the array. It returns a sequence of pairs composed of the index and the value for each item in the array. For example:</p>
<pre><code>for (index, element) in list.enumerated() {
print("Item \(index): \(element)")
}
</code></pre>
<p>Before Swift 3.0 and after Swift 2.0, the function was called <code>enumerate()</code>:</p>
<pre><code>for (index, element) in list.enumerate() {
print("Item \(index): \(element)")
}
</code></pre>
<p>Prior to Swift 2.0, <code>enumerate</code> was a global function.</p>
<pre><code>for (index, element) in enumerate(list) {
println("Item \(index): \(element)")
}
</code></pre> | {
"question_id": 24028421,
"question_date": "2014-06-04T03:19:21.913Z",
"question_score": 915,
"tags": "arrays|swift|enumeration",
"answer_id": 24028458,
"answer_date": "2014-06-04T03:23:54.540Z",
"answer_score": 1898
} |
Please answer the following Stack Overflow question:
Title: Split long commands in multiple lines through Windows batch file
<p>How can I split long commands over multiple lines in a batch file?</p> | <p>You can break up long lines with the caret <code>^</code> as long as you remember that the caret and the newline following it are completely removed. So, if there should be a space where you're breaking the line, include a space. <em>(<a href="https://stackoverflow.com/a/21000752/157247">More on that below.</a>)</em></p>
<p>Example:</p>
<pre><code>copy file1.txt file2.txt
</code></pre>
<p>would be written as:</p>
<pre><code>copy file1.txt^
file2.txt
</code></pre> | {
"question_id": 69068,
"question_date": "2008-09-16T03:04:34.260Z",
"question_score": 915,
"tags": "batch-file|line-continuation",
"answer_id": 69079,
"answer_date": "2008-09-16T03:06:37.857Z",
"answer_score": 1141
} |
Please answer the following Stack Overflow question:
Title: "UNPROTECTED PRIVATE KEY FILE!" Error using SSH into Amazon EC2 Instance (AWS)
<p>I've created a new linux instance on Amazon EC2, and as part of that downloaded the <code>.pem</code> file to allow me to SSH in.</p>
<p>When I tried to <code>ssh</code> with:</p>
<pre><code>ssh -i myfile.pem <public dns>
</code></pre>
<p>I got:</p>
<pre><code>@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@ WARNING: UNPROTECTED PRIVATE KEY FILE! @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
Permissions 0644 for 'amazonec2.pem' are too open.
It is recommended that your private key files are NOT accessible by others.
This private key will be ignored.
bad permissions: ignore key: amazonec2.pem
Permission denied (publickey).
</code></pre>
<p>Following <a href="https://stackoverflow.com/questions/201893/ssh-into-amazon-ec2-instance">this post</a> I tried to <code>chmod +600</code> the <code>.pem</code> file, but now when I <code>ssh</code> I just get</p>
<pre><code>Permission denied (publickey).
</code></pre>
<p>What school-boy error am I making here?
The <code>.pem</code> file is in my home folder (in macOS). Its permissions look like this:</p>
<pre><code>-rw-------@ 1 mattroberts staff 1696 19 Nov 11:20 amazonec2.pem
</code></pre> | <p>The problem is wrong set of permissions on the file.</p>
<p>Easily solved by executing -</p>
<p><code>chmod 400 mykey.pem</code></p>
<p>Taken from AWS instructions -</p>
<blockquote>
<p>Your key file must not be publicly viewable for SSH to work. Use this
command if needed: chmod 400 mykey.pem</p>
</blockquote>
<p>400 protects it by making it read only and only for the owner.</p> | {
"question_id": 8193768,
"question_date": "2011-11-19T11:35:08.933Z",
"question_score": 914,
"tags": "amazon-web-services|authentication|ssh|amazon-ec2|permissions",
"answer_id": 10822056,
"answer_date": "2012-05-30T18:23:04.807Z",
"answer_score": 1806
} |
Please answer the following Stack Overflow question:
Title: How do I drop a MongoDB database from the command line?
<p>What's the easiest way to do this from my bash prompt?</p> | <p>Like this:</p>
<pre><code>mongo <dbname> --eval "db.dropDatabase()"
</code></pre>
<p>More info on scripting the shell from the command line here: <a href="https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/#scripting" rel="noreferrer">https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/#scripting</a></p> | {
"question_id": 8857276,
"question_date": "2012-01-13T21:11:40.820Z",
"question_score": 914,
"tags": "mongodb",
"answer_id": 8857373,
"answer_date": "2012-01-13T21:19:12.320Z",
"answer_score": 1145
} |
Please answer the following Stack Overflow question:
Title: When to use .First and when to use .FirstOrDefault with LINQ?
<p>I've searched around and haven't really found a clear answer as to when you'd want to use <code>.First</code> and when you'd want to use <code>.FirstOrDefault</code> with LINQ.</p>
<ul>
<li><p>When would you want to use <code>.First</code>? Only when you'd want to catch the exception if no results where returned?</p>
<pre><code>var result = List.Where(x => x == "foo").First();
</code></pre></li>
<li><p>And when would you want to use <code>.FirstOrDefault</code>? When you'd always want the default type if no result?</p>
<pre><code>var result = List.Where(x => x == "foo").FirstOrDefault();
</code></pre></li>
<li><p>And for that matter, what about Take?</p>
<pre><code>var result = List.Where(x => x == "foo").Take(1);
</code></pre></li>
</ul> | <p>I would use <code>First()</code> when I know or expect the sequence to have at least one element. In other words, when it is an exceptional occurrence that the sequence is empty.</p>
<p>Use <code>FirstOrDefault()</code> when you know that you will need to check whether there was an element or not. In other words, when it is legal for the sequence to be empty. You should not rely on exception handling for the check. (It is bad practice and might hurt performance).</p>
<p>Finally, the difference between <code>First()</code> and <code>Take(1)</code> is that <code>First()</code> returns the element itself, while <code>Take(1)</code> returns a sequence of elements that contains exactly one element.</p> | {
"question_id": 1024559,
"question_date": "2009-06-21T19:15:29.933Z",
"question_score": 913,
"tags": "c#|.net|linq",
"answer_id": 1024577,
"answer_date": "2009-06-21T19:22:55.940Z",
"answer_score": 877
} |
Please answer the following Stack Overflow question:
Title: How do I replace NA values with zeros in an R dataframe?
<p>I have a data frame and some columns have <code>NA</code> values.</p>
<p>How do I replace these <code>NA</code> values with zeroes?</p> | <p>See my comment in @gsk3 answer. A simple example:</p>
<pre><code>> m <- matrix(sample(c(NA, 1:10), 100, replace = TRUE), 10)
> d <- as.data.frame(m)
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 4 3 NA 3 7 6 6 10 6 5
2 9 8 9 5 10 NA 2 1 7 2
3 1 1 6 3 6 NA 1 4 1 6
4 NA 4 NA 7 10 2 NA 4 1 8
5 1 2 4 NA 2 6 2 6 7 4
6 NA 3 NA NA 10 2 1 10 8 4
7 4 4 9 10 9 8 9 4 10 NA
8 5 8 3 2 1 4 5 9 4 7
9 3 9 10 1 9 9 10 5 3 3
10 4 2 2 5 NA 9 7 2 5 5
> d[is.na(d)] <- 0
> d
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10
1 4 3 0 3 7 6 6 10 6 5
2 9 8 9 5 10 0 2 1 7 2
3 1 1 6 3 6 0 1 4 1 6
4 0 4 0 7 10 2 0 4 1 8
5 1 2 4 0 2 6 2 6 7 4
6 0 3 0 0 10 2 1 10 8 4
7 4 4 9 10 9 8 9 4 10 0
8 5 8 3 2 1 4 5 9 4 7
9 3 9 10 1 9 9 10 5 3 3
10 4 2 2 5 0 9 7 2 5 5
</code></pre>
<p>There's no need to apply <code>apply</code>. =)</p>
<p><strong>EDIT</strong></p>
<p>You should also take a look at <code>norm</code> package. It has a lot of nice features for missing data analysis. =)</p> | {
"question_id": 8161836,
"question_date": "2011-11-17T03:45:44.920Z",
"question_score": 912,
"tags": "r|dataframe",
"answer_id": 8166616,
"answer_date": "2011-11-17T11:48:49.557Z",
"answer_score": 1108
} |
Please answer the following Stack Overflow question:
Title: How can I convert a Unix timestamp to DateTime and vice versa?
<p>There is this example code, but then it starts talking about millisecond / nanosecond problems.</p>
<p>The same question is on MSDN, <em><a href="https://docs.microsoft.com/archive/blogs/brada/seconds-since-the-unix-epoch-in-c" rel="noreferrer">Seconds since the Unix epoch in C#</a></em>.</p>
<p>This is what I've got so far:</p>
<pre><code>public Double CreatedEpoch
{
get
{
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
TimeSpan span = (this.Created.ToLocalTime() - epoch);
return span.TotalSeconds;
}
set
{
DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
this.Created = epoch.AddSeconds(value);
}
}
</code></pre> | <p>Here's what you need:</p>
<pre><code>public static DateTime UnixTimeStampToDateTime( double unixTimeStamp )
{
// Unix timestamp is seconds past epoch
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dateTime = dateTime.AddSeconds( unixTimeStamp ).ToLocalTime();
return dateTime;
}
</code></pre>
<p>Or, for Java (which is different because the timestamp is in milliseconds, not seconds):</p>
<pre><code>public static DateTime JavaTimeStampToDateTime( double javaTimeStamp )
{
// Java timestamp is milliseconds past epoch
DateTime dateTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
dateTime = dateTime.AddMilliseconds( javaTimeStamp ).ToLocalTime();
return dateTime;
}
</code></pre> | {
"question_id": 249760,
"question_date": "2008-10-30T10:30:29.927Z",
"question_score": 912,
"tags": "c#|datetime|unix|epoch|data-conversion",
"answer_id": 250400,
"answer_date": "2008-10-30T14:42:17.483Z",
"answer_score": 1202
} |
Please answer the following Stack Overflow question:
Title: How do you sort a dictionary by value?
<p>I often have to sort a dictionary (consisting of keys & values) by value. For example, I have a hash of words and respective frequencies that I want to order by frequency.</p>
<p>There is a <code>SortedList</code> which is good for a single value (say frequency), that I want to map back to the word.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/f7fta44c.aspx" rel="noreferrer">SortedDictionary</a> orders by key, not value. Some resort to a <a href="http://www.codeproject.com/KB/recipes/lookupcollection.aspx" rel="noreferrer">custom class</a>, but is there a cleaner way?</p> | <p>Use:</p>
<pre><code>using System.Linq.Enumerable;
...
List<KeyValuePair<string, string>> myList = aDictionary.ToList();
myList.Sort(
delegate(KeyValuePair<string, string> pair1,
KeyValuePair<string, string> pair2)
{
return pair1.Value.CompareTo(pair2.Value);
}
);
</code></pre>
<p>Since you're targeting .NET 2.0 or above, you can simplify this into lambda syntax -- it's equivalent, but shorter. If you're targeting .NET 2.0 you can only use this syntax if you're using the compiler from Visual Studio 2008 (or above).</p>
<pre><code>var myList = aDictionary.ToList();
myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));
</code></pre> | {
"question_id": 289,
"question_date": "2008-08-02T00:40:58.200Z",
"question_score": 912,
"tags": "c#|.net|sorting|dictionary",
"answer_id": 298,
"answer_date": "2008-08-02T01:15:42.123Z",
"answer_score": 557
} |
Please answer the following Stack Overflow question:
Title: How to efficiently concatenate strings in go
<p>In Go, a <code>string</code> is a primitive type, which means it is read-only, and every manipulation of it will create a new string.</p>
<p>So if I want to concatenate strings many times without knowing the length of the resulting string, what's the best way to do it?</p>
<p>The naive way would be:</p>
<pre><code>var s string
for i := 0; i < 1000; i++ {
s += getShortStringFromSomewhere()
}
return s
</code></pre>
<p>but that does not seem very efficient.</p> | <h3>New Way:</h3>
<p>From Go 1.10 there is a <code>strings.Builder</code> type, <a href="https://stackoverflow.com/questions/1760757/how-to-efficiently-concatenate-strings-in-go/47798475#47798475">please take a look at this answer for more detail</a>.</p>
<h3>Old Way:</h3>
<p>Use the <a href="http://golang.org/pkg/bytes/" rel="noreferrer"><code>bytes</code></a> package. It has a <a href="http://golang.org/pkg/bytes/#Buffer" rel="noreferrer"><code>Buffer</code></a> type which implements <a href="http://golang.org/pkg/io/#Writer" rel="noreferrer"><code>io.Writer</code></a>. </p>
<pre><code>package main
import (
"bytes"
"fmt"
)
func main() {
var buffer bytes.Buffer
for i := 0; i < 1000; i++ {
buffer.WriteString("a")
}
fmt.Println(buffer.String())
}
</code></pre>
<p>This does it in O(n) time.</p> | {
"question_id": 1760757,
"question_date": "2009-11-19T03:44:10.347Z",
"question_score": 912,
"tags": "string|go|string-concatenation",
"answer_id": 1766304,
"answer_date": "2009-11-19T20:31:24.203Z",
"answer_score": 1018
} |
Please answer the following Stack Overflow question:
Title: How can I write a heredoc to a file in Bash script?
<p>How can I write a here document to a file in Bash script?</p> | <p>Read the Advanced Bash-Scripting Guide <a href="http://tldp.org/LDP/abs/html/here-docs.html" rel="noreferrer">Chapter 19. Here Documents</a>.</p>
<p>Here's an example which will write the contents to a file at <code>/tmp/yourfilehere</code></p>
<pre><code>cat << EOF > /tmp/yourfilehere
These contents will be written to the file.
This line is indented.
EOF
</code></pre>
<p>Note that the final 'EOF' (The <code>LimitString</code>) should not have any whitespace in front of the word, because it means that the <code>LimitString</code> will not be recognized.</p>
<p>In a shell script, you may want to use indentation to make the code readable, however this can have the undesirable effect of indenting the text within your here document. In this case, use <code><<-</code> (followed by a dash) to disable leading tabs (<strong>Note</strong> that to test this you will need to <strong>replace the leading whitespace with a tab character</strong>, since I cannot print actual tab characters here.)</p>
<pre><code>#!/usr/bin/env bash
if true ; then
cat <<- EOF > /tmp/yourfilehere
The leading tab is ignored.
EOF
fi
</code></pre>
<p>If you don't want to interpret variables in the text, then use single quotes:</p>
<pre><code>cat << 'EOF' > /tmp/yourfilehere
The variable $FOO will not be interpreted.
EOF
</code></pre>
<p>To pipe the heredoc through a command pipeline:</p>
<pre><code>cat <<'EOF' | sed 's/a/b/'
foo
bar
baz
EOF
</code></pre>
<p>Output:</p>
<pre><code>foo
bbr
bbz
</code></pre>
<p>... or to write the the heredoc to a file using <code>sudo</code>:</p>
<pre><code>cat <<'EOF' | sed 's/a/b/' | sudo tee /etc/config_file.conf
foo
bar
baz
EOF
</code></pre> | {
"question_id": 2953081,
"question_date": "2010-06-01T20:28:10.393Z",
"question_score": 912,
"tags": "bash|heredoc",
"answer_id": 2954835,
"answer_date": "2010-06-02T03:40:50.250Z",
"answer_score": 1370
} |
Please answer the following Stack Overflow question:
Title: How to permanently remove few commits from remote branch
<p>I know that's rewriting of history which is bad yada yada.</p>
<p>But how to permanently remove few commits from remote branch?</p> | <p>You <code>git reset --hard</code> your local branch to remove changes from working tree and index, and you <code>git push --force</code> (or <a href="https://stackoverflow.com/a/52937476/6309"><code>git push --force-with-lease</code></a>) your revised local branch to the remote.<br />
(<a href="https://stackoverflow.com/questions/1475665/why-git-push-helloworld-mastermaster-instead-of-just-git-push-helloworld">other solution here</a>, involving deleting the remote branch, and re-pushing it)</p>
<p>This <a href="https://stackoverflow.com/questions/253055/how-do-i-push-amended-commit-to-the-remote-git-repo">SO answer</a> illustrates the danger of such a command, especially if people depends on the remote history for their own local repos.<br />
You need to be prepared to point out people to the <a href="http://git-scm.com/docs/git-rebase#_recovering_from_upstream_rebase" rel="noreferrer">RECOVERING FROM UPSTREAM REBASE</a> section of the <a href="http://git-scm.com/docs/git-rebase" rel="noreferrer"><code>git rebase</code></a> man page.</p>
<p>Plus, as noted by <a href="https://stackoverflow.com/users/7059681/ringo">ringo</a> in <a href="https://stackoverflow.com/questions/3293531/how-to-permanently-remove-few-commits-from-remote-branch/3293592#comment128013893_3293592">the comments</a>, if the remote branch is protected against force push, a <code>git revert</code>, as in <a href="https://stackoverflow.com/a/29827413/6309">this answer</a>, might be preferable.</p>
<hr />
<p>With Git 2.23 (August 2019, nine years later), you would use the new command <a href="https://stackoverflow.com/a/57066202/6309"><strong><code>git switch</code></strong></a>.<br />
That is: <a href="https://git-scm.com/docs/git-switch#Documentation/git-switch.txt--Cltnew-branchgt" rel="noreferrer"><code>git switch -C mybranch origin/mybranch~n</code></a><br />
(replace <code>n</code> by the number of commits to remove)</p>
<p>That will restore the index and working tree, like a <code>git reset --hard</code> would.<br />
The <a href="https://git-scm.com/docs/git-switch#Documentation/git-switch.txt--Cltnew-branchgt" rel="noreferrer">documentation adds</a>:</p>
<blockquote>
<pre><code>-C <new-branch>
--force-create <new-branch>
</code></pre>
<p>Similar to <code>--create</code> except that if <code><new-branch></code> already exists, it will be reset to <code><start-point></code>.<br />
This is a convenient shortcut for:</p>
<pre><code>$ git branch -f <new-branch>
$ git switch <new-branch>
</code></pre>
</blockquote> | {
"question_id": 3293531,
"question_date": "2010-07-20T19:19:59.557Z",
"question_score": 911,
"tags": "git",
"answer_id": 3293592,
"answer_date": "2010-07-20T19:26:36.220Z",
"answer_score": 628
} |
Please answer the following Stack Overflow question:
Title: How do I detect whether a Python variable is a function?
<p>I have a variable, <code>x</code>, and I want to know whether it is pointing to a function or not.</p>
<p>I had hoped I could do something like:</p>
<pre><code>>>> isinstance(x, function)
</code></pre>
<p>But that gives me:</p>
<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
File "<stdin>", line 1, in ?
NameError: name 'function' is not defined
</code></pre>
<p>The reason I picked that is because</p>
<pre><code>>>> type(x)
<type 'function'>
</code></pre> | <p>If this is for Python 2.x or for Python 3.2+, you can use <a href="https://docs.python.org/3/library/functions.html#callable" rel="noreferrer"><code>callable()</code></a>. It used to be deprecated, but is now undeprecated, so you can use it again. You can read the discussion here: <a href="http://bugs.python.org/issue10518" rel="noreferrer">http://bugs.python.org/issue10518</a>. You can do this with:</p>
<pre><code>callable(obj)
</code></pre>
<p>If this is for Python 3.x but before 3.2, check if the object has a <code>__call__</code> attribute. You can do this with:</p>
<pre><code>hasattr(obj, '__call__')
</code></pre>
<p>The oft-suggested <a href="https://docs.python.org/3/library/types.html#types.FunctionType" rel="noreferrer"><code>types.FunctionTypes</code></a> or <a href="https://docs.python.org/3/library/inspect.html#inspect.isfunction" rel="noreferrer"><code>inspect.isfunction</code></a> approach (both do <a href="https://github.com/python/cpython/blob/ea46c7bc503d1103d60c0ec7023bb52c5defa11d/Lib/inspect.py#L159-L170" rel="noreferrer">the exact same thing</a>) comes with a number of caveats. It returns <code>False</code> for non-Python functions. Most <a href="https://docs.python.org/3/library/functions.html" rel="noreferrer">builtin functions</a>, for example, are implemented in C and not Python, so they return <code>False</code>:</p>
<pre><code>>>> isinstance(open, types.FunctionType)
False
>>> callable(open)
True
</code></pre>
<p>so <code>types.FunctionType</code> might give you surprising results. The proper way to check properties of duck-typed objects is to ask them if they quack, not to see if they fit in a duck-sized container.</p> | {
"question_id": 624926,
"question_date": "2009-03-09T03:31:30.623Z",
"question_score": 911,
"tags": "python",
"answer_id": 624939,
"answer_date": "2009-03-09T03:39:02.620Z",
"answer_score": 1150
} |
Please answer the following Stack Overflow question:
Title: Are HTTP headers case-sensitive?
<p>In a blog post I use the following PHP to set the content-type of a response:</p>
<pre><code>header('content-type: application/json; charset=utf-8');
</code></pre>
<p>I just got a comment on that post saying that <code>content-type</code> needs to be capitalized, <code>Content-type</code>. Is this correct? It seems to work for me with all lower-case, and I assumed the HTTP headers were case-insensitive. Or does it just work because browsers are nice?</p> | <p>Header names are not case sensitive.</p>
<p>From <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html" rel="noreferrer">RFC 2616 - "Hypertext Transfer Protocol -- HTTP/1.1"</a>, <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2" rel="noreferrer">Section 4.2, "Message Headers"</a>:</p>
<blockquote>
<p>Each header field consists of a name followed by a colon (":") and the field value. Field names are case-<strong>in</strong>sensitive.</p>
</blockquote>
<p>The updating RFC 7230 does not list any <a href="https://www.rfc-editor.org/rfc/rfc7230#appendix-A.2" rel="noreferrer">changes from RFC 2616</a> at this part.</p> | {
"question_id": 5258977,
"question_date": "2011-03-10T11:22:16.993Z",
"question_score": 911,
"tags": "http|http-headers",
"answer_id": 5259004,
"answer_date": "2011-03-10T11:24:26.320Z",
"answer_score": 1180
} |
Please answer the following Stack Overflow question:
Title: Fetch: POST JSON data
<p>I'm trying to POST a JSON object using <a href="https://developer.mozilla.org/en-US/docs/Web/API/GlobalFetch/fetch" rel="noreferrer">fetch</a>.</p>
<p>From what I can understand, I need to attach a stringified object to the body of the request, e.g.:</p>
<pre class="lang-js prettyprint-override"><code>fetch("/echo/json/",
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({a: 1, b: 2})
})
.then(function(res){ console.log(res) })
.catch(function(res){ console.log(res) })
</code></pre>
<p>When using <a href="https://jsfiddle.net/abbpbah4/" rel="noreferrer">jsfiddle's JSON echo</a> I'd expect to see the object I've sent (<code>{a: 1, b: 2}</code>) back, but this does not happen - chrome devtools doesn't even show the JSON as part of the request, which means that it's not being sent.</p> | <p>With ES2017 <a href="https://caniuse.com/#feat=async-functions" rel="noreferrer"><code>async/await</code> support</a>, this is how to <code>POST</code> a JSON payload:</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>(async () => {
const rawResponse = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 1, b: 'Textual content'})
});
const content = await rawResponse.json();
console.log(content);
})();</code></pre>
</div>
</div>
</p>
<p>Can't use ES2017? See @vp_art's <a href="https://stackoverflow.com/a/42493030/304174">answer using promises</a></p>
<p>The question however is asking for an issue caused by <strong>a long since fixed chrome bug.</strong><br>
Original answer follows.</p>
<blockquote>
<p>chrome devtools doesn't even show the JSON as part of the request</p>
</blockquote>
<p><strong>This is the real issue here</strong>, and it's a <a href="https://code.google.com/p/chromium/issues/detail?id=457484" rel="noreferrer">bug with chrome devtools</a>, fixed in Chrome 46.</p>
<p>That code works fine - it is POSTing the JSON correctly, it just cannot be seen.</p>
<blockquote>
<p>I'd expect to see the object I've sent back</p>
</blockquote>
<p>that's not working because that is not the <a href="http://doc.jsfiddle.net/use/echo.html#json" rel="noreferrer">correct format for JSfiddle's echo</a>.</p>
<p>The <a href="https://jsfiddle.net/Razor/abbpbah4/5/" rel="noreferrer">correct code</a> is:</p>
<pre class="lang-js prettyprint-override"><code>var payload = {
a: 1,
b: 2
};
var data = new FormData();
data.append( "json", JSON.stringify( payload ) );
fetch("/echo/json/",
{
method: "POST",
body: data
})
.then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })
</code></pre>
<p>For endpoints accepting JSON payloads, <strong>the original code is correct</strong></p> | {
"question_id": 29775797,
"question_date": "2015-04-21T14:54:41.137Z",
"question_score": 910,
"tags": "javascript|json|fetch-api",
"answer_id": 29823632,
"answer_date": "2015-04-23T12:34:29.840Z",
"answer_score": 1011
} |
Please answer the following Stack Overflow question:
Title: Rollback to an old Git commit in a public repo
<p>How can I go about rolling back to a specific commit in <strong>git</strong>?</p>
<p>The best answer someone could give me was to use <code>git revert</code> X times until I reach the desired commit. </p>
<p>So let's say I want to revert back to a commit that's 20 commits old, I'd have to run it 20 times. </p>
<p>Is there an easier way to do this? </p>
<p>I can't use reset because this repository is public.</p> | <p>Try this:</p>
<pre><code>git checkout [revision] .
</code></pre>
<p>where <code>[revision]</code> is the commit hash (for example: <code>12345678901234567890123456789012345678ab</code>). </p>
<p>Don't forget the <code>.</code> at the end, very important. This will apply changes to the whole tree. You should execute this command in the git project root. If you are in any sub directory, then this command only changes the files in the current directory. Then commit and you should be good.</p>
<p>You can undo this by</p>
<pre><code>git reset --hard
</code></pre>
<p>that will delete all modifications from the working directory and staging area.</p> | {
"question_id": 2007662,
"question_date": "2010-01-05T17:01:14.857Z",
"question_score": 910,
"tags": "git|git-checkout|git-revert",
"answer_id": 2007704,
"answer_date": "2010-01-05T17:07:42.767Z",
"answer_score": 1334
} |
Please answer the following Stack Overflow question:
Title: Is it possible to add dynamically named properties to JavaScript object?
<p>In JavaScript, I've created an object like so:</p>
<pre><code>var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
</code></pre>
<p>Is it possible to add further properties to this object after its initial creation if the properties name is not determined until run time? i.e.</p>
<pre><code>var propName = 'Property' + someUserInput
//imagine someUserInput was 'Z', how can I now add a 'PropertyZ' property to
//my object?
</code></pre> | <p>Yes.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var data = {
'PropertyA': 1,
'PropertyB': 2,
'PropertyC': 3
};
data["PropertyD"] = 4;
// dialog box with 4 in it
alert(data.PropertyD);
alert(data["PropertyD"]);</code></pre>
</div>
</div>
</p> | {
"question_id": 1184123,
"question_date": "2009-07-26T09:24:39.187Z",
"question_score": 909,
"tags": "javascript",
"answer_id": 1184130,
"answer_date": "2009-07-26T09:27:01.930Z",
"answer_score": 1463
} |
Please answer the following Stack Overflow question:
Title: How to disable a link using only CSS
<p>Is there a way to disable a link using CSS?</p>
<p>I have a class called <code>current-page</code> and want links with this class to be disabled so that no action occurs when they are clicked.</p> | <p>From <a href="http://css-tricks.com/pointer-events-current-nav/" rel="noreferrer">this solution</a>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>[aria-current="page"] {
pointer-events: none;
cursor: default;
text-decoration: none;
color: black;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="link.html" aria-current="page">Link</a></code></pre>
</div>
</div>
</p>
<p>For browser support, please see <a href="https://caniuse.com/#feat=pointer-events" rel="noreferrer">https://caniuse.com/#feat=pointer-events</a>. If you need to support Internet Explorer, there is a workaround; see <a href="https://stackoverflow.com/a/10276157/1207195">this answer</a>.</p>
<p>Warning: The use of <a href="https://developer.mozilla.org/en-US/docs/CSS/pointer-events" rel="noreferrer"><code>pointer-events</code></a> in CSS for non-SVG elements is experimental. The feature used to be part of the CSS 3 UI draft specification but, due to many open issues, has been postponed to CSS 4.</p> | {
"question_id": 2091168,
"question_date": "2010-01-19T04:55:03.270Z",
"question_score": 908,
"tags": "html|css",
"answer_id": 4416239,
"answer_date": "2010-12-11T10:17:53.907Z",
"answer_score": 1426
} |
Please answer the following Stack Overflow question:
Title: What are the special dollar sign shell variables?
<p>In Bash, there appear to be several variables which hold special, consistently-meaning values. For instance,</p>
<pre><code>./myprogram &; echo $!
</code></pre>
<p>will return the PID of the process which backgrounded <code>myprogram</code>. I know of others, such as <code>$?</code> which I think is the current TTY. Are there others?</p> | <ul>
<li><code>$1</code>, <code>$2</code>, <code>$3</code>, ... are the <a href="https://www.gnu.org/software/bash/manual/html_node/Positional-Parameters.html" rel="noreferrer">positional parameters</a>.</li>
<li><code>"$@"</code> is an array-like construct of all positional parameters, <code>{$1, $2, $3 ...}</code>.</li>
<li><code>"$*"</code> is the IFS expansion of all positional parameters, <code>$1 $2 $3 ...</code>.</li>
<li><code>$#</code> is the number of positional parameters.</li>
<li><code>$-</code> current options set for the shell.</li>
<li><code>$$</code> pid of the current shell (not subshell).</li>
<li><code>$_</code> most recent parameter (or the abs path of the command to start the current shell immediately after startup).</li>
<li><code>$IFS</code> is the (input) field separator.</li>
<li><code>$?</code> is the most recent foreground pipeline exit status.</li>
<li><code>$!</code> is the PID of the most recent background command.</li>
<li><code>$0</code> is the name of the shell or shell script.</li>
</ul>
<p>Most of the above can be found under <a href="https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html" rel="noreferrer">Special Parameters</a> in the Bash Reference Manual. There are all the <a href="https://www.gnu.org/software/bash/manual/html_node/Shell-Variables.html" rel="noreferrer">environment variables set by the shell</a>.</p>
<p>For a comprehensive index, please see the <a href="https://www.gnu.org/software/bash/manual/html_node/Variable-Index.html" rel="noreferrer">Reference Manual Variable Index</a>.</p> | {
"question_id": 5163144,
"question_date": "2011-03-02T03:42:17.583Z",
"question_score": 908,
"tags": "bash|environment-variables|dollar-sign",
"answer_id": 5163260,
"answer_date": "2011-03-02T04:04:52.233Z",
"answer_score": 1563
} |
Please answer the following Stack Overflow question:
Title: Is there a command to undo git init?
<p>I just Git init'ed a repos with a wrong user, and want to undo it. Is there any command for this? Do I actually have to go in and edit the .git directory?</p> | <p>You can just delete .git. Typically:</p>
<pre><code>rm -rf .git
</code></pre>
<p>Then, recreate as the right user.</p> | {
"question_id": 3212459,
"question_date": "2010-07-09T12:16:51.680Z",
"question_score": 907,
"tags": "git|git-init",
"answer_id": 3212465,
"answer_date": "2010-07-09T12:17:38.623Z",
"answer_score": 1654
} |
Please answer the following Stack Overflow question:
Title: What are the differences between "=" and "<-" assignment operators?
<p>What are the differences between the assignment operators <code>=</code> and <code><-</code> in R? </p>
<p>I know that operators are slightly different, as this example shows</p>
<pre><code>x <- y <- 5
x = y = 5
x = y <- 5
x <- y = 5
# Error in (x <- y) = 5 : could not find function "<-<-"
</code></pre>
<p>But is this the only difference? </p> | <blockquote>
<p>What are the differences between the assignment operators <code>=</code> and <code><-</code> in R?</p>
</blockquote>
<p>As your example shows, <code>=</code> and <code><-</code> have slightly different operator precedence (which determines the order of evaluation when they are mixed in the same expression). In fact, <a href="https://www.rdocumentation.org/packages/base/versions/3.5.0/topics/Syntax" rel="noreferrer"><code>?Syntax</code></a> in R gives the following operator precedence table, from highest to lowest:</p>
<blockquote>
<pre><code>…
‘-> ->>’ rightwards assignment
‘<- <<-’ assignment (right to left)
‘=’ assignment (right to left)
…
</code></pre>
</blockquote>
<p>But is this the only difference?</p>
<p>Since you were asking about the <em>assignment operators</em>: yes, that is the only difference. However, you would be forgiven for believing otherwise. Even the R documentation of <a href="https://www.rdocumentation.org/packages/base/versions/3.5.0/topics/assignOps" rel="noreferrer"><code>?assignOps</code></a> claims that there are more differences:</p>
<blockquote>
<p>The operator <code><-</code> can be used anywhere,
whereas the operator <code>=</code> is only allowed at the top level (e.g.,
in the complete expression typed at the command prompt) or as one
of the subexpressions in a braced list of expressions.</p>
</blockquote>
<p>Let’s not put too fine a point on it: <strong>the R documentation is wrong</strong>. This is easy to show: we just need to find a counter-example of the <code>=</code> operator that isn’t (a) at the top level, nor (b) a subexpression in a braced list of expressions (i.e. <code>{…; …}</code>). — Without further ado:</p>
<pre><code>x
# Error: object 'x' not found
sum((x = 1), 2)
# [1] 3
x
# [1] 1
</code></pre>
<p>Clearly we’ve performed an assignment, using <code>=</code>, outside of contexts (a) and (b). So, why has the documentation of a core R language feature been wrong for decades?</p>
<p>It’s because in R’s syntax the symbol <code>=</code> has two distinct meanings that get routinely conflated (even by experts, including in the documentation cited above):</p>
<ol>
<li>The first meaning is as an <strong>assignment operator</strong>. This is all we’ve talked about so far.</li>
<li>The second meaning isn’t an operator but rather a <strong>syntax token</strong> that signals <em>named argument passing</em> in a function call. Unlike the <code>=</code> <em>operator</em> it performs no action at runtime, it merely changes the way an expression is parsed.</li>
</ol>
<p>So how does R decide whether a given usage of <code>=</code> refers to the operator or to named argument passing? Let’s see.</p>
<p>In any piece of code of the general form …</p>
<pre><code><i>‹function_name›</i>(<i>‹argname›</i> <b>=</b> <i>‹value›</i>, …)
<i>‹function_name›</i>(<i>‹args›</i>, <i>‹argname›</i> <b>=</b> <i>‹value›</i>, …)</code></pre>
<p>… the <strong><code>=</code></strong> is the token that defines named argument passing: it is <em>not</em> the assignment operator. Furthermore, <code>=</code> is entirely <em>forbidden</em> in some syntactic contexts:</p>
<pre><code>if (<i>‹var›</i> <b>=</b> <i>‹value›</i>) …
while (<i>‹var›</i> <b>=</b> <i>‹value›</i>) …
for (<i>‹var›</i> <b>=</b> <i>‹value›</i> in <i>‹value2›</i>) …
for (<i>‹var1›</i> in <i>‹var2›</i> <b>=</b> <i>‹value›</i>) …</code></pre>
<p>Any of these will raise an error “unexpected '=' in ‹bla›”.</p>
<p>In any other context, <code>=</code> refers to the assignment operator call. In particular, merely putting parentheses around the subexpression makes any of the above (a) valid, and (b) an <em>assignment</em>. For instance, the following performs assignment:</p>
<pre><code>median((x = 1 : 10))
</code></pre>
<p>But also:</p>
<pre><code>if (! (nf = length(from))) return()
</code></pre>
<p><sub>Now you might object that such code is atrocious (and you may be right). But I took this code from the <code>base::file.copy</code> function (replacing <code><-</code> with <code>=</code>) — it’s a pervasive pattern in much of the core R codebase.</sub></p>
<p>The <a href="http://developer.r-project.org/equalAssign.html" rel="noreferrer">original explanation by John Chambers</a>, which the the R documentation is probably based on, actually explains this correctly:</p>
<blockquote>
<p>[<code>=</code> assignment is] allowed in only two places in the grammar: at the top level (as a complete program or user-typed expression); and when isolated from surrounding logical structure, by braces or an extra pair of parentheses.</p>
</blockquote>
<hr />
<p>In sum, by default the operators <code><-</code> and <code>=</code> do the same thing. But either of them can be <em>overridden</em> separately to change its behaviour. By contrast, <code><-</code> and <code>-></code> (left-to-right assignment), though syntactically distinct, always call the <em>same</em> function. Overriding one also overrides the other. Knowing this is rarely practical <a href="https://github.com/klmr/functional#a-concise-lambda-syntax" rel="noreferrer">but it <em>can</em> be used for some fun shenanigans</a>.</p> | {
"question_id": 1741820,
"question_date": "2009-11-16T12:14:51.313Z",
"question_score": 907,
"tags": "r|assignment-operator|r-faq",
"answer_id": 51564252,
"answer_date": "2018-07-27T19:17:14.773Z",
"answer_score": 230
} |
Please answer the following Stack Overflow question:
Title: Does C# have extension properties?
<p>Does C# have extension properties?</p>
<p>For example, can I add an extension property to <code>DateTimeFormatInfo</code> called <code>ShortDateLongTimeFormat</code> which would return <code>ShortDatePattern + " " + LongTimePattern</code>?</p> | <h3>For the moment it is still not supported out of the box by Roslyn compiler ...</h3>
<p>Until now, the extension properties were not seen as valuable enough to be included in the previous versions of C# standard. <strong>C# 7</strong> and <strong>C# 8.0</strong> have seen this as proposal champion but it wasn't released yet, most of all because even if there is already an implementation, they want to make it right from the start.</p>
<h3>But it will ...</h3>
<p>There is an <strong><a href="https://github.com/dotnet/roslyn/issues/112" rel="noreferrer">extension members</a></strong> item in the <strong><a href="https://github.com/dotnet/roslyn/issues/2136" rel="noreferrer">C# 7 work list</a></strong> so it may be supported in the near future. The current status of extension property can be found on <a href="https://github.com/dotnet/roslyn/issues/2136" rel="noreferrer">Github under the related item</a>.</p>
<p>However, there is an even more promising topic which is the <a href="https://github.com/dotnet/roslyn/issues/6136" rel="noreferrer">"extend everything"</a> with a focus on especially properties and static classes or even fields.</p>
<h3>Moreover you can use a workaround</h3>
<p>As specified in this <a href="http://www.codeproject.com/Articles/386911/Csharp-Easy-Extension-Properties" rel="noreferrer">article</a>, you can use the <code>TypeDescriptor</code> capability to attach an attribute to an object instance at runtime. However, it is not using the syntax of the standard properties.<br/>
It's a little bit different from just syntactic sugar adding a possibility to define an extended property like <br/><code>string Data(this MyClass instance)</code> as an alias for extension method <br/><code>string GetData(this MyClass instance)</code> as it stores data into the class.</p>
<p>I hope that C#7 will provide a full featured extension everything (properties and fields), however on that point, only time will tell. </p>
<p>And feel free to contribute as the software of tomorrow will come from the community.</p>
<p><strong><em>Update: August 2016</em></strong></p>
<p>As dotnet team published <a href="https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/" rel="noreferrer">what's new in C# 7.0</a> and from a comment of <a href="https://social.msdn.microsoft.com/profile/Mads+Torgersen+-+MSFT" rel="noreferrer">Mads Torgensen</a>:</p>
<blockquote>
<p>Extension properties: we had a (brilliant!) intern implement them over
the summer as an experiment, along with other kinds of extension
members. We remain interested in this, but it’s a big change and we
need to feel confident that it’s worth it.</p>
</blockquote>
<p>It seems that extension properties and other members, are still good candidates to be included in a future release of Roslyn, but maybe not the 7.0 one.</p>
<p><strong><em>Update: May 2017</em></strong></p>
<p><a href="https://github.com/dotnet/roslyn/issues/112" rel="noreferrer"><strong>The extension members</strong></a> has been closed as duplicate of <a href="https://github.com/dotnet/roslyn/issues/11159" rel="noreferrer"><strong>extension everything issue</strong></a> which is closed too.
The main discussion was in fact about Type extensibility in a broad sense.
The feature is now tracked <a href="https://github.com/dotnet/csharplang/issues/192" rel="noreferrer"><strong>here as a proposal</strong></a> and has been removed from <a href="https://github.com/dotnet/csharplang/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3A%22Proposal+champion%22+milestone%3A7.0" rel="noreferrer"><strong>7.0 milestone</strong></a>.</p>
<p><strong><em>Update: August, 2017 - C# 8.0 proposed feature</em></strong></p>
<p>While it still remains only a <em>proposed</em> feature, we have now a clearer view of what would be its syntax. Keep in mind that this will be the new syntax for extension methods as well:</p>
<pre><code>public interface IEmployee
{
public decimal Salary { get; set; }
}
public class Employee
{
public decimal Salary { get; set; }
}
public extension MyPersonExtension extends Person : IEmployee
{
private static readonly ConditionalWeakTable<Person, Employee> _employees =
new ConditionalWeakTable<Person, Employee>();
public decimal Salary
{
get
{
// `this` is the instance of Person
return _employees.GetOrCreate(this).Salary;
}
set
{
Employee employee = null;
if (!_employees.TryGetValue(this, out employee)
{
employee = _employees.GetOrCreate(this);
}
employee.Salary = value;
}
}
}
IEmployee person = new Person();
var salary = person.Salary;
</code></pre>
<p>Similar to partial classes, but compiled as a separate class/type in a different assembly. Note you will also be able to add static members and operators this way. As mentioned in <a href="https://channel9.msdn.com/Blogs/Seth-Juarez/A-Preview-of-C-8-with-Mads-Torgersen" rel="noreferrer">Mads Torgensen podcast</a>, <strong><em>the extension won't have any state (so it cannot add private instance members to the class) which means you won't be able to add private instance data linked to the instance</em></strong>. The reason invoked for that is it would imply to manage internally dictionaries and it could be difficult (memory management, etc...).
For this, you can still use the <code>TypeDescriptor</code>/<code>ConditionalWeakTable</code> technique described earlier and with the property extension, hides it under a nice property.</p>
<p>Syntax is still subject to change as implies this <a href="https://github.com/dotnet/csharplang/issues/840" rel="noreferrer">issue</a>. For example, <code>extends</code> could be replaced by <code>for</code> which some may feel more natural and less java related.</p>
<p><strong>Update December 2018 - Roles, Extensions and static interface members</strong></p>
<p><em>Extension everything</em> didn't make it to C# 8.0, because of some of drawbacks explained as the end of this <a href="https://github.com/dotnet/csharplang/issues/1711" rel="noreferrer">GitHub ticket</a>. So, there was an exploration to improve the design. <a href="https://github.com/dotnet/csharplang/issues/1711" rel="noreferrer">Here</a>, Mads Torgensen explains what are <strong>roles and extensions</strong> and how they differs:</p>
<blockquote>
<p>Roles allow interfaces to be implemented on specific values of a given
type. Extensions allow interfaces to be implemented on all values of a
given type, within a specific region of code.</p>
</blockquote>
<p>It can be seen at a split of previous proposal in two use cases. The <strong>new syntax for extension</strong> would be like this:</p>
<pre><code>public extension ULongEnumerable of ulong
{
public IEnumerator<byte> GetEnumerator()
{
for (int i = sizeof(ulong); i > 0; i--)
{
yield return unchecked((byte)(this >> (i-1)*8));
}
}
}
</code></pre>
<p>then you would be able to do this:</p>
<pre><code>foreach (byte b in 0x_3A_9E_F1_C5_DA_F7_30_16ul)
{
WriteLine($"{e.Current:X}");
}
</code></pre>
<p>And for a <strong>static interface</strong>:</p>
<pre><code>public interface IMonoid<T> where T : IMonoid<T>
{
static T operator +(T t1, T t2);
static T Zero { get; }
}
</code></pre>
<p>Add an <strong>extension property</strong> on <code>int</code> and treat the <code>int</code> as <code>IMonoid<int></code>:</p>
<pre><code>public extension IntMonoid of int : IMonoid<int>
{
public static int Zero => 0;
}
</code></pre> | {
"question_id": 619033,
"question_date": "2009-03-06T14:30:44.747Z",
"question_score": 907,
"tags": "c#|properties|extension-methods",
"answer_id": 34976295,
"answer_date": "2016-01-24T13:22:20.180Z",
"answer_score": 631
} |
Please answer the following Stack Overflow question:
Title: How can foreign key constraints be temporarily disabled using T-SQL?
<p>Are disabling and enabling foreign key constraints supported in SQL Server? Or is my only option to <strong><code>drop</code></strong> and then <strong>re-<code>create</code></strong> the constraints?</p> | <p>If you want to disable all constraints in the database just run this code:</p>
<pre><code>-- disable all constraints
EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"
</code></pre>
<p>To switch them back on, run: (the print is optional of course and it is just listing the tables)</p>
<pre><code>-- enable all constraints
exec sp_MSforeachtable @command1="print '?'", @command2="ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"
</code></pre>
<p>I find it useful when populating data from one database to another. It is much better approach than dropping constraints. As you mentioned it comes handy when dropping all the data in the database and repopulating it (say in test environment). </p>
<p>If you are deleting all the data you may find <a href="https://stackoverflow.com/questions/155246/how-do-you-truncate-all-tables-in-a-database-using-tsql#156813">this solution</a> to be helpful.</p>
<p>Also sometimes it is handy to disable all triggers as well, you can see the complete solution <a href="https://stackoverflow.com/questions/123558/sql-server-2005-t-sql-to-temporarily-disable-a-trigger#123966">here</a>.</p> | {
"question_id": 159038,
"question_date": "2008-10-01T18:33:43.630Z",
"question_score": 906,
"tags": "sql-server|tsql|foreign-keys|constraints",
"answer_id": 161410,
"answer_date": "2008-10-02T08:50:21.667Z",
"answer_score": 1212
} |
Please answer the following Stack Overflow question:
Title: npm WARN package.json: No repository field
<p>I installed Express.js with the following command:</p>
<pre><code>sudo npm install -g express
</code></pre>
<p>I get the following warnings:</p>
<pre><code>npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No readme data.
npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No repository field.
npm WARN package.json [email protected] No repository field.
</code></pre>
<p>I'm new to Node.js and Express.js. Why do I have the above warnings? Should I be worried?</p> | <p>It's just a check as of NPM v1.2.20, they report this as a warning.</p>
<p>However, don't worry, there are <em>sooooooo</em> many packages which still don't have the <code>repository</code> field in their <code>package.json</code>. The field is used for informational purposes.</p>
<p>In the case you're a package author, put the <code>repository</code> in your <code>package.json</code>, like this:</p>
<pre class="lang-json prettyprint-override"><code>"repository": {
"type": "git",
"url": "git://github.com/username/repository.git"
}
</code></pre>
<p>Read more about the <a href="https://docs.npmjs.com/cli/v8/configuring-npm/package-json#repository" rel="noreferrer"><code>repository</code></a> field, and see the <a href="https://github.com/npm/npm/issues/3568" rel="noreferrer">logged bug</a> for further details.</p>
<hr />
<p><em>Additionally,</em> <a href="https://stackoverflow.com/a/23355019/2083599">as originally reported by @dan_nl</a>, you can set <code>private</code> key in your <code>package.json</code>.<br />
This will not only stop you from accidentally running <code>npm publish</code> in your app, but will also stop NPM from printing warnings regarding <code>package.json</code> problems.</p>
<pre class="lang-json prettyprint-override"><code>{
"name": "my-super-amazing-app",
"version": "1.0.0",
"private": true
}
</code></pre> | {
"question_id": 16827858,
"question_date": "2013-05-30T04:18:43.547Z",
"question_score": 906,
"tags": "node.js|express|npm",
"answer_id": 16827990,
"answer_date": "2013-05-30T04:33:30.330Z",
"answer_score": 1391
} |
Please answer the following Stack Overflow question:
Title: How to list npm user-installed packages
<p>How do I list the user-installed / environment package <em>only</em> in npm?</p>
<p>When I do <code>npm -g list</code>, it outputs every package and their dependencies. Instead I'd like to see the packages installed in the <em>current</em> working project or environment.</p> | <pre class="lang-bash prettyprint-override"><code>npm list -g --depth=0
</code></pre>
<ul>
<li><strong>npm</strong>: the Node.js package manager command line tool</li>
<li><strong>list -g</strong>: display a tree of every package found in the user’s folders (without the <code>-g</code> option it only shows the current directory’s packages)</li>
<li><strong>--depth 0 / --depth=0</strong>: avoid including every package’s dependencies in the tree view</li>
</ul> | {
"question_id": 17937960,
"question_date": "2013-07-30T03:45:53.117Z",
"question_score": 906,
"tags": "javascript|node.js|npm|package|package-managers",
"answer_id": 25497068,
"answer_date": "2014-08-26T02:20:18.537Z",
"answer_score": 1762
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.