input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: How make Eclipse/EGit recognize existing repository information after update?
<p>After upgrading Eclipse from Helios to Indigo with EGit plugin 1.0.0, all my projects seem to have lost their metadata about their git repositories, respectively.</p>
<p>In Helios, every Eclipse project was a git repository on its own. When updating to Indigo, i hoped i could continue using the workspace from Helios. After the update, all projects are still present in the workspace; and in each project directory, there's still the <code>.git</code> subdirectory, but Eclipse seems to treat each project as if it wasn't a git repository already.</p>
<p>So, there's still all git metadata in the project folders, but eclipse doesn't recognize them. Is there another way to "reactivate" the git functionality?</p> | <p>Thanks to Jeremy, i found how to reactivate the repos myself. Basically, two steps were required:</p>
<ol>
<li>Add the (already existing) local repository to EGit's <code>Git Repositories</code> view;</li>
<li>"Share" each of the projects again using "use or create repository".</li>
</ol>
<p>The second step won't work if the repo isn't available in the repository view. So, after an eclipse upgrade, do the following:</p>
<h2>Add the (already existing) local repository to EGit's <code>Git Repositories</code> view</h2>
<ul>
<li>Open the <code>Git Repositories</code> view:
<img src="https://i.stack.imgur.com/AwnQ9.png" alt="enter 'Git Repositories' View"></li>
<li>Hit the "add" button (Tooltip: <code>Add an existing local Git Repository to this view</code>)
<img src="https://i.stack.imgur.com/RwQGu.png" alt="add repositories"></li>
<li>In the "Add Git Repositories" dialogue, under <code>Search criteria</code>, enter the workspace directory, select "<code>Look for nested repositores</code>", and hit <kbd>Search</kbd>:
<img src="https://i.stack.imgur.com/Mz0S4.png" alt="select repositories to add"></li>
<li>Select the repositories you want to add and click <kbd>OK</kbd></li>
</ul>
<h2>"Share" each of the projects again using "use or create repository"</h2>
<ul>
<li>Open you existing project in Eclipse's <code>Project explorer</code>;</li>
<li>Right-click and select "<code>Team</code> -> <code>Share Project...</code>":
<img src="https://i.stack.imgur.com/wvVCa.png" alt="select share project"></li>
<li><p>Select Git Project, and in the next dialogue, select "<code>Use or create Repository in parent folder of project</code>". Important: don't try to select the repository from the combo box that's visible when "<code>Use or create Repository in parent folder of project</code>" isn't selected - it won't work.</p>
<p><img src="https://i.stack.imgur.com/a6e43.png" alt="select repository to use"></p></li>
</ul>
<p>The wizard suggests the local git repository that's located in the current project, so just hit <kbd>Finish</kbd>.</p> | {
"question_id": 7194877,
"question_date": "2011-08-11T12:06:47.330Z",
"question_score": 215,
"tags": "git|eclipse",
"answer_id": 7194878,
"answer_date": "2011-08-12T08:37:31.777Z",
"answer_score": 338
} |
Please answer the following Stack Overflow question:
Title: What does the git index contain EXACTLY?
<p>What does the Git index exactly contain, and what command can I use to view the content of the index?</p>
<hr />
<p>Thanks for all your answers. I know that the index acts as a staging area, and what is committed is in the index rather than the working tree. I am just curious about what an index object consists of. I guess it might be a list of filename/directory names, SHA-1 pairs, a kind of virtual tree maybe?</p>
<p>Is there, in Git terminology, any <em>plumbing</em> command that I can use to list the contents of the index?</p> | <p>The Git book contains an article on <a href="http://shafiulazam.com/gitbook/7_the_git_index.html" rel="noreferrer">what an index includes</a>:</p>
<blockquote>
<p>The index is a binary file (generally kept in <code>.git/index</code>) containing a sorted list of path names, each with permissions and the SHA1 of a blob object; <code>git ls-files</code> can show you the contents of the index:</p>
</blockquote>
<pre><code>$ git ls-files --stage
100644 63c918c667fa005ff12ad89437f2fdc80926e21c 0 .gitignore
100644 5529b198e8d14decbe4ad99db3f7fb632de0439d 0 .mailmap
</code></pre>
<p>The <a href="http://www.kernel.org/pub/software/scm/git/docs/technical/racy-git.txt" rel="noreferrer">Racy git problem</a> gives some more details on that structure:</p>
<blockquote>
<p>The index is one of the most important data structures in git.<br />
It represents a virtual working tree state by recording list of paths and their object names and serves as a staging area to write out the next tree object to be committed.<br />
The state is "virtual" in the sense that it does not necessarily have to, and often does not, match the files in the working tree.</p>
</blockquote>
<hr />
<p>Nov. 2021: see also "<a href="https://github.blog/2021-11-10-make-your-monorepo-feel-small-with-gits-sparse-index/" rel="noreferrer">Make your monorepo feel small with Git’s sparse index</a>" from <a href="https://twitter.com/stolee" rel="noreferrer"><strong>Derrick Stolee</strong></a> (Microsoft/GitHub)</p>
<p><a href="https://i.stack.imgur.com/NueSy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NueSy.png" alt="https://github.blog/wp-content/uploads/2021/11/Fig-1-working-directory-index-commit-history.png" /></a></p>
<blockquote>
<p>The Git index is a critical data structure in Git. It serves as the “staging area” between the files you have on your filesystem and your commit history.</p>
<ul>
<li>When you run <code>git add</code>, the files from your working directory are hashed and stored as objects in the index, leading them to be “staged changes”.</li>
<li>When you run <code>git commit</code>, the staged changes as stored in the index are used to create that new commit.</li>
<li>When you run <code>git checkout</code>, Git takes the data from a commit and writes it to the working directory and the index.</li>
</ul>
<p>In addition to storing your staged changes, the index also stores filesystem information about your working directory.<br />
This helps Git report changed files more quickly.</p>
</blockquote>
<hr />
<p>To see more, cf. "<a href="https://github.com/git/git/blob/master/Documentation/technical/index-format.txt" rel="noreferrer"><strong>git/git/Documentation/technical/index-format.txt</strong></a>":</p>
<h2>The Git index file has the following format</h2>
<blockquote>
<p>All binary numbers are in network byte order.<br />
<strong>Version 2</strong> is described here unless stated otherwise.</p>
</blockquote>
<blockquote>
<ul>
<li>A 12-byte header consisting of:</li>
<li>4-byte <strong>signature</strong>:<br />
The signature is { '<code>D</code>', '<code>I</code>', '<code>R</code>', '<code>C</code>' } (stands for "<strong><code>dircache</code></strong>")</li>
<li>4-byte <strong>version number</strong>:<br />
The current supported versions are 2, 3 and 4.</li>
<li>32-bit number of index entries.</li>
<li>A number of sorted <strong><a href="https://github.com/git/git/blob/867b1c1bf68363bcfd17667d6d4b9031fa6a1300/Documentation/technical/index-format.txt#L38" rel="noreferrer">index entries</a></strong>.</li>
<li><strong>Extensions</strong>:<br />
Extensions are identified by signature.<br />
Optional extensions can be ignored if Git does not understand them.<br />
Git currently supports cached tree and resolve undo extensions.</li>
<li>4-byte extension signature. If the first byte is '<code>A</code>'..'<code>Z</code>' the extension is optional and can be ignored.</li>
<li>32-bit size of the extension</li>
<li>Extension data</li>
<li>160-bit SHA-1 over the content of the index file before this checksum.</li>
</ul>
</blockquote>
<hr />
<p><a href="https://stackoverflow.com/users/1483503/mljrg">mljrg</a> <a href="https://stackoverflow.com/users/1483503/mljrg">comments</a>:</p>
<blockquote>
<p>If the index is the place where the next commit is prepared, why doesn't "<code>git ls-files -s</code>" return nothing after commit?</p>
</blockquote>
<p>Because <strong>the index represents what is being tracked</strong>, and right after a commit, what is being tracked is identical to the last commit (<code>git diff --cached</code> returns nothing).</p>
<p>So <code>git ls-files -s</code> lists all files tracked (object name, mode bits and stage number in the output).</p>
<p>That list (of element tracked) is initialized with the content of a commit.<br />
When you switch branch, the index content is reset to the commit referenced by the branch you just switched to.</p>
<hr />
<p>Git 2.20 (Q4 2018) adds an <strong>Index Entry Offset Table (IEOT)</strong>:</p>
<p>See <a href="https://github.com/git/git/commit/77ff1127a4ca340fb9e81861a9851b0c3701bdc1" rel="noreferrer">commit 77ff112</a>, <a href="https://github.com/git/git/commit/3255089ada6fc8f18d41dfc37cf66d7af994603d" rel="noreferrer">commit 3255089</a>, <a href="https://github.com/git/git/commit/abb4bb83845dc012ffe1c04750d1a09edd598a82" rel="noreferrer">commit abb4bb8</a>, <a href="https://github.com/git/git/commit/c780b9cfe8d79331ed9797e328b1bf80666c4ac2" rel="noreferrer">commit c780b9c</a>, <a href="https://github.com/git/git/commit/3b1d9e045e1ad6c2cd5cbe668ccb740a82b50efb" rel="noreferrer">commit 3b1d9e0</a>, <a href="https://github.com/git/git/commit/371ed0defa2a8692731d164e7a2d5e53e0a22362" rel="noreferrer">commit 371ed0d</a> (10 Oct 2018) by <a href="https://github.com/benpeart" rel="noreferrer">Ben Peart (<code>benpeart</code>)</a>.<br />
See <a href="https://github.com/git/git/commit/252d079cbd27ca442d94535e3979145eceaf082b" rel="noreferrer">commit 252d079</a> (26 Sep 2018) by <a href="https://github.com/pclouds" rel="noreferrer">Nguyễn Thái Ngọc Duy (<code>pclouds</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/e27bfaaee37c4c9d7e94f945f82c3e452d2dc071" rel="noreferrer">commit e27bfaa</a>, 19 Oct 2018)</sup></p>
<blockquote>
<h2>ieot: add Index Entry Offset Table (IEOT) extension</h2>
</blockquote>
<blockquote>
<p>This patch enables addressing the CPU cost of loading the index by adding
additional data to the index that will allow us to efficiently multi-
thread the loading and conversion of cache entries.</p>
<p>It accomplishes this by adding an (optional) index extension that is a
table of offsets to blocks of cache entries in the index file.</p>
<p>To make this work for V4 indexes, when writing the cache entries, it periodically"resets" the prefix-compression by encoding the current entry as if the path name for the previous entry is completely different and saves the
offset of that entry in the IEOT.<br />
Basically, with V4 indexes, it generates offsets into blocks of prefix-compressed entries.</p>
</blockquote>
<p>With the <a href="https://stackoverflow.com/a/43667992/6309">new index.threads config setting</a>, the index loading is now faster.</p>
<hr />
<p>As a result (<a href="https://public-inbox.org/git/[email protected]/" rel="noreferrer">of using IEOT</a>), <a href="https://github.com/git/git/commit/7bd9631bfc17f685f79093f11e1bbe01ab280b1c" rel="noreferrer">commit 7bd9631</a> clean-up the <code>read-cache.c load_cache_entries_threaded()</code> function for Git 2.23 (Q3 2019).</p>
<p>See <a href="https://github.com/git/git/commit/837303700a73836930cfe1e870e5abb8c730e2fd" rel="noreferrer">commit 8373037</a>, <a href="https://github.com/git/git/commit/d713e88c401f2af054b7b653e83e2cd0795ef140" rel="noreferrer">commit d713e88</a>, <a href="https://github.com/git/git/commit/d92349dd5541ea2d54ec500e204372c93ee89d28" rel="noreferrer">commit d92349d</a>, <a href="https://github.com/git/git/commit/113c29ade08054ba2c543b41570e3a6643022b3d" rel="noreferrer">commit 113c29a</a>, <a href="https://github.com/git/git/commit/c95fc72f47341cf7cf80b3b878cc8d35684bc1e8" rel="noreferrer">commit c95fc72</a>, <a href="https://github.com/git/git/commit/7a2a721687f5d8027f6d380b60a2da62c202191b" rel="noreferrer">commit 7a2a721</a>, <a href="https://github.com/git/git/commit/c0165798952fff060243cdf199df30209f9995bc" rel="noreferrer">commit c016579</a>, <a href="https://github.com/git/git/commit/be27fb7b287a81b5b3c889121eab99d344272e8b" rel="noreferrer">commit be27fb7</a>, <a href="https://github.com/git/git/commit/13a178129ffe91b4d2443c7950a399a634488225" rel="noreferrer">commit 13a1781</a>, <a href="https://github.com/git/git/commit/7bd9631bfc17f685f79093f11e1bbe01ab280b1c" rel="noreferrer">commit 7bd9631</a>, <a href="https://github.com/git/git/commit/3c1dce8835a983ffc34f6656f665a04d9ce7da79" rel="noreferrer">commit 3c1dce8</a>, <a href="https://github.com/git/git/commit/cf7a901ae4dff574e78d7b03bbaecfeb9dcc44d7" rel="noreferrer">commit cf7a901</a>, <a href="https://github.com/git/git/commit/d64db5b334f8822284bcc7068e093d8fbfb46dd9" rel="noreferrer">commit d64db5b</a>, <a href="https://github.com/git/git/commit/76a7bc092efc2be59f1e42dc437154a9a1feed0a" rel="noreferrer">commit 76a7bc0</a> (09 May 2019) by <a href="https://github.com/peff" rel="noreferrer">Jeff King (<code>peff</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/c0e78f7e4687e7bd5ff0b83974b28c1cc81c5487" rel="noreferrer">commit c0e78f7</a>, 13 Jun 2019)</sup></p>
<blockquote>
<h2>read-cache: drop unused parameter from threaded load</h2>
</blockquote>
<blockquote>
<p>The <code>load_cache_entries_threaded()</code> function takes a <code>src_offset</code> parameter
that it doesn't use. This has been there since its inception in <a href="https://github.com/git/git/commit/77ff1127a4ca340fb9e81861a9851b0c3701bdc1" rel="noreferrer">77ff112</a> (<code>read-cache</code>: load cache entries on worker threads, 2018-10-10, Git v2.20.0-rc0).</p>
<p>Digging on the mailing list, that parameter was part of an <a href="https://public-inbox.org/git/[email protected]/" rel="noreferrer">earlier iteration of the series</a>, but became unnecessary when the code switched to using the IEOT extension.</p>
</blockquote>
<hr />
<p>With Git 2.29 (Q4 2020), the format description adjusts to the recent SHA-256 work.</p>
<p>See <a href="https://github.com/git/git/commit/8afa50aabcf18ab1904218e8019d623d11e36ed9" rel="noreferrer">commit 8afa50a</a>, <a href="https://github.com/git/git/commit/0756e61078b32686dc995df768e50725aba13b7e" rel="noreferrer">commit 0756e61</a>, <a href="https://github.com/git/git/commit/123712ba41164146cd711dab6fe107b62d443f12" rel="noreferrer">commit 123712b</a>, <a href="https://github.com/git/git/commit/5b6422a6160dc04faa6742434a4d162b4899cfe3" rel="noreferrer">commit 5b6422a</a> (15 Aug 2020) by <a href="https://github.com/none" rel="noreferrer">Martin Ågren (<code>none</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/74a395c4844f846d933b873c5548e19d06e1e89e" rel="noreferrer">commit 74a395c</a>, 19 Aug 2020)</sup></p>
<blockquote>
<h2><a href="https://github.com/git/git/commit/123712ba41164146cd711dab6fe107b62d443f12" rel="noreferrer"><code>index-format.txt</code></a>: document SHA-256 index format</h2>
<p><sup>Signed-off-by: Martin Ågren</sup></p>
</blockquote>
<blockquote>
<p>Document that in SHA-1 repositories, we use SHA-1 and in SHA-256 repositories, we use SHA-256, then replace all other uses of "SHA-1" with something more neutral.<br />
Avoid referring to "160-bit" hash values.</p>
</blockquote>
<p><code>technical/index-format</code> now includes in its <a href="https://github.com/git/git/blob/123712ba41164146cd711dab6fe107b62d443f12/Documentation/technical/index-format.txt#L6-L10" rel="noreferrer">man page</a>:</p>
<blockquote>
<p>All binary numbers are in network byte order.<br />
In a repository using the traditional SHA-1, checksums and object IDs
(object names) mentioned below are all computed using SHA-1.<br />
Similarly, in SHA-256 repositories, these values are computed using SHA-256.</p>
<p>Version 2 is described here unless stated otherwise.</p>
</blockquote> | {
"question_id": 4084921,
"question_date": "2010-11-03T07:20:42.737Z",
"question_score": 215,
"tags": "git|internals|git-index",
"answer_id": 4086986,
"answer_date": "2010-11-03T12:23:19.787Z",
"answer_score": 191
} |
Please answer the following Stack Overflow question:
Title: Max return value if empty query
<p>I have this query:</p>
<pre><code>int maxShoeSize = Workers
.Where(x => x.CompanyId == 8)
.Max(x => x.ShoeSize);
</code></pre>
<p>What will be in <code>maxShoeSize</code> if company 8 has no workers at all?</p>
<p><strong>UPDATE:</strong><br>
How can I change the query in order to get 0 and not an exception?</p> | <pre><code>int maxShoeSize = Workers.Where(x => x.CompanyId == 8)
.Select(x => x.ShoeSize)
.DefaultIfEmpty(0)
.Max();
</code></pre>
<p>The zero in <code>DefaultIfEmpty</code> is not necessary.</p> | {
"question_id": 6966680,
"question_date": "2011-08-06T12:07:55.803Z",
"question_score": 215,
"tags": "c#|.net|entity-framework|linq|lambda",
"answer_id": 6967222,
"answer_date": "2011-08-06T13:47:04.050Z",
"answer_score": 377
} |
Please answer the following Stack Overflow question:
Title: How can I unit test Arduino code?
<p>I'd like to be able to unit test my Arduino code. Ideally, I would be able to run any tests without having to upload the code to the Arduino. What tools or libraries can help me with this?</p>
<p>There is an <a href="http://radpartbrainmat.blogspot.com/search/label/arduemu" rel="noreferrer">Arduino emulator in development</a> which could be useful, but it doesn't yet seem to be ready for use.</p>
<p><a href="http://www.atmel.com/dyn/Products/tools_card.asp?tool_id=2725" rel="noreferrer">AVR Studio</a> from Atmel contains a chip simulator which could be useful, but I can't see how I would use it in conjunction with the Arduino IDE.</p> | <p>In the absence of any pre-existing unit test frameworks for Arduino, I have created <a href="http://github.com/mmurdoch/arduinounit/" rel="noreferrer">ArduinoUnit</a>. Here's a simple Arduino sketch demonstrating its use:</p>
<pre><code>#include <ArduinoUnit.h>
// Create test suite
TestSuite suite;
void setup() {
Serial.begin(9600);
}
// Create a test called 'addition' in the test suite
test(addition) {
assertEquals(3, 1 + 2);
}
void loop() {
// Run test suite, printing results to the serial port
suite.run();
}
</code></pre> | {
"question_id": 780819,
"question_date": "2009-04-23T08:43:15.300Z",
"question_score": 215,
"tags": "unit-testing|embedded|arduino|avr|avr-gcc",
"answer_id": 791519,
"answer_date": "2009-04-26T20:12:38.663Z",
"answer_score": 66
} |
Please answer the following Stack Overflow question:
Title: Where is the warnings screen option in Android Studio?
<p>I want to see warnings of my code in Android Studio, But i am unable to find the option to display warnings view. In case of eclipse we can see the warnings in the "Problems" view. </p>
<p>Can anyone suggest me, how to view warnings in android studio?</p> | <p>If, on the toolbar, you click Analyze -> Inspect Code; then in the window that pops up select how much of your project you want to inspect (I usually do Whole Project, but you might want to select a specific module), then click okay. </p>
<p>Android Studio will work for a bit, then the inspection window will pop up from the bottom with a list of results, subdivided by inspection.</p> | {
"question_id": 17206514,
"question_date": "2013-06-20T06:16:53.043Z",
"question_score": 215,
"tags": "android-studio",
"answer_id": 17265000,
"answer_date": "2013-06-23T20:27:53.567Z",
"answer_score": 287
} |
Please answer the following Stack Overflow question:
Title: Can git automatically switch between spaces and tabs?
<p>I use tabs for indentation in my python programs, but I would like to collaborate (using git) with people who use spaces instead.</p>
<p>Is there a way for git to automatically convert between spaces and tabs (say, 4 spaces = 1 tab) on pushing/fetching? (similar to the CR/LF conversion)</p> | <p>Here is the complete solution:</p>
<p>In your repository, add a file <code>.git/info/attributes</code> which contains:</p>
<pre><code>*.py filter=tabspace
</code></pre>
<p><strong>Linux/Unix</strong></p>
<p>Now run the commands:</p>
<pre><code>git config --global filter.tabspace.smudge 'unexpand --tabs=4 --first-only'
git config --global filter.tabspace.clean 'expand --tabs=4 --initial'
</code></pre>
<p><strong>OS X</strong></p>
<p>First install coreutils with brew:</p>
<pre><code>brew install coreutils
</code></pre>
<p>Now run the commands:</p>
<pre><code>git config --global filter.tabspace.smudge 'gunexpand --tabs=4 --first-only'
git config --global filter.tabspace.clean 'gexpand --tabs=4 --initial'
</code></pre>
<p><strong>All systems</strong></p>
<p>You may now check out all the files of your project. You can do that with:</p>
<pre><code>git checkout HEAD -- **
</code></pre>
<p>and all the python files will now have tabs instead of spaces.</p>
<p><strong>Edit</strong>: changed the forced checkout command. You should commit your work first, of course.</p> | {
"question_id": 2316677,
"question_date": "2010-02-23T08:26:04.387Z",
"question_score": 215,
"tags": "git|tabs|indentation",
"answer_id": 2318063,
"answer_date": "2010-02-23T12:32:36.840Z",
"answer_score": 207
} |
Please answer the following Stack Overflow question:
Title: What does npm -D flag mean?
<p>I am about to install <a href="https://github.com/firstandthird/load-grunt-config" rel="nofollow noreferrer">this npm package</a> and it says <code>npm install -D load-grunt-config</code>. What does the <code>-D</code> flag do?</p> | <p>The <code>-D</code> flag is the shortcut for: <code>--save-dev</code>. Source: <a href="https://docs.npmjs.com/cli/install" rel="noreferrer">https://docs.npmjs.com/cli/install</a></p>
<blockquote>
<p><strong>-D, --save-dev</strong>: Package will appear in your <strong>devDependencies</strong>.</p>
</blockquote> | {
"question_id": 23177336,
"question_date": "2014-04-20T01:07:38.707Z",
"question_score": 215,
"tags": "npm",
"answer_id": 23177406,
"answer_date": "2014-04-20T01:22:46.043Z",
"answer_score": 255
} |
Please answer the following Stack Overflow question:
Title: Possibility of duplicate Mongo ObjectId's being generated in two different collections?
<p>Is it possible for the same exact Mongo ObjectId to be generated for a document in two different collections? I realize that it's definitely very unlikely, but is it possible? </p>
<p>Without getting too specific, the reason I ask is that with an application that I'm working on we show public profiles of elected officials who we hope to convert into full fledged users of our site. We have separate collections for users and the elected officials who aren't currently members of our site. There are various other documents containing various pieces of data about the elected officials that all map back to the person using their elected official ObjectId.</p>
<p>After creating the account we still highlight the data that's associated to the elected official but they now also are a part of the users collection with a corresponding users ObjectId to map their profile to interactions with our application.</p>
<p>We had begun converting our application from MySql to Mongo a few months ago and while we're in transition we store the legacy MySql id for both of these data types and we're also starting to now store the elected official Mongo ObjectId in the users document to map back to the elected official data.</p>
<p>I was pondering just specifying the new user ObjectId as the previous elected official ObjectId to make things simpler but wanted to make sure that it wasn't possible to have a collision with any existing user ObjectId.</p>
<p>Thanks for your insight.</p>
<p>Edit: Shortly after posting this question, I realized that my proposed solution wasn't a very good idea. It would be better to just keep the current schema that we have in place and just link to the elected official '_id' in the users document.</p> | <p><strong>Short Answer</strong></p>
<p>Just to add a direct response to your initial question: YES, if you use BSON Object ID generation, then <em>for most drivers</em> the IDs are almost certainly going to be unique across collections. See below for what "almost certainly" means.</p>
<p><strong>Long Answer</strong></p>
<p>The BSON Object ID's generated by Mongo DB drivers are highly likely to be unique across collections. This is mainly because of the last 3 bytes of the ID, which <em>for most drivers</em> is generated via a static incrementing counter. That counter is collection-independent; it's global. The Java driver, for example, uses a randomly initialized, static AtomicInteger. </p>
<p>So why, in the Mongo docs, do they say that the IDs are "highly likely" to be unique, instead of outright saying that they WILL be unique? Three possibilities can occur where you won't get a unique ID (please let me know if there are more):</p>
<p>Before this discussion, recall that the BSON Object ID consists of:</p>
<p>[4 bytes seconds since epoch, 3 bytes machine hash, 2 bytes process ID, 3 bytes counter]</p>
<p>Here are the three possibilities, so you judge for yourself how likely it is to get a dupe:</p>
<p>1) Counter overflow: there are 3 bytes in the counter. If you happen to insert over 16,777,216 (2^24) documents in a single second, on the same machine, in the same process, then you may overflow the incrementing counter bytes and end up with two Object IDs that share the same time, machine, process, and counter values.</p>
<p>2) Counter non-incrementing: some Mongo drivers use random numbers instead of incrementing numbers for the counter bytes. In these cases, there is a 1/16,777,216 chance of generating a non-unique ID, but only if those two IDs are generated in the same second (i.e. before the time section of the ID updates to the next second), on the same machine, in the same process.</p>
<p>3) Machine and process hash to the same values. The machine ID and process ID values may, in some highly unlikely scenario, map to the same values for two different machines. If this occurs, and at the same time the two counters on the two different machines, during the same second, generate the same value, then you'll end up with a duplicate ID.</p>
<p>These are the three scenarios to watch out for. Scenario 1 and 3 seem highly unlikely, and scenario 2 is totally avoidable if you're using the right driver. You'll have to check the source of the driver to know for sure. </p> | {
"question_id": 4677237,
"question_date": "2011-01-13T05:58:53.083Z",
"question_score": 215,
"tags": "mongodb|database|nosql",
"answer_id": 5694803,
"answer_date": "2011-04-17T16:36:28.013Z",
"answer_score": 358
} |
Please answer the following Stack Overflow question:
Title: How to prevent moment.js from loading locales with webpack?
<p>Is there any way you can stop <code>moment.js</code> from loading all the locales (I just need English) when you're using webpack? I'm looking at the source and it seems that if <code>hasModule</code> is defined, which it is for webpack, then it always tries to <code>require()</code> every locale. I'm pretty sure this needs a pull request to fix. But is there any way we can fix this with the webpack config?</p>
<p>Here is my webpack config to load momentjs:</p>
<pre><code>resolve: {
alias: {
moment: path.join(__dirname, "src/lib/bower/moment/moment.js")
},
},
</code></pre>
<p>Then anywhere I need it, I just do <code>require('moment')</code>. This works but it's adding about 250 kB of unneeded language files to my bundle. Also I'm using the bower version of momentjs and gulp.</p>
<p>Also if this can't be fixed by the webpack config here is <a href="https://github.com/moment/moment/blob/develop/moment.js#L760-L772" rel="noreferrer">a link to the function where it loads the locales</a>. I tried adding <code>&& module.exports.loadLocales</code> to the <code>if</code> statement but I guess webpack doesn't actually work in a way where that would work. It just <code>require</code>s no matter what. I think it uses a regex now so I don't really know how you would even go about fixing it.</p> | <p>The code <code>require('./locale/' + name)</code> can use every file in the <code>locale</code> dir. So webpack includes every file as module in your bundle. It cannot know which language you are using.</p>
<p>There are <a href="http://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin">two plugins</a> that are useful to give webpack more information about which module should be included in your bundle: <code>ContextReplacementPlugin</code> and <code>IgnorePlugin</code>.</p>
<p><code>require('./locale/' + name)</code> is called a <a href="http://webpack.github.io/docs/context.html">context</a> (a require which contains an expression). webpack infers some information from this code fragment: A directory and a regular expression. Here: <code>directory = ".../moment/locale"</code> <code>regular expression = /^.*$/</code>. So by default every file in the <code>locale</code> directory is included.</p>
<p>The <code>ContextReplacementPlugin</code> allows to override the inferred information i.e. provide a new regular expression (to choose the languages you want to include).</p>
<p>Another approach is to ignore the require with the <code>IgnorePlugin</code>.</p>
<p>Here is an example:</p>
<pre><code>var webpack = require("webpack");
module.exports = {
// ...
plugins: [
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /de|fr|hu/)
// new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/)
]
};
</code></pre> | {
"question_id": 25384360,
"question_date": "2014-08-19T13:13:35.633Z",
"question_score": 215,
"tags": "javascript|gulp|momentjs|webpack",
"answer_id": 25426019,
"answer_date": "2014-08-21T12:09:17.720Z",
"answer_score": 319
} |
Please answer the following Stack Overflow question:
Title: What is the difference between the views and components folders in a Vue project?
<p>I just used the command line (<code>CLI</code>) to initialize a Vue.js project. The <code>CLI</code> created a <code>src/components</code> and <code>src/views</code> folder.</p>
<p>It has been a few months since I have worked with a Vue project and the folder structure seems new to me. </p>
<p>What is the difference between the <code>views</code> and <code>components</code> folders in a Vue project generated with <a href="https://github.com/vuejs/vue-cli" rel="noreferrer"><code>vue-cli</code></a>?</p> | <p>First of all, both folders, <code>src/components</code> and <code>src/views</code>, contain Vue components.</p>
<p>The key difference is that some Vue components act as <em>Views</em> for routing.</p>
<p>When dealing with routing in Vue, usually with <a href="https://router.vuejs.org/" rel="noreferrer"><strong>Vue Router</strong></a>, routes are defined in order to switch the current <em>view</em> used in the <a href="https://router.vuejs.org/api/#router-view" rel="noreferrer"><em><code><router-view></code></em></a> component. These routes are typically located at <code>src/router/routes.js</code>, where we can see something like this:</p>
<pre><code>import Home from '@/views/Home.vue'
import About from '@/views/About.vue'
export default [
{
path: '/',
name: 'home',
component: Home,
},
{
path: '/about',
name: 'about',
component: About,
},
]
</code></pre>
<p>The components located under <code>src/components</code> are less likely to be used in a route whereas components located under <code>src/views</code> will be used by at least one route.</p>
<hr>
<blockquote>
<p>Vue CLI aims to be the standard tooling baseline for the Vue
ecosystem. It ensures the various build tools work smoothly together
with sensible defaults so you can focus on writing your app instead of
spending days wrangling with configurations. At the same time, it
still offers the flexibility to tweak the config of each tool without
the need for ejecting.</p>
</blockquote>
<p>Vue CLI aims for rapid Vue.js development, it keeps things simple and offers flexibility. Its goal is to enable teams of varying skill levels to set up a new project and get started.</p>
<p>At the end of the day, <strong>it is a matter of convenience and application structure</strong>.</p>
<ul>
<li>Some people like to have their Views folder under <code>src/router</code> like
<a href="https://github.com/chrisvfritz/vue-enterprise-boilerplate/tree/master/src/router" rel="noreferrer"><strong>this</strong></a> enterprise boilerplate.</li>
<li>Some people call it <em>Pages</em> instead of <em>Views</em>.</li>
<li>Some people have all their components under the same folder.</li>
</ul>
<hr>
<h1>Choose the application structure that best suits the project you are working on.</h1> | {
"question_id": 50865828,
"question_date": "2018-06-14T20:57:39.880Z",
"question_score": 215,
"tags": "vue.js|vuejs2|vue-cli|vue-cli-3|vue-cli-4",
"answer_id": 50866150,
"answer_date": "2018-06-14T21:24:09.347Z",
"answer_score": 276
} |
Please answer the following Stack Overflow question:
Title: What is this question mark operator about?
<p>I'm reading <a href="https://doc.rust-lang.org/std/fs/struct.File.html" rel="noreferrer">the documentation for <code>File</code></a>:</p>
<pre><code>//..
let mut file = File::create("foo.txt")?;
//..
</code></pre>
<p>What is the <code>?</code> in this line? I do not recall seeing it in the Rust Book before.</p> | <p>As you may have noticed, Rust does not have exceptions. It has panics, but their use for error-handling is discouraged (they are meant for unrecoverable errors).</p>
<p>In Rust, error handling uses <a href="https://doc.rust-lang.org/std/result/enum.Result.html" rel="noreferrer"><code>Result</code></a>. A typical example would be:</p>
<pre><code>fn halves_if_even(i: i32) -> Result<i32, Error> {
if i % 2 == 0 {
Ok(i / 2)
} else {
Err(/* something */)
}
}
fn do_the_thing(i: i32) -> Result<i32, Error> {
let i = match halves_if_even(i) {
Ok(i) => i,
Err(e) => return Err(e),
};
// use `i`
}
</code></pre>
<p>This is great because:</p>
<ul>
<li>when writing the code you cannot accidentally forget to deal with the error,</li>
<li>when reading the code you can immediately see that there is a potential for error right here.</li>
</ul>
<p>It's less than ideal, however, in that it is very verbose. This is where the question mark operator <code>?</code> comes in.</p>
<p>The above can be rewritten as:</p>
<pre><code>fn do_the_thing(i: i32) -> Result<i32, Error> {
let i = halves_if_even(i)?;
// use `i`
}
</code></pre>
<p>which is much more concise.</p>
<p>What <code>?</code> does here is equivalent to the <code>match</code> statement above with an addition. In short:</p>
<ol>
<li>It unpacks the <code>Result</code> if OK</li>
<li>It <em>returns</em> the error if not, calling <a href="https://doc.rust-lang.org/std/convert/trait.From.html#tymethod.from" rel="noreferrer"><code>From::from</code></a> on the error value to potentially convert it to another type.</li>
</ol>
<p>It's a bit magic, but error handling needs some magic to cut down the boilerplate, and unlike exceptions it is immediately visible which function calls may or may not error out: those that are adorned with <code>?</code>.</p>
<p>One example of the magic is that this also works for <code>Option</code>:</p>
<pre><code>// Assume
// fn halves_if_even(i: i32) -> Option<i32>
fn do_the_thing(i: i32) -> Option<i32> {
let i = halves_if_even(i)?;
// use `i`
}
</code></pre>
<p>The <code>?</code> operator, <a href="https://github.com/rust-lang/rust/pull/31954" rel="noreferrer">stabilized in Rust version 1.13.0</a> is powered by the (unstable) <a href="https://doc.rust-lang.org/std/ops/trait.Try.html" rel="noreferrer"><code>Try</code></a> trait.</p>
<p>See also:</p>
<ul>
<li><a href="https://stackoverflow.com/q/40545332/155423">Is the question mark operator ? equivalent to the try! macro?</a></li>
<li><a href="https://stackoverflow.com/q/30555477/155423">Why do try!() and ? not compile when used in a function that doesn't return Option or Result?</a></li>
</ul> | {
"question_id": 42917566,
"question_date": "2017-03-21T02:50:31.793Z",
"question_score": 215,
"tags": "rust",
"answer_id": 42921174,
"answer_date": "2017-03-21T07:54:49.493Z",
"answer_score": 281
} |
Please answer the following Stack Overflow question:
Title: Localization and internationalization, what's the difference?
<p>I was going to ask a question about preparing a desktop application to support multiple languages on the UI. </p>
<p>In my search for existing questions on the topic I was thinking the word "International", so I selected the Internationalization tag and read through some matching questions.</p>
<p>Eventually I realized I should probably be looking under questions tagged Localization instead. However it appears I'm not alone in getting these two terms mixed up.</p>
<p>So, what are they key differences between Localization and Internationalization? </p>
<p>Also, is a clear distinction between them really that important?</p> | <dl>
<dt><strong>Internationalization (i18n)</strong></dt><dd>the process of changing your software so that it isn't hardwired to one language/locale/culture.</dd>
<dt><strong>Localization (l10n)</strong></dt><dd>the process of adding the appropriate resources to your software so that a particular language/locale is supported. It's bigger in scope than just <a href="http://en.wikipedia.org/wiki/Language_localization" rel="noreferrer" title="Wikipedia on language localization">this Wikipedia entry</a>, but it's a good start.</dd>
</dl>
<p><br>
The value of distinguishing between them is that (theoretically) once your program goes through the i18n process, you can then iterate many l10n processes as you need them; also, it's nice to be precise with language.</p> | {
"question_id": 506743,
"question_date": "2009-02-03T11:20:02.343Z",
"question_score": 215,
"tags": "localization|internationalization",
"answer_id": 506752,
"answer_date": "2009-02-03T11:23:37.843Z",
"answer_score": 241
} |
Please answer the following Stack Overflow question:
Title: Same-named attributes in attrs.xml for custom view
<p>I'm writing a few custom views which share some same-named attributes. In their respective <code><declare-styleable></code> section in <code>attrs.xml</code> I'd like to use the same names for attributes:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView1">
<attr name="myattr1" format="string" />
<attr name="myattr2" format="dimension" />
...
</declare-styleable>
<declare-styleable name="MyView2">
<attr name="myattr1" format="string" />
<attr name="myattr2" format="dimension" />
...
</declare-styleable>
</resources>
</code></pre>
<p>I'm getting an error saying that <code>myattr1</code> and <code>myattr2</code> are already defined. I found that I should omit the <code>format</code> attribute for <code>myattr1</code> and <code>myattr2</code> in <code>MyView2</code>, but if I do that, I obtain the following error in the console:</p>
<pre><code>[2010-12-13 23:53:11 - MyProject] ERROR: In <declare-styleable> MyView2, unable to find attribute
</code></pre>
<p>Is there a way I could accomplish this, maybe some sort of namespacing (just guessing)?</p> | <p><strong>Solution:</strong> Simply extract common attributes from both views and add them directly as children of the <code><resources></code> node:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="myattr1" format="string" />
<attr name="myattr2" format="dimension" />
<declare-styleable name="MyView1">
<attr name="myattr1" />
<attr name="myattr2" />
...
</declare-styleable>
<declare-styleable name="MyView2">
<attr name="myattr1" />
<attr name="myattr2" />
...
</declare-styleable>
</resources>
</code></pre> | {
"question_id": 4434327,
"question_date": "2010-12-13T22:58:41.260Z",
"question_score": 215,
"tags": "android|android-view|android-custom-view|android-custom-attributes",
"answer_id": 4464966,
"answer_date": "2010-12-16T20:17:54.580Z",
"answer_score": 451
} |
Please answer the following Stack Overflow question:
Title: Get keys from HashMap in Java
<p>I have a Hashmap in Java like this:</p>
<pre><code>private Map<String, Integer> team1 = new HashMap<String, Integer>();
</code></pre>
<p>Then I fill it like this:</p>
<pre><code>team1.put("United", 5);
</code></pre>
<p>How can I get the keys? Something like: <code>team1.getKey()</code> to return "United".</p> | <p>A <code>HashMap</code> contains more than one key. You can use <code>keySet()</code> to get the set of all keys.</p>
<pre><code>team1.put("foo", 1);
team1.put("bar", 2);
</code></pre>
<p>will store <code>1</code> with key <code>"foo"</code> and <code>2</code> with key <code>"bar"</code>. To iterate over all the keys:</p>
<pre><code>for ( String key : team1.keySet() ) {
System.out.println( key );
}
</code></pre>
<p>will print <code>"foo"</code> and <code>"bar"</code>.</p> | {
"question_id": 10462819,
"question_date": "2012-05-05T14:32:18.983Z",
"question_score": 214,
"tags": "java|data-structures|java-6",
"answer_id": 10462838,
"answer_date": "2012-05-05T14:34:30.233Z",
"answer_score": 376
} |
Please answer the following Stack Overflow question:
Title: PHP - Failed to open stream : No such file or directory
<p>In PHP scripts, whether calling <code>include()</code>, <code>require()</code>, <code>fopen()</code>, or their derivatives such as <code>include_once</code>, <code>require_once</code>, or even, <code>move_uploaded_file()</code>, one often runs into an error or warning: </p>
<blockquote>
<p>Failed to open stream : No such file or directory.</p>
</blockquote>
<p>What is a good process to quickly find the root cause of the problem?</p> | <p>There are many reasons why one might run into this error and thus a good checklist of what to check first helps considerably.</p>
<p>Let's consider that we are troubleshooting the following line:</p>
<pre><code>require "/path/to/file"
</code></pre>
<p><br></p>
<h1>Checklist</h1>
<p><br></p>
<h2>1. Check the file path for typos</h2>
<ul>
<li>either check manually (by visually checking the path)</li>
<li><p>or move whatever is called by <code>require*</code> or <code>include*</code> to its own variable, echo it, copy it, and try accessing it from a terminal:</p>
<pre><code>$path = "/path/to/file";
echo "Path : $path";
require "$path";
</code></pre>
<p>Then, in a terminal:</p>
<pre><code>cat <file path pasted>
</code></pre></li>
</ul>
<p><br></p>
<h2>2. Check that the file path is correct regarding relative vs absolute path considerations</h2>
<ul>
<li>if it is starting by a forward slash "/" then it is not referring to the root of your website's folder (the document root), but to the root of your server.
<ul>
<li>for example, your website's directory might be <code>/users/tony/htdocs</code></li>
</ul></li>
<li>if it is not starting by a forward slash then it is either relying on the include path (see below) or the path is relative. If it is relative, then PHP will calculate relatively to the path of the <a href="https://secure.php.net/manual/en/function.getcwd.php" rel="noreferrer">current working directory</a>.
<ul>
<li>thus, not relative to the path of your web site's root, or to the file where you are typing</li>
<li>for that reason, always use absolute file paths</li>
</ul></li>
</ul>
<p>Best practices :</p>
<p>In order to make your script robust in case you move things around, while still generating an absolute path at runtime, you have 2 options :</p>
<ol>
<li>use <code>require __DIR__ . "/relative/path/from/current/file"</code>. The <a href="https://secure.php.net/manual/en/language.constants.predefined.php" rel="noreferrer"><code>__DIR__</code> magic constant</a> returns the directory of the current file.</li>
<li><p>define a <code>SITE_ROOT</code> constant yourself :</p>
<ul>
<li>at the root of your web site's directory, create a file, e.g. <code>config.php</code></li>
<li><p>in <code>config.php</code>, write</p>
<pre><code>define('SITE_ROOT', __DIR__);
</code></pre></li>
<li><p>in every file where you want to reference the site root folder, include <code>config.php</code>, and then use the <code>SITE_ROOT</code> constant wherever you like :</p>
<pre><code>require_once __DIR__."/../config.php";
...
require_once SITE_ROOT."/other/file.php";
</code></pre></li>
</ul></li>
</ol>
<p>These 2 practices also make your application more portable because it does not rely on ini settings like the include path.</p>
<p><br></p>
<h2>3. Check your include path</h2>
<p>Another way to include files, neither relatively nor purely absolutely, is to rely on the <a href="https://secure.php.net/manual/en/ini.core.php#ini.include-path" rel="noreferrer">include path</a>. This is often the case for libraries or frameworks such as the Zend framework.</p>
<p>Such an inclusion will look like this :</p>
<pre><code>include "Zend/Mail/Protocol/Imap.php"
</code></pre>
<p>In that case, you will want to make sure that the folder where "Zend" is, is part of the include path.</p>
<p>You can check the include path with :</p>
<pre><code>echo get_include_path();
</code></pre>
<p>You can add a folder to it with :</p>
<pre><code>set_include_path(get_include_path().":"."/path/to/new/folder");
</code></pre>
<p><br></p>
<h2>4. Check that your server has access to that file</h2>
<p>It might be that all together, the user running the server process (Apache or PHP) simply doesn't have permission to read from or write to that file.</p>
<p>To check under what user the server is running you can use <a href="https://secure.php.net/manual/en/function.posix-getpwuid.php" rel="noreferrer">posix_getpwuid</a> :</p>
<pre><code>$user = posix_getpwuid(posix_geteuid());
var_dump($user);
</code></pre>
<p>To find out the permissions on the file, type the following command in the terminal:</p>
<pre><code>ls -l <path/to/file>
</code></pre>
<p>and look at <a href="https://en.wikipedia.org/wiki/File_system_permissions#Symbolic_notation" rel="noreferrer">permission symbolic notation</a></p>
<p><br></p>
<h2>5. Check PHP settings</h2>
<p>If none of the above worked, then the issue is probably that some PHP settings forbid it to access that file.</p>
<p>Three settings could be relevant :</p>
<ol>
<li><a href="https://secure.php.net/manual/en/ini.core.php#ini.open-basedir" rel="noreferrer">open_basedir</a>
<ul>
<li>If this is set PHP won't be able to access any file outside of the specified directory (not even through a symbolic link).</li>
<li>However, the default behavior is for it not to be set in which case there is no restriction</li>
<li>This can be checked by either calling <a href="https://secure.php.net/manual/en/function.phpinfo.php" rel="noreferrer"><code>phpinfo()</code></a> or by using <code>ini_get("open_basedir")</code></li>
<li>You can change the setting either by editing your php.ini file or your httpd.conf file</li>
</ul></li>
<li><a href="https://secure.php.net/manual/en/features.safe-mode.php" rel="noreferrer">safe mode</a>
<ul>
<li>if this is turned on restrictions might apply. However, this has been removed in PHP 5.4. If you are still on a version that supports safe mode upgrade to a PHP version that is <a href="http://php.net/eol.php" rel="noreferrer">still being supported</a>.</li>
</ul></li>
<li><a href="https://secure.php.net/manual/en/filesystem.configuration.php" rel="noreferrer">allow_url_fopen and allow_url_include</a>
<ul>
<li>this applies only to including or opening files through a network process such as http:// not when trying to include files on the local file system</li>
<li>this can be checked with <code>ini_get("allow_url_include")</code> and set with <code>ini_set("allow_url_include", "1")</code></li>
</ul></li>
</ol>
<p><br></p>
<h1>Corner cases</h1>
<p>If none of the above enabled to diagnose the problem, here are some special situations that could happen :</p>
<p><br></p>
<h2>1. The inclusion of library relying on the include path</h2>
<p>It can happen that you include a library, for example, the Zend framework, using a relative or absolute path. For example :</p>
<pre><code>require "/usr/share/php/libzend-framework-php/Zend/Mail/Protocol/Imap.php"
</code></pre>
<p>But then you still get the same kind of error.</p>
<p>This could happen because the file that you have (successfully) included, has itself an include statement for another file, and that second include statement assumes that you have added the path of that library to the include path.</p>
<p>For example, the Zend framework file mentioned before could have the following include :</p>
<pre><code>include "Zend/Mail/Protocol/Exception.php"
</code></pre>
<p>which is neither an inclusion by relative path, nor by absolute path. It is assuming that the Zend framework directory has been added to the include path.</p>
<p>In such a case, the only practical solution is to add the directory to your include path.</p>
<p><br></p>
<h2>2. SELinux</h2>
<p>If you are running Security-Enhanced Linux, then it might be the reason for the problem, by denying access to the file from the server.</p>
<p><strong>To check whether SELinux is enabled</strong> on your system, run the <code>sestatus</code> command in a terminal. If the command does not exist, then SELinux is not on your system. If it does exist, then it should tell you whether it is enforced or not.</p>
<p><strong>To check whether SELinux policies are the reason</strong> for the problem, you can try turning it off temporarily. However be CAREFUL, since this will disable protection entirely. Do not do this on your production server.</p>
<pre><code>setenforce 0
</code></pre>
<p>If you no longer have the problem with SELinux turned off, then this is the root cause.</p>
<p><strong>To solve it</strong>, you will have to configure SELinux accordingly.</p>
<p>The following context types will be necessary :</p>
<ul>
<li><code>httpd_sys_content_t</code> for files that you want your server to be able to read</li>
<li><code>httpd_sys_rw_content_t</code> for files on which you want read and write access</li>
<li><code>httpd_log_t</code> for log files</li>
<li><code>httpd_cache_t</code> for the cache directory</li>
</ul>
<p>For example, to assign the <code>httpd_sys_content_t</code> context type to your website root directory, run :</p>
<pre><code>semanage fcontext -a -t httpd_sys_content_t "/path/to/root(/.*)?"
restorecon -Rv /path/to/root
</code></pre>
<p>If your file is in a home directory, you will also need to turn on the <code>httpd_enable_homedirs</code> boolean :</p>
<pre><code>setsebool -P httpd_enable_homedirs 1
</code></pre>
<p>In any case, there could be a variety of reasons why SELinux would deny access to a file, depending on your policies. So you will need to enquire into that. <a href="http://www.serverlab.ca/tutorials/linux/web-servers-linux/configuring-selinux-policies-for-apache-web-servers/" rel="noreferrer">Here</a> is a tutorial specifically on configuring SELinux for a web server.</p>
<p><br></p>
<h2>3. Symfony</h2>
<p>If you are using Symfony, and experiencing this error when uploading to a server, then it can be that the app's cache hasn't been reset, either because <code>app/cache</code> has been uploaded, or that cache hasn't been cleared.</p>
<p>You can test and fix this by running the following console command:</p>
<pre><code>cache:clear
</code></pre>
<p><br></p>
<h2>4. Non ACSII characters inside Zip file</h2>
<p>Apparently, this error can happen also upon calling <code>zip->close()</code> when some files inside the zip have non-ASCII characters in their filename, such as "é".</p>
<p>A potential solution is to wrap the file name in <code>utf8_decode()</code> before creating the target file.</p>
<p><em>Credits to <a href="https://stackoverflow.com/users/4217158/fran-cano">Fran Cano</a> for identifying and suggesting a solution to this issue</em></p> | {
"question_id": 36577020,
"question_date": "2016-04-12T14:58:40.190Z",
"question_score": 214,
"tags": "php|require|fopen|include-path",
"answer_id": 36577021,
"answer_date": "2016-04-12T14:58:40.190Z",
"answer_score": 325
} |
Please answer the following Stack Overflow question:
Title: Android device does not show up in adb list
<p>I have a HP Slate 21 that is connected to my Windows box using a USB cable. USB debugging is enabled on the device. After <a href="https://stackoverflow.com/a/15609366/3063884">adding the proper <code>%SingleAdbInterface%</code> and <code>%CompositeAdbInterface%</code></a> entries to the <code>android_winusb.inf</code> file, I now see "Android ADB Interface" in my Device Manager. However, running <code>adb devices</code> at the command-line does not show the device.</p>
<p>I have another HP slate 7 that shows up just fine under <code>adb devices</code>.</p>
<p>The only difference I see from Device Manager is that the one that works is named "Android Composite ADB Interface" and the other one is named "Android ADB Interface."</p>
<p>There is yet another subtle difference. In the winusb.inf file, for Slate 7 I have two <code>%CompositeAdbInterface%</code> entries defined but for Slate 21, there is just one <code>%CompositeAdbInterface%</code> entry defined.</p>
<p>What could be wrong with my setup?</p> | <p>Looks like the installed driver was in bad state. Here is what I did to make it work:</p>
<ol>
<li>Delete the device from Device Manager.</li>
<li>Rescan for hardware changes.</li>
<li>List item "Slate 21" will show up with "Unknown driver" status.</li>
<li>Click on "Update Driver" and select /extras/google/usb_driver</li>
</ol>
<p>Device Manager will find the driver and warn you about installing it. Select "Yes."
This time the device got installed properly.</p>
<p>Note that I didn't have to modify winusb.inf file or update any other driver.</p>
<p>Hope this helps.</p> | {
"question_id": 21170392,
"question_date": "2014-01-16T18:53:27.417Z",
"question_score": 214,
"tags": "android|adb",
"answer_id": 21470729,
"answer_date": "2014-01-31T01:02:12.580Z",
"answer_score": 51
} |
Please answer the following Stack Overflow question:
Title: Random number between 0 and 1?
<p>I want a random number between 0 and 1, like 0.3452. I used <code>random.randrange(0, 1)</code> but it is always 0 for me. What should I do?</p> | <p>You can use <code>random.uniform</code></p>
<pre><code>import random
random.uniform(0, 1)
</code></pre> | {
"question_id": 33359740,
"question_date": "2015-10-27T03:59:10.753Z",
"question_score": 214,
"tags": "python|random",
"answer_id": 33359801,
"answer_date": "2015-10-27T04:06:00.660Z",
"answer_score": 326
} |
Please answer the following Stack Overflow question:
Title: java.lang.NoClassDefFoundError: Could not initialize class XXX
<pre><code>public class PropHolder {
public static Properties prop;
static {
//code for loading properties from file
}
}
// Referencing the class somewhere else:
Properties prop = PropHolder.prop;
</code></pre>
<p><code>class PropHolder</code> is a class of my own. The class resides in the same JAR file of the main class. So that should not because any JAR is missing from classpath.</p>
<p>When I look in to the JAR file by <code>jar tf myjarfile</code>, I can see the <code>PropHolder.class</code> listed there.</p>
<p>Btw: the code is running fine on my local machine. But couldn't work when I deploy it with some script onto a Linux server. So I think it is not the problem of the code.
But for some reason. the deploy process is very hard to track.</p>
<p>What could be the problem?</p> | <p>My best bet is there is an issue here:</p>
<pre><code>static {
//code for loading properties from file
}
</code></pre>
<p>It would appear some uncaught exception occurred and propagated up to the actual ClassLoader attempting to load the class. We would need a stacktrace to confirm this though.</p>
<p>Either that or it occurred when creating <code>PropHolder.prop</code> static variable.</p> | {
"question_id": 7325579,
"question_date": "2011-09-06T20:12:10.047Z",
"question_score": 214,
"tags": "java|jar|runtime|noclassdeffounderror",
"answer_id": 7325829,
"answer_date": "2011-09-06T20:35:58.883Z",
"answer_score": 257
} |
Please answer the following Stack Overflow question:
Title: Laravel-5 'LIKE' equivalent (Eloquent)
<p>I'm using the below code to pull some results from the database with Laravel 5.</p>
<pre><code>BookingDates::where('email', Input::get('email'))->orWhere('name', 'like', Input::get('name'))->get()
</code></pre>
<p>However, the orWhereLike doesn't seem to be matching any results. What does that code produce in terms of MySQL statements?</p>
<p>I'm trying to achieve something like the following:</p>
<pre><code>select * from booking_dates where email='[email protected]' or name like '%John%'
</code></pre> | <p>If you want to see what is run in the database use <code>dd(DB::getQueryLog())</code> to see what queries were run.</p>
<p>Try this</p>
<pre><code>BookingDates::where('email', Input::get('email'))
->orWhere('name', 'like', '%' . Input::get('name') . '%')->get();
</code></pre> | {
"question_id": 30761950,
"question_date": "2015-06-10T16:19:15.273Z",
"question_score": 214,
"tags": "php|mysql|laravel-5",
"answer_id": 30762205,
"answer_date": "2015-06-10T16:31:45.903Z",
"answer_score": 489
} |
Please answer the following Stack Overflow question:
Title: Set NOW() as Default Value for datetime datatype?
<p>I have two columns in table users namely <code>registerDate and lastVisitDate</code> which consist of datetime data type. I would like to do the following.</p>
<ol>
<li>Set registerDate defaults value to MySQL NOW()</li>
<li>Set lastVisitDate default value to <code>0000-00-00 00:00:00</code> Instead of null which it uses by default.</li>
</ol>
<p>Because the table already exists and has existing records, I would like to use Modify table. I've tried using the two piece of code below, but neither works. </p>
<pre><code>ALTER TABLE users MODIFY registerDate datetime DEFAULT NOW()
ALTER TABLE users MODIFY registerDate datetime DEFAULT CURRENT_TIMESTAMP;
</code></pre>
<p>It gives me Error : <code>ERROR 1067 (42000): Invalid default value for 'registerDate'</code></p>
<p>Is it possible for me to set the default datetime value to NOW() in MySQL?</p> | <p>As of MySQL 5.6.5, you can use the <code>DATETIME</code> type with a dynamic default value:</p>
<pre><code>CREATE TABLE foo (
creation_time DATETIME DEFAULT CURRENT_TIMESTAMP,
modification_time DATETIME ON UPDATE CURRENT_TIMESTAMP
)
</code></pre>
<p>Or even combine both rules:</p>
<pre><code>modification_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
</code></pre>
<p>Reference:<br>
<a href="http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.7/en/timestamp-initialization.html</a><br>
<a href="http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html" rel="noreferrer">http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html</a></p>
<p>Prior to 5.6.5, you need to use the <code>TIMESTAMP</code> data type, which automatically updates whenever the record is modified. Unfortunately, however, only one auto-updated <code>TIMESTAMP</code> field can exist per table.</p>
<pre><code>CREATE TABLE mytable (
mydate TIMESTAMP
)
</code></pre>
<p>See: <a href="http://dev.mysql.com/doc/refman/5.1/en/create-table.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.1/en/create-table.html</a></p>
<p>If you want to prevent MySQL from updating the timestamp value on <code>UPDATE</code> (so that it only triggers on <code>INSERT</code>) you can change the definition to:</p>
<pre><code>CREATE TABLE mytable (
mydate TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
</code></pre> | {
"question_id": 5818423,
"question_date": "2011-04-28T12:14:03.573Z",
"question_score": 214,
"tags": "mysql|sql|datetime|mysql-error-1067",
"answer_id": 5818452,
"answer_date": "2011-04-28T12:16:51.607Z",
"answer_score": 268
} |
Please answer the following Stack Overflow question:
Title: Getting the error "Missing $ inserted" in LaTeX
<p>I try to write the following in latex:</p>
<pre><code>\begin{itemize}
\item \textbf{insert(element|text)} inserts the element or text passed at the start of the selection.
\item \textbf{insert_after(element|text)} inserts the element or text passed at the end of the selection.
\item \textbf{replace(element|text)} replaces the selection with the passed text/element.
\item \textbf{delete()} deletes the selected text.
\item \textbf{annotate(name,value)} annotates the selected text with the passed name and value-pair. This can either be a hidden meta-data about the selection, or can alter the visible appearance.
\item \textbf{clear_annotation()} removes any annotation for this specific selection.
\item \textbf{update_element(value)} performs an update of the element at the selection with the passed value.
\end{itemize}
</code></pre>
<p>For some reason, I get a bunch of errors. I think there is something with the use of the word "insert". I get errors like "Missing $ inserted", so it seems like the parses tries to fix some "errors" on my parts. Do I need to escape words like "insert", how do I do that?</p> | <p>The "Missing $ inserted" is probably caused by the underscores and bars. These characters in LaTeX have special meaning in math mode (which is delimited by <code>$</code> characters). Try escaping them; e.g. <code>update\_element</code> instead of <code>update_element</code>.</p>
<p>However, if you're trying to display code, a better solution would be to use the <a href="https://en.wikibooks.org/wiki/LaTeX/Paragraph_Formatting#Verbatim_text" rel="noreferrer"><code>\verb</code> command</a>, which will typeset the text in a monospaced font and will automatically handle underscores and bars correctly (no need to escape them with <code>\</code>).</p> | {
"question_id": 2476831,
"question_date": "2010-03-19T11:34:10.740Z",
"question_score": 214,
"tags": "latex",
"answer_id": 2476868,
"answer_date": "2010-03-19T11:41:15.763Z",
"answer_score": 373
} |
Please answer the following Stack Overflow question:
Title: How to put scroll bar only for modal-body?
<p>I have the following element:</p>
<pre><code><div class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" style="overflow-y: scroll; max-height:85%; margin-top: 50px; margin-bottom:50px;" >
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title"></h3>
</div>
<div class="modal-body"></div>
<div class="modal-footer"></div>
</div>
</div>
</div>
</code></pre>
<p>It shows modal dialog something like this, basically, it puts scroll bar around entire <code>modal-dialog</code> and not <code>modal-body</code> that contains the content I am trying to display.</p>
<p>The image looks something like this:</p>
<p><a href="https://i.stack.imgur.com/M41N2.png" rel="noreferrer"><img src="https://i.stack.imgur.com/M41N2.png" alt="enter image description here"></a></p>
<p>How do I get a scroll bar around <code>modal-body</code> only?</p>
<p>I have tried assigning <code>style="overflow-y: scroll; max-height:85%; margin-top: 50px; margin-bottom:50px;"</code> to <code>modal-body</code> but it didn't work.</p> | <p>You have to set the <code>height</code> of the <code>.modal-body</code> in and give it <code>overflow-y: auto</code>. Also reset <code>.modal-dialog</code> overflow value to <code>initial</code>.</p>
<p>See the working sample:</p>
<p><a href="http://www.bootply.com/T0yF2ZNTUd" rel="noreferrer">http://www.bootply.com/T0yF2ZNTUd</a></p>
<pre><code>.modal{
display: block !important; /* I added this to see the modal, you don't need this */
}
/* Important part */
.modal-dialog{
overflow-y: initial !important
}
.modal-body{
height: 80vh;
overflow-y: auto;
}
</code></pre> | {
"question_id": 25874001,
"question_date": "2014-09-16T16:30:56.057Z",
"question_score": 214,
"tags": "css|twitter-bootstrap",
"answer_id": 25874635,
"answer_date": "2014-09-16T17:06:59.020Z",
"answer_score": 387
} |
Please answer the following Stack Overflow question:
Title: Find element's index in pandas Series
<p>I know this is a very basic question but for some reason I can't find an answer. How can I get the index of certain element of a Series in python pandas? (first occurrence would suffice)</p>
<p>I.e., I'd like something like:</p>
<pre><code>import pandas as pd
myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
print myseries.find(7) # should output 3
</code></pre>
<p>Certainly, it is possible to define such a method with a loop:</p>
<pre><code>def find(s, el):
for i in s.index:
if s[i] == el:
return i
return None
print find(myseries, 7)
</code></pre>
<p>but I assume there should be a better way. Is there?</p> | <pre><code>>>> myseries[myseries == 7]
3 7
dtype: int64
>>> myseries[myseries == 7].index[0]
3
</code></pre>
<p>Though I admit that there should be a better way to do that, but this at least avoids iterating and looping through the object and moves it to the C level.</p> | {
"question_id": 18327624,
"question_date": "2013-08-20T05:33:54.513Z",
"question_score": 214,
"tags": "python|pandas",
"answer_id": 18327852,
"answer_date": "2013-08-20T05:52:43.623Z",
"answer_score": 260
} |
Please answer the following Stack Overflow question:
Title: Convert php array to Javascript
<p>How can I convert a PHP array in a format like this</p>
<pre><code>Array
(
[0] => 001-1234567
[1] => 1234567
[2] => 12345678
[3] => 12345678
[4] => 12345678
[5] => AP1W3242
[6] => AP7X1234
[7] => AS1234
[8] => MH9Z2324
[9] => MX1234
[10] => TN1A3242
[11] => ZZ1234
)
</code></pre>
<p>to a Javascript array in the format below?</p>
<pre><code>var cities = [
"Aberdeen",
"Ada",
"Adamsville",
"Addyston",
"Adelphi",
"Adena",
"Adrian",
"Akron",
"Albany"
];
</code></pre> | <p><strong><a href="https://stackoverflow.com/a/5619038/367456">Spudley's answer is fine</a>.</strong></p>
<blockquote>
<p><strong>Security Notice:</strong> <em>The following should not be necessary any longer for you</em></p>
</blockquote>
<p>If you don't have PHP 5.2 you can use something like this:</p>
<pre><code>function js_str($s)
{
return '"' . addcslashes($s, "\0..\37\"\\") . '"';
}
function js_array($array)
{
$temp = array_map('js_str', $array);
return '[' . implode(',', $temp) . ']';
}
echo 'var cities = ', js_array($php_cities_array), ';';
</code></pre> | {
"question_id": 5618925,
"question_date": "2011-04-11T08:54:20.780Z",
"question_score": 214,
"tags": "php|javascript|arrays",
"answer_id": 5619163,
"answer_date": "2011-04-11T09:18:01.940Z",
"answer_score": 65
} |
Please answer the following Stack Overflow question:
Title: Resource interpreted as Document but transferred with MIME type application/zip
<p>With Chrome 12.0.742.112, if I redirect with the following headers:</p>
<pre><code>HTTP/1.1 302 Found
Location: http://0.0.0.0:3000/files/download.zip
Content-Type: text/html; charset=utf-8
Cache-Control: no-cache
X-Ua-Compatible: IE=Edge
X-Runtime: 0.157964
Content-Length: 0
Server: WEBrick/1.3.1 (Ruby/1.9.2/2011-02-18)
Date: Tue, 05 Jul 2011 18:42:25 GMT
Connection: Keep-Alive
</code></pre>
<p>Which if followed returns the following header:</p>
<pre><code>HTTP/1.1 200 OK
Last-Modified: Tue, 05 Jul 2011 18:18:30 GMT
Content-Type: application/zip
Content-Length: 150014
Server: WEBrick/1.3.1 (Ruby/1.9.2/2011-02-18)
Date: Tue, 05 Jul 2011 18:44:47 GMT
Connection: Keep-Alive
</code></pre>
<p>Chrome will not redirect, nor change the previous page, it'll just report the following warning in the console:</p>
<blockquote>
<p>Resource interpreted as Document but transferred with MIME type application/zip.</p>
</blockquote>
<p>The process works correctly in Firefox, and also works fine in Chrome if I open a new tab and go directly to <code>http://0.0.0.0:3000/files/download.zip</code>. Am I doing something wrong, or is this a bug/quirk of Chrome?</p> | <p>I've fixed this…by simply opening a new tab.</p>
<p>Why it wasn't working I'm not entirely sure, but it could have something to do with how Chrome deals with multiple downloads on a page, perhaps it thought they were spam and just ignored them.</p> | {
"question_id": 6587393,
"question_date": "2011-07-05T18:47:20.037Z",
"question_score": 214,
"tags": "javascript|google-chrome",
"answer_id": 6587821,
"answer_date": "2011-07-05T19:26:31.610Z",
"answer_score": 24
} |
Please answer the following Stack Overflow question:
Title: How can I use a DLL file from Python?
<p>What is the easiest way to use a <code>DLL</code> file from within <code>Python</code>?</p>
<p>Specifically, how can this be done <em>without</em> writing any additional wrapper <code>C++</code> code to expose the functionality to <code>Python</code>?</p>
<p>Native <code>Python</code> functionality is strongly preferred over using a third-party library.</p> | <p>For ease of use, <a href="http://docs.python.org/library/ctypes.html" rel="noreferrer">ctypes</a> is the way to go.</p>
<p>The following example of ctypes is from actual code I've written (in Python 2.5). This has been, by far, the easiest way I've found for doing what you ask.</p>
<pre><code>import ctypes
# Load DLL into memory.
hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll")
# Set up prototype and parameters for the desired function call.
# HLLAPI
hllApiProto = ctypes.WINFUNCTYPE (
ctypes.c_int, # Return type.
ctypes.c_void_p, # Parameters 1 ...
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p) # ... thru 4.
hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0),
# Actually map the call ("HLLAPI(...)") to a Python name.
hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams)
# This is how you can actually call the DLL function.
# Set up the variables and call the Python name with them.
p1 = ctypes.c_int (1)
p2 = ctypes.c_char_p (sessionVar)
p3 = ctypes.c_int (1)
p4 = ctypes.c_int (0)
hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))
</code></pre>
<p>The <code>ctypes</code> stuff has all the C-type data types (<code>int</code>, <code>char</code>, <code>short</code>, <code>void*</code>, and so on) and can pass by value or reference. It can also return specific data types although my example doesn't do that (the HLL API returns values by modifying a variable passed by reference).</p>
<hr>
<p>In terms of the specific example shown above, IBM's EHLLAPI is a fairly consistent interface.</p>
<p>All calls pass four void pointers (EHLLAPI sends the return code back through the fourth parameter, a pointer to an <code>int</code> so, while I specify <code>int</code> as the return type, I can safely ignore it) as per IBM's documentation <a href="http://publib.boulder.ibm.com/infocenter/pcomhelp/v5r9/index.jsp?topic=/com.ibm.pcomm.doc/books/html/emulator_programming08.htm" rel="noreferrer">here</a>. In other words, the C variant of the function would be:</p>
<pre><code>int hllApi (void *p1, void *p2, void *p3, void *p4)
</code></pre>
<p>This makes for a single, simple <code>ctypes</code> function able to do anything the EHLLAPI library provides, but it's likely that other libraries will need a separate <code>ctypes</code> function set up per library function.</p>
<p>The return value from <code>WINFUNCTYPE</code> is a function prototype but you still have to set up more parameter information (over and above the types). Each tuple in <code>hllApiParams</code> has a parameter "direction" (1 = input, 2 = output and so on), a parameter name and a default value - see the <code>ctypes</code> doco for details</p>
<p>Once you have the prototype and parameter information, you can create a Python "callable" <code>hllApi</code> with which to call the function. You simply create the needed variable (<code>p1</code> through <code>p4</code> in my case) and call the function with them.</p> | {
"question_id": 252417,
"question_date": "2008-10-31T02:01:48.157Z",
"question_score": 214,
"tags": "python|dll",
"answer_id": 252473,
"answer_date": "2008-10-31T02:43:41.100Z",
"answer_score": 175
} |
Please answer the following Stack Overflow question:
Title: How do I force a DIV block to extend to the bottom of a page even if it has no content?
<p>In the markup shown below, I'm trying to get the content div to stretch all the way to the bottom of the page but it's only stretching if there's content to display. The reason I want to do this is so the vertical border still appears down the page even if there isn't any content to display.</p>
<p>Here is my <strong>DEMO</strong>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
font-family: Trebuchet MS, Verdana, MS Sans Serif;
font-size:0.9em;
margin:0;
padding:0;
}
div#header {
width: 100%;
height: 100px;
}
#header a {
background-position: 100px 30px;
background: transparent url(site-style-images/sitelogo.jpg) no-repeat fixed 100px 30px;
height: 80px;
display: block;
}
#header, #menuwrapper {
background-repeat: repeat;
background-image: url(site-style-images/darkblue_background_color.jpg);
}
#menu #menuwrapper {
height:25px;
}
div#menuwrapper {
width:100%
}
#menu, #content {
width:1024px;
margin: 0 auto;
}
div#menu {
height: 25px;
background-color:#50657a;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="form1">
<div id="header">
<a title="Home" href="index.html" />
</div>
<div id="menuwrapper">
<div id="menu">
</div>
</div>
<div id="content">
</div>
</form></code></pre>
</div>
</div>
</p> | <p>Your problem is not that the div is not at 100% height, but that the container around it is not.This will help in the browser I suspect you are using:</p>
<pre><code>html,body { height:100%; }
</code></pre>
<p>You may need to adjust padding and margins as well, but this will get you 90% of the way there.If you need to make it work with all browsers you will have to mess around with it a bit.</p>
<p>This site has some excellent examples:</p>
<p><a href="http://www.brunildo.org/test/html_body_0.html" rel="noreferrer">http://www.brunildo.org/test/html_body_0.html</a><br>
<a href="http://www.brunildo.org/test/html_body_11b.html" rel="noreferrer">http://www.brunildo.org/test/html_body_11b.html</a><br>
<a href="http://www.brunildo.org/test/index.html" rel="noreferrer">http://www.brunildo.org/test/index.html</a><br></p>
<p>I also recommend going to <a href="http://quirksmode.org/" rel="noreferrer">http://quirksmode.org/</a></p> | {
"question_id": 147528,
"question_date": "2008-09-29T04:40:24.290Z",
"question_score": 214,
"tags": "css|html|border",
"answer_id": 579123,
"answer_date": "2009-02-23T20:09:13.557Z",
"answer_score": 120
} |
Please answer the following Stack Overflow question:
Title: QLabel: set color of text and background
<p>How do I set color of text and background of a <code>QLabel</code> ?</p> | <p>The best and recommended way is to use Qt Style Sheet. Docs: <a href="http://doc.qt.io/qt-5/stylesheet.html" rel="noreferrer">Qt 5 Style Sheet</a>, <a href="https://doc.qt.io/qt-6/stylesheet.html" rel="noreferrer">Qt 6 Style Sheet</a>.</p>
<p>To change the text color and background color of a <code>QLabel</code>, here is what I would do :</p>
<pre><code>QLabel* pLabel = new QLabel;
pLabel->setStyleSheet("QLabel { background-color : red; color : blue; }");
</code></pre>
<p>You could also avoid using Qt Style Sheets and change the <code>QPalette</code> colors of your <code>QLabel</code>, but you might get different results on different platforms and/or styles.</p>
<p>As Qt documentation states :</p>
<blockquote>
<p>Using a QPalette isn't guaranteed to work for all styles, because style authors are restricted by the different platforms' guidelines and by the native theme engine.</p>
</blockquote>
<p>But you could do something like this :</p>
<pre><code> QPalette palette = ui->pLabel->palette();
palette.setColor(ui->pLabel->backgroundRole(), Qt::yellow);
palette.setColor(ui->pLabel->foregroundRole(), Qt::yellow);
ui->pLabel->setPalette(palette);
</code></pre>
<p>But as I said, I strongly suggest not to use the palette and go for Qt Style Sheet.</p> | {
"question_id": 2749798,
"question_date": "2010-05-01T11:57:30.423Z",
"question_score": 214,
"tags": "qt|qt4|qlabel",
"answer_id": 2756376,
"answer_date": "2010-05-03T06:07:37.397Z",
"answer_score": 314
} |
Please answer the following Stack Overflow question:
Title: Resource interpreted as stylesheet but transferred with MIME type text/html (seems not related with web server)
<p>I have this problem. Chrome continues to return this error </p>
<blockquote>
<p>Resource interpreted as stylesheet but transferred with MIME type text/html</p>
</blockquote>
<p>The files affected by this error are just the Style, chosen and jquery-gentleselect (other CSS files that are imported in the index in the same way work well and without error). I've already checked my MIME type and text/css is already on CSS.</p>
<p>Honestly I'd like to start by understanding the problem (a thing that seems I cannot do alone).</p> | <blockquote>
<p>i'd like to start by understanding the problem</p>
</blockquote>
<p>Browsers make HTTP requests to servers. The server then makes an HTTP response.</p>
<p>Both requests and responses consist of a bunch of headers and a (sometimes optional) body with some content in it.</p>
<p>If there is a body, then one of the headers is the <code>Content-Type</code> which describes what the body is (is it an HTML document? An image? The contents of a form submission? etc).</p>
<p>When you ask for your stylesheet, your server is telling the browser that it is an HTML document (<code>Content-Type: text/html</code>) instead of a stylesheet (<code>Content-Type: text/css</code>).</p>
<blockquote>
<p>I've already checked my myme.type and text/css is already on css.</p>
</blockquote>
<p>Then something else about your server is making that stylesheet come with the wrong content type.</p>
<p>Use the Net tab of your browser's developer tools to examine the request and the response.</p> | {
"question_id": 22631158,
"question_date": "2014-03-25T10:04:48.863Z",
"question_score": 214,
"tags": "html|css|google-chrome",
"answer_id": 22631253,
"answer_date": "2014-03-25T10:07:58.143Z",
"answer_score": 107
} |
Please answer the following Stack Overflow question:
Title: What's the difference between Visual Studio Community and other, paid versions?
<p>What's missing in Visual Studio Community 2015? They say it's full-featured and <em>free</em>, but if that's the case, then why do/will they still sell Visual Studio Ultimate 2015 or Visual Studio Enterprise 2015 for 6 grand?</p>
<p>Something is missing in the Community preview, right? And why is it called 'Community'? My code won't be synced across your devices like the new Windows 10 update system is, will it? (Kind of joking about that last part, and kind of not, too).</p> | <p>Check the following: <a href="https://www.visualstudio.com/vs/compare/" rel="noreferrer">https://www.visualstudio.com/vs/compare/</a>
Visual studio community is free version for students and other academics, individual developers, open-source projects, and small non-enterprise teams (see "Usage" section at bottom of linked page). While VSUltimate is for companies. You also get more things with paid versions!</p> | {
"question_id": 30285135,
"question_date": "2015-05-17T08:59:41.167Z",
"question_score": 214,
"tags": "visual-studio",
"answer_id": 30285184,
"answer_date": "2015-05-17T09:05:17.320Z",
"answer_score": 102
} |
Please answer the following Stack Overflow question:
Title: How to change default Anaconda python environment
<p>I've installed Anaconda and created two extra environments: py3k (which holds Python 3.3) and py34 (which holds Python 3.4). Besides those, I have a default environment named 'root' which the Anaconda installer created by default and which holds Python 2.7. This last one is the default, whenever I launch 'ipython' from the terminal it gives me version 2.7. In order to work with Python 3.4, I need to issue the commands (in the shell)</p>
<pre><code>source activate py34
ipython
</code></pre>
<p>which change the default environment to Python 3.4. This works fine, but it's annoying since most of the time I work on Python 3.4, instead of Python 2.7 (which I hold for teaching purposes, it's a rather long story). Anyway, I'll like to know how to change the default environment to Python 3.4, bearing in mind that I don't want to reinstall everything from scratch. </p> | <p>If you just want to <strong>temporarily</strong> change to another environment, use</p>
<pre><code>source activate environment-name
</code></pre>
<p>ETA: This may be deprecated. I believe the current correct command is:</p>
<pre><code>source conda activate environment-name
</code></pre>
<p>(you can create <code>environment-name</code> with <code>conda create</code>)</p>
<hr />
<p>To change <strong>permanently</strong>, there is no method except creating a startup script that runs the above code.</p>
<hr />
<p>Typically it's best to just create new environments. However, if you really want to <strong>change the Python version</strong> in the default environment, you can do so as follows:</p>
<p>First, make sure you have the latest version of conda by running</p>
<pre><code>conda update conda
</code></pre>
<p>Then run</p>
<pre><code>conda install python=3.5
</code></pre>
<p>This will attempt to update all your packages in your root environment to Python 3 versions. If it is not possible (e.g., because some package is not built for Python 3.5), it will give you an error message indicating which package(s) caused the issue.</p>
<p>If you installed packages with pip, you'll have to reinstall them.</p> | {
"question_id": 28436769,
"question_date": "2015-02-10T16:31:05.337Z",
"question_score": 214,
"tags": "python|anaconda|conda",
"answer_id": 28460907,
"answer_date": "2015-02-11T17:44:45.990Z",
"answer_score": 103
} |
Please answer the following Stack Overflow question:
Title: How can I output a UTF-8 CSV in PHP that Excel will read properly?
<p>I've got this very simple thing that just outputs some stuff in CSV format, but it's got to be UTF-8. I open this file in TextEdit or TextMate or Dreamweaver and it displays UTF-8 characters properly, but if I open it in Excel it's doing this silly íÄ kind of thing instead. Here's what I've got at the head of my document:</p>
<pre><code>header("content-type:application/csv;charset=UTF-8");
header("Content-Disposition:attachment;filename=\"CHS.csv\"");
</code></pre>
<p>This all seems to have the desired effect except Excel (Mac, 2008) doesn't want to import it properly. There's no options in Excel for me to "open as UTF-8" or anything, so … I'm getting a little annoyed.</p>
<p>I can't seem to find any clear solutions to this anywhere, despite a lot of people having the same problem. The thing I see the most is to include the BOM, but I can't exactly figure out how to do that. As you can see above I'm just <code>echo</code>ing this data, I'm not writing any file. I can do that if I need to, I'm just not because there doesn't seem like a need for it at this point. Any help?</p>
<p>Update: I tried echoing the BOM as <code>echo pack("CCC", 0xef, 0xbb, 0xbf);</code> which I just pulled from a site that was trying to detect the BOM. But Excel just appends those three characters to the very first cell when it imports, and still messes up the special characters.</p> | <p>To quote <a href="http://answers.microsoft.com/en-us/mac/forum/macoffice2011-macexcel/mac-excel-converts-utf-8-characters-to-underlines/7c4cdaa7-bfa3-41a2-8482-554ae235227b?msgId=c8295574-a053-48a6-b419-51523ce2a247" rel="noreferrer">a Microsoft support engineer</a>,</p>
<blockquote>
<p>Excel for Mac does not currently support UTF-8</p>
</blockquote>
<p><strong>Update, 2017</strong>: This is true of all versions of Microsoft Excel for Mac before <em>Office 2016</em>. Newer versions (from Office 365) do now support UTF-8.</p>
<p>In order to output UTF-8 content that Excel both on Windows and OS X will be able to successfully read, you will need to do two things:</p>
<ol>
<li><p>Make sure that you convert your UTF-8 CSV text to UTF-16LE</p>
<pre><code>mb_convert_encoding($csv, 'UTF-16LE', 'UTF-8');
</code></pre></li>
<li><p>Make sure that you add the <a href="https://en.wikipedia.org/wiki/Byte_order_mark#UTF-16" rel="noreferrer">UTF-16LE byte order mark</a> to the start of the file</p>
<pre><code>chr(255) . chr(254)
</code></pre></li>
</ol>
<p>The next problem that appears only with Excel on OS X (but <em>not</em> Windows) will be when viewing a CSV file with comma separated values, Excel will render rows only with one row and all of the text along with the commas in the first row.</p>
<p>The way to avoid this is to use tabs as your separated value.</p>
<p>I used <a href="http://php.net/manual/en/function.fputcsv.php#84783" rel="noreferrer">this function from the PHP comments</a> (using tabs "\t" instead of commas) and it worked perfectly on OS X and Windows Excel.</p>
<p>Note that to fix an issue with an empty column as the end of a row, that I did have to change the line of code that says:</p>
<pre><code> $field_cnt = count($fields);
</code></pre>
<p>to</p>
<pre><code> $field_cnt = count($fields)-1;
</code></pre>
<p>As some of the other comments on this page say, other spreadsheet apps like OpenOffice Calc, Apple's own Numbers and Google Doc's Spreadsheet have no issues with UTF-8 files with commas.</p>
<p>See <a href="https://stackoverflow.com/q/6588068/2143004">the table in this question</a> for what works and doesn't work for Unicode CSV files in Excel</p>
<hr>
<p>As a side note, I might add that if you are using <a href="//getcomposer.org" rel="noreferrer">Composer</a>, you should have a look at adding <a href="http://csv.thephpleague.com/" rel="noreferrer"><code>League\Csv</code></a> to your requires. <code>League\Csv</code> has <a href="http://csv.thephpleague.com/examples/" rel="noreferrer">a really nice API for building CSV files</a>.</p>
<p>To use <code>League\Csv</code> with this method of creating CSV files, check out <a href="https://github.com/thephpleague/csv/blob/8.2.3/examples/bom_excel_macos.php" rel="noreferrer">this example</a></p> | {
"question_id": 4348802,
"question_date": "2010-12-03T18:49:11.333Z",
"question_score": 214,
"tags": "php|csv|utf-8|byte-order-mark",
"answer_id": 16766198,
"answer_date": "2013-05-27T04:14:33.313Z",
"answer_score": 147
} |
Please answer the following Stack Overflow question:
Title: Generating random number between 1 and 10 in Bash Shell Script
<p>How would I generate an inclusive random number between 1 to 10 in Bash Shell Script?</p>
<p>Would it be <code>$(RANDOM 1+10)</code>?</p> | <pre><code>$(( ( RANDOM % 10 ) + 1 ))
</code></pre>
<p><strong>EDIT.</strong> Changed brackets into parenthesis according to the comment.
<a href="http://web.archive.org/web/20150206070451/http://islandlinux.org/howto/generate-random-numbers-bash-scripting">http://web.archive.org/web/20150206070451/http://islandlinux.org/howto/generate-random-numbers-bash-scripting</a></p> | {
"question_id": 8988824,
"question_date": "2012-01-24T14:49:05.223Z",
"question_score": 214,
"tags": "bash",
"answer_id": 8988890,
"answer_date": "2012-01-24T14:53:04.083Z",
"answer_score": 364
} |
Please answer the following Stack Overflow question:
Title: How to get an MD5 checksum in PowerShell
<p>I would like to calculate an <a href="http://en.wikipedia.org/wiki/MD5">MD5</a> checksum of some content. How do I do this in PowerShell?</p> | <p>Starting in PowerShell version 4, this is easy to do for files out of the box with the <a href="https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Get-FileHash?view=powershell-4.0" rel="noreferrer"><code>Get-FileHash</code></a> cmdlet:</p>
<pre><code>Get-FileHash <filepath> -Algorithm MD5
</code></pre>
<p>This is certainly preferable since it avoids the problems the solution for older PowerShell offers as identified in the comments (uses a stream, closes it, and supports large files).</p>
<p>If the content is a string:</p>
<pre><code>$someString = "Hello, World!"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$utf8 = New-Object -TypeName System.Text.UTF8Encoding
$hash = [System.BitConverter]::ToString($md5.ComputeHash($utf8.GetBytes($someString)))
</code></pre>
<hr />
<p><strong>For older PowerShell version</strong></p>
<p>If the content is a file:</p>
<pre><code>$someFilePath = "C:\foo.txt"
$md5 = New-Object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
$hash = [System.BitConverter]::ToString($md5.ComputeHash([System.IO.File]::ReadAllBytes($someFilePath)))
</code></pre> | {
"question_id": 10521061,
"question_date": "2012-05-09T17:24:26.913Z",
"question_score": 214,
"tags": "powershell|powershell-2.0",
"answer_id": 10521162,
"answer_date": "2012-05-09T17:32:52.043Z",
"answer_score": 389
} |
Please answer the following Stack Overflow question:
Title: npm not working - "read ECONNRESET"
<p>I'm having a problem with npm, I cant install anything. Here is the error messages:</p>
<pre><code>C:\Windows\system32>npm install -g yo
npm http GET https://registry.npmjs.org/yo
npm http GET https://registry.npmjs.org/yo
npm http GET https://registry.npmjs.org/yo
npm ERR! network read ECONNRESET
npm ERR! network This is most likely not a problem with npm itself
npm ERR! network and is related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settin
gs.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly. See: 'npm help config'
npm ERR! System Windows_NT 6.2.9200
npm ERR! command "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nod
ejs\\node_modules\\npm\\bin\\npm-cli.js" "install" "-g" "yo"
npm ERR! cwd C:\Windows\system32
npm ERR! node -v v0.10.17
npm ERR! npm -v 1.3.8
npm ERR! syscall read
npm ERR! code ECONNRESET
npm ERR! errno ECONNRESET
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! C:\Windows\system32\npm-debug.log
npm ERR! not ok code 0
</code></pre>
<p>Any idea why is this? Here are my network settings and it seems I dont have any proxy configured. I also disabled all the firewalls.</p>
<p><img src="https://i.stack.imgur.com/ujoSG.png" alt="enter image description here"></p> | <p>use </p>
<pre><code>npm config set registry http://registry.npmjs.org/
</code></pre>
<p>so that npm requests for <code>http</code> url instead of <code>https</code>.</p>
<p>and then try the same <code>npm install</code> command</p> | {
"question_id": 18419144,
"question_date": "2013-08-24T13:34:03.603Z",
"question_score": 214,
"tags": "node.js|npm",
"answer_id": 18428563,
"answer_date": "2013-08-25T11:37:07.970Z",
"answer_score": 410
} |
Please answer the following Stack Overflow question:
Title: Is Java's assertEquals method reliable?
<p>I know that <code>==</code> has some issues when comparing two <code>Strings</code>. It seems that <code>String.equals()</code> is a better approach. Well, I'm doing JUnit testing and my inclination is to use <code>assertEquals(str1, str2)</code>. Is this a reliable way to assert two Strings contain the same content? I would use <code>assertTrue(str1.equals(str2))</code>, but then you don't get the benefit of seeing what the expected and actual values are on failure.</p>
<p>On a related note, does anyone have a link to a page or thread that plainly explains the problems with <code>str1 == str2</code>?</p> | <p>You should <strong>always</strong> use <code>.equals()</code> when comparing <code>Strings</code> in Java.</p>
<p>JUnit calls the <code>.equals()</code> method to determine equality in the method <code>assertEquals(Object o1, Object o2)</code>.</p>
<p>So, you are definitely safe using <code>assertEquals(string1, string2)</code>. (Because <code>String</code>s are <code>Object</code>s)</p>
<p><a href="https://stackoverflow.com/questions/1111296/when-s-is-false-but-equals-s-is-true">Here is a link to a great Stackoverflow question</a> regarding some of the differences between <code>==</code> and <code>.equals()</code>.</p> | {
"question_id": 1201927,
"question_date": "2009-07-29T17:47:34.880Z",
"question_score": 214,
"tags": "java|string|junit|junit4",
"answer_id": 1201944,
"answer_date": "2009-07-29T17:51:30.317Z",
"answer_score": 295
} |
Please answer the following Stack Overflow question:
Title: PHP function to make slug (URL string)
<p>I want to have a function to create slugs from Unicode strings, e.g. <code>gen_slug('Andrés Cortez')</code> should return <code>andres-cortez</code>. How should I do that?</p> | <p>Instead of a lengthy replace, try this one:</p>
<pre><code>public static function slugify($text, string $divider = '-')
{
// replace non letter or digits by divider
$text = preg_replace('~[^\pL\d]+~u', $divider, $text);
// transliterate
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
// trim
$text = trim($text, $divider);
// remove duplicate divider
$text = preg_replace('~-+~', $divider, $text);
// lowercase
$text = strtolower($text);
if (empty($text)) {
return 'n-a';
}
return $text;
}
</code></pre>
<p>This was based off the one in Symfony's Jobeet tutorial.</p> | {
"question_id": 2955251,
"question_date": "2010-06-02T05:41:17.310Z",
"question_score": 214,
"tags": "php|internationalization|slug",
"answer_id": 2955878,
"answer_date": "2010-06-02T07:57:06.477Z",
"answer_score": 542
} |
Please answer the following Stack Overflow question:
Title: One line if statement not working
<pre><code><%if @item.rigged %>Yes<%else%>No<%end%>
</code></pre>
<p>I was thinking of something like this?</p>
<pre><code>if @item.rigged ? "Yes" : "No"
</code></pre>
<p>But it doesn't work. Ruby has the <code>||=</code> but I"m not even sure how to use that thing. </p> | <p>Remove <code>if</code> from <code>if @item.rigged ? "Yes" : "No"</code> </p>
<p>Ternary operator has form <code>condition ? if_true : if_false</code></p> | {
"question_id": 3827874,
"question_date": "2010-09-30T05:00:08.577Z",
"question_score": 214,
"tags": "ruby",
"answer_id": 3827879,
"answer_date": "2010-09-30T05:01:04.100Z",
"answer_score": 424
} |
Please answer the following Stack Overflow question:
Title: How can you float: right in React Native?
<p>I have an element that I want to float right, for example</p>
<pre><code><View style={{width: 300}}>
<Text style={{backgroundColor: "#DDD"}}>Hello</Text>
</View>
</code></pre>
<p>How can the <code>Text</code> be floated / aligned to the right? Also, why does the <code>Text</code> take up the full space of the <code>View</code>, instead of just the space for "Hello"?</p> | <blockquote>
<p>why does the Text take up the full space of the View, instead of just the space for "Hello"?</p>
</blockquote>
<p>Because the <code>View</code> is a flex container and by default has <a href="http://facebook.github.io/react-native/docs/layout-props.html#flexdirection" rel="noreferrer"><code>flexDirection: 'column'</code></a> and <a href="http://facebook.github.io/react-native/docs/layout-props.html#alignitems" rel="noreferrer"><code>alignItems: 'stretch'</code></a>, which means that its children should be stretched out to fill its width.</p>
<p>(Note, per <a href="http://facebook.github.io/react-native/docs/layout-props.html#display" rel="noreferrer">the docs</a>, that <em>all</em> components in React Native are <code>display: 'flex'</code> by default and that <code>display: 'inline'</code> does not exist at all. In this way, the default behaviour of a <code>Text</code> within a <code>View</code> in React Native differs from the default behaviour of <code>span</code> within a <code>div</code> on the web; in the latter case, the span would <em>not</em> fill the width of the <code>div</code> because a <code>span</code> is an inline element by default. There is no such concept in React Native.)</p>
<blockquote>
<p>How can the Text be floated / aligned to the right?</p>
</blockquote>
<p>The <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/float" rel="noreferrer"><code>float</code></a> property doesn't exist in React Native, but there are <em>loads</em> of options available to you (with slightly different behaviours) that will let you right-align your text. Here are the ones I can think of:</p>
<h3>1. Use <a href="https://facebook.github.io/react-native/docs/text-style-props.html#textalign" rel="noreferrer"><code>textAlign: 'right'</code></a> on the <code>Text</code> element</h3>
<pre><code><View>
<Text style={{textAlign: 'right'}}>Hello, World!</Text>
</View>
</code></pre>
<p>(This approach doesn't change the fact that the <code>Text</code> fills the entire width of the <code>View</code>; it just right-aligns the text within the <code>Text</code>.)</p>
<h3>2. Use <a href="https://facebook.github.io/react-native/docs/layout-props.html#alignself" rel="noreferrer"><code>alignSelf: 'flex-end'</code></a> on the <code>Text</code></h3>
<pre><code><View>
<Text style={{alignSelf: 'flex-end'}}>Hello, World!</Text>
</View>
</code></pre>
<p>This shrinks the <code>Text</code> element to the size required to hold its content and puts it at the end of the cross direction (the horizontal direction, by default) of the <code>View</code>.</p>
<h3>3. Use <a href="https://facebook.github.io/react-native/docs/layout-props.html#alignitems" rel="noreferrer"><code>alignItems: 'flex-end'</code></a> on the <code>View</code></h3>
<pre><code><View style={{alignItems: 'flex-end'}}>
<Text>Hello, World!</Text>
</View>
</code></pre>
<p>This is equivalent to setting <code>alignSelf: 'flex-end'</code> on all the <code>View</code>'s children.</p>
<h3>4. Use <a href="https://facebook.github.io/react-native/docs/layout-props.html#flexdirection" rel="noreferrer"><code>flexDirection: 'row'</code></a> and <a href="https://facebook.github.io/react-native/docs/layout-props.html#justifycontent" rel="noreferrer"><code>justifyContent: 'flex-end'</code></a> on the <code>View</code></h3>
<pre><code><View style={{flexDirection: 'row', justifyContent: 'flex-end'}}>
<Text>Hello, World!</Text>
</View>
</code></pre>
<p><code>flexDirection: 'row'</code> sets the main direction of layout to be horizontal instead of vertical; <code>justifyContent</code> is just like <code>alignItems</code>, but controls alignment in the main direction instead of the cross direction.</p>
<h3>5. Use <a href="https://facebook.github.io/react-native/docs/layout-props.html#flexdirection" rel="noreferrer"><code>flexDirection: 'row'</code></a> on the <code>View</code> and <a href="https://facebook.github.io/react-native/docs/layout-props.html#marginleft" rel="noreferrer"><code>marginLeft: 'auto'</code></a> on the <code>Text</code></h3>
<pre><code><View style={{flexDirection: 'row'}}>
<Text style={{marginLeft: 'auto'}}>Hello, World!</Text>
</View>
</code></pre>
<p>This approach is demonstrated, in the context of the web and real CSS, at <a href="https://stackoverflow.com/a/34063808/1709587">https://stackoverflow.com/a/34063808/1709587</a>.</p>
<h3>6. Use <a href="https://facebook.github.io/react-native/docs/layout-props.html#position" rel="noreferrer"><code>position: 'absolute'</code></a> and <a href="https://facebook.github.io/react-native/docs/layout-props.html#right" rel="noreferrer"><code>right: 0</code></a> on the <code>Text</code>:</h3>
<pre><code><View>
<Text style={{position: 'absolute', right: 0}}>Hello, World!</Text>
</View>
</code></pre>
<p>Like in real CSS, this takes the <code>Text</code> "out of flow", meaning that its siblings will be able to overlap it and its vertical position will be at the top of the <code>View</code> by default (although you can explicitly set a distance from the top of the <code>View</code> using the <code>top</code> style property).</p>
<hr>
<p>Naturally, which of these various approaches you want to use - and whether the choice between them even matters at all - will depend upon your precise circumstances.</p> | {
"question_id": 32030050,
"question_date": "2015-08-15T22:33:13.890Z",
"question_score": 214,
"tags": "react-native",
"answer_id": 47961683,
"answer_date": "2017-12-24T15:02:10.703Z",
"answer_score": 399
} |
Please answer the following Stack Overflow question:
Title: How to sort an array of objects with jquery or javascript
<p>I have an array of objects:</p>
<pre><code>var array = [(id, name, value),(id, name, value)]; //and so on
</code></pre>
<p>How do I get the array to be sorted in ascending order of the atribute name <code>(array[i][1])</code>?</p>
<p>I've tried to do this: <code>array[i][1].sort()</code>, but that doesn't work.</p>
<p>Please help me!</p>
<p>Edit: the array can contain more than two objects! It can contain hundreds.</p>
<p><strong>Edit:</strong>
Why is this question marked as a duplicate, when it was asked 2 years before the "duplicated" question?</p> | <pre><code>//This will sort your array
function SortByName(a, b){
var aName = a.name.toLowerCase();
var bName = b.name.toLowerCase();
return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}
array.sort(SortByName);
</code></pre> | {
"question_id": 5503900,
"question_date": "2011-03-31T17:33:21.983Z",
"question_score": 214,
"tags": "javascript|jquery|sorting|multidimensional-array",
"answer_id": 5503957,
"answer_date": "2011-03-31T17:38:25.913Z",
"answer_score": 404
} |
Please answer the following Stack Overflow question:
Title: How can I parse a local JSON file from assets folder into a ListView?
<p>I'm currently developing a physics app that is supposed to show a list of formulas and even solve some of them (the only problem is the <code>ListView</code>)</p>
<p><strong>This is my main layout</strong></p>
<pre><code> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:measureWithLargestChild="false"
android:orientation="vertical"
tools:context=".CatList" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/titlebar" >
<TextView
android:id="@+id/Title1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/app_name"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ff1c00"
android:textIsSelectable="false" />
</RelativeLayout>
<ListView
android:id="@+id/listFormulas"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
</code></pre>
<p><strong>And this is my main activity</strong></p>
<pre><code>package com.wildsushii.quickphysics;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.view.Menu;
import android.widget.ListView;
public class CatList extends Activity {
public static String AssetJSONFile (String filename, Context context) throws IOException {
AssetManager manager = context.getAssets();
InputStream file = manager.open(filename);
byte[] formArray = new byte[file.available()];
file.read(formArray);
file.close();
return new String(formArray);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cat_list);
ListView categoriesL = (ListView)findViewById(R.id.listFormulas);
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
Context context = null;
try {
String jsonLocation = AssetJSONFile("formules.json", context);
JSONObject formArray = (new JSONObject()).getJSONObject("formules");
String formule = formArray.getString("formule");
String url = formArray.getString("url");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
//My problem is here!!
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.cat_list, menu);
return true;
}
}
</code></pre>
<p>I actually know I can make this without using JSON but I need more practice parsing JSON. By the way, this is the JSON</p>
<pre><code> {
"formules": [
{
"formule": "Linear Motion",
"url": "qp1"
},
{
"formule": "Constant Acceleration Motion",
"url": "qp2"
},
{
"formule": "Projectile Motion",
"url": "qp3"
},
{
"formule": "Force",
"url": "qp4"
},
{
"formule": "Work, Power, Energy",
"url": "qp5"
},
{
"formule": "Rotary Motion",
"url": "qp6"
},
{
"formule": "Harmonic Motion",
"url": "qp7"
},
{
"formule": "Gravity",
"url": "qp8"
},
{
"formule": "Lateral and Longitudinal Waves",
"url": "qp9"
},
{
"formule": "Sound Waves",
"url": "qp10"
},
{
"formule": "Electrostatics",
"url": "qp11"
},
{
"formule": "Direct Current",
"url": "qp12"
},
{
"formule": "Magnetic Field",
"url": "qp13"
},
{
"formule": "Alternating Current",
"url": "qp14"
},
{
"formule": "Thermodynamics",
"url": "qp15"
},
{
"formule": "Hydrogen Atom",
"url": "qp16"
},
{
"formule": "Optics",
"url": "qp17"
},
{
"formule": "Modern Physics",
"url": "qp18"
},
{
"formule": "Hydrostatics",
"url": "qp19"
},
{
"formule": "Astronomy",
"url": "qp20"
}
]
}
</code></pre>
<p>I have tried a lot of things and even delete the entire project to make a new one :(</p> | <p>As Faizan describes in <a href="https://stackoverflow.com/questions/13814503/reading-a-json-file-in-android/13814551#13814551">their answer here</a>:</p>
<p>First of all read the Json File from your assests file using below code.</p>
<p>and then you can simply read this string return by this function as</p>
<pre><code>public String loadJSONFromAsset() {
String json = null;
try {
InputStream is = getActivity().getAssets().open("yourfilename.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
json = new String(buffer, "UTF-8");
} catch (IOException ex) {
ex.printStackTrace();
return null;
}
return json;
}
</code></pre>
<p>and use this method like that</p>
<pre><code> try {
JSONObject obj = new JSONObject(loadJSONFromAsset());
JSONArray m_jArry = obj.getJSONArray("formules");
ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> m_li;
for (int i = 0; i < m_jArry.length(); i++) {
JSONObject jo_inside = m_jArry.getJSONObject(i);
Log.d("Details-->", jo_inside.getString("formule"));
String formula_value = jo_inside.getString("formule");
String url_value = jo_inside.getString("url");
//Add your values in your `ArrayList` as below:
m_li = new HashMap<String, String>();
m_li.put("formule", formula_value);
m_li.put("url", url_value);
formList.add(m_li);
}
} catch (JSONException e) {
e.printStackTrace();
}
</code></pre>
<p>For further details regarding JSON <a href="http://www.vogella.com/articles/AndroidJSON/article.html" rel="noreferrer">Read HERE</a></p> | {
"question_id": 19945411,
"question_date": "2013-11-13T04:38:21.627Z",
"question_score": 214,
"tags": "java|android|json|android-listview|local",
"answer_id": 19945484,
"answer_date": "2013-11-13T04:43:55.477Z",
"answer_score": 386
} |
Please answer the following Stack Overflow question:
Title: How to jump to top of browser page
<p>I'm writing a modal popup and I need the browser to jump to the top of the screen when the open modal button is pressed. Is there a way to scroll the browser to the top using jQuery?</p> | <p>You can set the <code>scrollTop</code>, like this:</p>
<pre><code>$('html,body').scrollTop(0);
</code></pre>
<p>Or if you want a little animation instead of a snap to the top:</p>
<pre><code>$('html, body').animate({ scrollTop: 0 }, 'fast');
</code></pre> | {
"question_id": 4147112,
"question_date": "2010-11-10T17:17:46.887Z",
"question_score": 214,
"tags": "javascript|jquery|css|modal-dialog",
"answer_id": 4147118,
"answer_date": "2010-11-10T17:18:28.537Z",
"answer_score": 443
} |
Please answer the following Stack Overflow question:
Title: How can I create an Array of ArrayLists?
<p>I am wanting to create an array of arraylist like below:</p>
<pre><code>ArrayList<Individual>[] group = new ArrayList<Individual>()[4];
</code></pre>
<p>But it's not compiling. How can I do this?</p> | <p>As per <a href="https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createArrays" rel="noreferrer">Oracle Documentation</a>:</p>
<blockquote>
<p>"You cannot create arrays of parameterized types"</p>
</blockquote>
<p>Instead, you could do:</p>
<pre><code>ArrayList<ArrayList<Individual>> group = new ArrayList<ArrayList<Individual>>(4);
</code></pre>
<p>As suggested by Tom Hawting - tackline, it is even better to do:</p>
<pre><code>List<List<Individual>> group = new ArrayList<List<Individual>>(4);
</code></pre> | {
"question_id": 8559092,
"question_date": "2011-12-19T09:09:00.760Z",
"question_score": 214,
"tags": "java|arrays|arraylist",
"answer_id": 8559102,
"answer_date": "2011-12-19T09:09:59.507Z",
"answer_score": 160
} |
Please answer the following Stack Overflow question:
Title: What is an illegal reflective access?
<p>There are a lot of questions about illegal reflective access in Java 9.</p>
<p>I have found plenty of discussion about working around the error messages, but I would love to know what an illegal reflective access actually is.</p>
<p>So my question is:</p>
<p>What defines an illegal reflective access and what circumstances trigger the warning?</p>
<p>I have gathered that it has something to do with the encapsulation principles that were introduced in Java 9, but I can't find an explanation of how it all hangs together, what triggers the warning, and in what scenario.</p> | <p>Apart from an understanding of the accesses amongst modules and their respective packages. I believe the crux of it lies in the <strong><a href="http://openjdk.java.net/jeps/261#Relaxed-strong-encapsulation" rel="noreferrer">Module System#Relaxed-strong-encapsulation</a></strong> and I would just cherry-pick the relevant parts of it to try and answer the question.</p>
<blockquote>
<p><strong>What defines an illegal reflective access and what circumstances
trigger the warning?</strong></p>
</blockquote>
<p>To aid in the migration to Java-9, the strong encapsulation of the modules could be relaxed.</p>
<ul>
<li><p>An implementation may provide <em>static access</em>, i.e. by compiled bytecode.</p>
</li>
<li><p>May provide a means to invoke its run-time system with one or more packages of one or more of its modules open to code in <em>all unnamed modules</em>, i.e. to code on the classpath. If the run-time system is invoked in this way, and if by doing so some invocations of the reflection APIs succeed where otherwise they would have failed.</p>
</li>
</ul>
<p>In such cases, you've actually ended up making a <em>reflective access</em> which is <em>"illegal"</em> since in a pure modular world you were not meant to do such accesses.</p>
<blockquote>
<p><strong>How it all hangs together and what triggers the warning in what
scenario?</strong></p>
</blockquote>
<p>This relaxation of the encapsulation is controlled at runtime by a new launcher option <code>--illegal-access</code> which by default in Java9 equals <code>permit</code>. The <code>permit</code> mode ensures</p>
<blockquote>
<p>The first reflective-access operation to any such package causes a
warning to be issued, but no warnings are issued after that point.
This single warning describes how to enable further warnings. This
warning cannot be suppressed.</p>
</blockquote>
<p>The modes are configurable with values <code>debug</code>(message as well as stacktrace for every such access), <code>warn</code>(message for each such access), and <code>deny</code>(disables such operations).</p>
<hr />
<p>Few things to debug and fix on applications would be:-</p>
<ul>
<li>Run it with <code>--illegal-access=deny</code> to get to know about and avoid <em>open</em>ing packages from one module to another without a module declaration including such a directive(<code>opens</code>) or explicit use of <code>--add-opens</code> VM arg.</li>
<li>Static references from compiled code to JDK-internal APIs could be identified using the <code>jdeps</code> tool with the <code>--jdk-internals</code> option</li>
</ul>
<blockquote>
<p>The warning message issued when an illegal reflective-access operation
is detected has the following form:</p>
<pre><code>WARNING: Illegal reflective access by $PERPETRATOR to $VICTIM
</code></pre>
</blockquote>
<blockquote>
<p>where:</p>
<p><code>$PERPETRATOR</code> is the fully-qualified name of the type containing the
code that invoked the reflective operation in question plus the code
source (i.e., JAR-file path), if available, and</p>
<p><code>$VICTIM</code> is a string that describes the member being accessed,
including the fully-qualified name of the enclosing type</p>
</blockquote>
<p>Questions for such a sample warning: = <a href="https://stackoverflow.com/questions/46230413/jdk9-an-illegal-reflective-access-operation-has-occurred-org-python-core-pysys">JDK9: An illegal reflective access operation has occurred. org.python.core.PySystemState</a></p>
<p>Last and an important note, while trying to ensure that you do not face such warnings and are future safe, all you need to do is ensure your modules are not making those illegal reflective accesses. :)</p> | {
"question_id": 50251798,
"question_date": "2018-05-09T11:01:45.970Z",
"question_score": 214,
"tags": "java|java-9|java-module|java-platform-module-system",
"answer_id": 50259167,
"answer_date": "2018-05-09T17:40:17.030Z",
"answer_score": 77
} |
Please answer the following Stack Overflow question:
Title: Jinja2 template variable if None Object set a default value
<p>How to make a variable in jijna2 default to "" if object is None instead of doing something like this?</p>
<pre><code> {% if p %}
{{ p.User['first_name']}}
{% else %}
NONE
{%endif %}
</code></pre>
<p>So if object p is None I want to default the values of p (first_name and last_name) to "".
Basically </p>
<pre><code>nvl(p.User[first_name'], "")
</code></pre>
<p>Error receiving:</p>
<pre><code>Error: jinja2.exceptions.UndefinedError
UndefinedError: 'None' has no attribute 'User'
</code></pre> | <p>Use the <a href="https://jinja.palletsprojects.com/en/2.11.x/templates/#none" rel="noreferrer"><code>none</code> test</a> (not to be confused with Python's <a href="https://docs.python.org/3/library/constants.html" rel="noreferrer"><code>None</code> object</a>!):</p>
<pre><code>{% if p is not none %}
{{ p.User['first_name'] }}
{% else %}
NONE
{% endif %}
</code></pre>
<p>or:</p>
<pre><code>{{ p.User['first_name'] if p is not none else 'NONE' }}
</code></pre>
<p>or if you need an empty string:</p>
<pre><code>{{ p.User['first_name'] if p is not none }}
</code></pre> | {
"question_id": 19614027,
"question_date": "2013-10-27T02:31:01.713Z",
"question_score": 214,
"tags": "jinja2",
"answer_id": 19616065,
"answer_date": "2013-10-27T08:28:01.757Z",
"answer_score": 348
} |
Please answer the following Stack Overflow question:
Title: CSS selector - element with a given child
<p>I'm looking to make a selector which will select all elements if they have a specific child element. For example, select all <code><div></code> with a child <code><span></code>.</p>
<p>Possible?</p> | <blockquote>
<p>Is it possible to select an element if it contains a specific child element?</p>
</blockquote>
<p>Unfortunately not yet.</p>
<p>The <a href="http://www.w3.org/TR/CSS2/selector.html" rel="noreferrer">CSS2</a> and <a href="http://www.w3.org/TR/2005/WD-css3-selectors-20051215/#selectors" rel="noreferrer">CSS3</a> selector specifications do not allow for any sort of parent selection.</p>
<hr />
<h3>A Note About Specification Changes</h3>
<p>This is a disclaimer about the accuracy of this post from this point onward. Parent selectors in CSS have been discussed for many years. As no consensus has been found, changes keep happening. I will attempt to keep this answer up-to-date, however be aware that <em>there may be inaccuracies due to changes in the specifications</em>.</p>
<hr />
<p>An older <a href="http://www.w3.org/TR/selectors4/" rel="noreferrer">"Selectors Level 4 Working Draft"</a> described a feature which was the ability to specify the <a href="http://www.w3.org/TR/selectors4/#subject" rel="noreferrer">"subject" of a selector</a>. <strong>This feature has been dropped and will not be available for CSS implementations</strong>.</p>
<p>The subject was going to be the element in the selector chain that would have styles applied to it.</p>
<sub>Example HTML</sub>
<pre><code><p><span>lorem</span> ipsum dolor sit amet</p>
<p>consecteture edipsing elit</p>
</code></pre>
<p>This selector would style the <code>span</code> element</p>
<pre><code>p span {
color: red;
}
</code></pre>
<p>This selector would style the <code>p</code> element</p>
<pre><code>!p span {
color: red;
}
</code></pre>
<hr />
<p>A more recent <a href="https://drafts.csswg.org/selectors-4/#relational" rel="noreferrer">"Selectors Level 4 Editor’s Draft"</a> includes "The Relational Pseudo-class: <code>:has()</code>"</p>
<p><code>:has()</code> would allow an author to select an element based on its contents. My understanding is it was chosen to provide compatibility with <a href="http://api.jquery.com/has-selector/" rel="noreferrer">jQuery's custom <code>:has()</code></a> pseudo-selector*.</p>
<p>In any event, continuing the example from above, to select the <code>p</code> element that contains a <code>span</code> one could use:</p>
<pre><code>p:has(span) {
color: red;
}
</code></pre>
<hr />
<p><sub>* This makes me wonder if jQuery had implemented selector subjects whether subjects would have remained in the specification.</sub></p> | {
"question_id": 4220327,
"question_date": "2010-11-18T22:35:48.113Z",
"question_score": 214,
"tags": "css|css-selectors",
"answer_id": 4220347,
"answer_date": "2010-11-18T22:39:03.927Z",
"answer_score": 161
} |
Please answer the following Stack Overflow question:
Title: Java switch statement: Constant expression required, but it IS constant
<p>So, I am working on this class that has a few static constants:</p>
<pre><code>public abstract class Foo {
...
public static final int BAR;
public static final int BAZ;
public static final int BAM;
...
}
</code></pre>
<p>Then, I would like a way to get a relevant string based on the constant:</p>
<pre><code>public static String lookup(int constant) {
switch (constant) {
case Foo.BAR: return "bar";
case Foo.BAZ: return "baz";
case Foo.BAM: return "bam";
default: return "unknown";
}
}
</code></pre>
<p>However, when I compile, I get a <code>constant expression required</code> error on each of the 3 case labels.</p>
<p>I understand that the compiler needs the expression to be known at compile time to compile a switch, but why isn't <code>Foo.BA_</code> constant?</p> | <blockquote>
<p>I understand that the compiler needs the expression to be known at compile time to compile a switch, but why isn't Foo.BA_ constant?</p>
</blockquote>
<p>While they are constant from the perspective of any code that executes after the fields have been initialized, they are not a <em>compile time constant</em> in the sense required by the JLS; see <a href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.28" rel="noreferrer">§15.28 Constant Expressions</a> for the specification of a <em>constant expression</em><sup>1</sup>. This refers to <a href="http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#10931" rel="noreferrer">§4.12.4 Final Variables</a> which defines a "constant variable" as follows:</p>
<blockquote>
<p>We call a variable, of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28) a constant variable. Whether a variable is a constant variable or not may have implications with respect to class initialization (§12.4.1), binary compatibility (§13.1, §13.4.9) and definite assignment (§16).</p>
</blockquote>
<p>In your example, the Foo.BA* variables do not have initializers, and hence do not qualify as "constant variables". The fix is simple; change the Foo.BA* variable declarations to have initializers that are compile-time constant expressions.</p>
<p>In other examples (where the initializers are already compile-time constant expressions), declaring the variable as <code>final</code> may be what is needed.</p>
<p>You could change your code to use an <code>enum</code> rather than <code>int</code> constants, but that brings another couple of different restrictions:</p>
<ul>
<li>You <em>must</em> include a <code>default</code> case, even if you have <code>case</code> for every known value of the <code>enum</code>; see <a href="https://stackoverflow.com/questions/5013194/why-is-default-required-for-a-switch-on-an-enum-in-this-code/5013598#5013598">Why is default required for a switch on an enum?</a></li>
<li>The <code>case</code> labels must all be explicit <code>enum</code> values, not expressions that evaluate to <code>enum</code> values.</li>
</ul>
<hr>
<p><sup>1 - The constant expression restrictions can be summarized as follows. Constant expressions a) can use primitive types and <code>String</code> only, b) allow primaries that are literals (apart from <code>null</code>) and constant variables only, c) allow constant expressions possibly parenthesised as subexpressions, d) allow operators except for assignment operators, <code>++</code>, <code>--</code> or <code>instanceof</code>, and e) allow type casts to primitive types or <code>String</code> only.</sup></p>
<p><sup>Note that this doesn't include any form of method or lambda calls, <code>new</code>, <code>.class</code>. <code>.length</code> or array subscripting. Furthermore, any use of array values, <code>enum</code> values, values of primitive wrapper types, boxing and unboxing are all excluded because of a).</sup></p> | {
"question_id": 3827393,
"question_date": "2010-09-30T03:02:44.437Z",
"question_score": 214,
"tags": "java|compile-time-constant",
"answer_id": 3827424,
"answer_date": "2010-09-30T03:11:32.373Z",
"answer_score": 181
} |
Please answer the following Stack Overflow question:
Title: missing private key in the distribution certificate on keychain
<p>I have the following problem which I could not find a solution for anywhere. Basically, we have a company developer account (not enterprise) and so in order to submit our app, I requested from our team lead to send me the distribution certificate and create and send me a distribution provisioning profile. </p>
<p>With the developer profile, everything works good, but when I installed the cert and the provisioning profile, I did not see the distribution profile on Xcode, and nor do I have a private key under the dist cert in the keychain.</p>
<p>Does anyone know how to solve this? I read in diff places that I will need to revoke the certificate and create a new one, but I can't really do that since we have a bunch of apps in the company and I can't revoke it for everyone.</p> | <p><img src="https://i.stack.imgur.com/vXRjU.png" alt="enter image description here">Ahh this is a common issue, The solution is simple:</p>
<p>Who ever created the developer credentials originally needs to go to the keychain on their computer and right click on the key(s) for private and public and export the key to a file.
Then you just download that file on your computer and open it, and it will be added to your keychain.</p>
<p>You need to have both the private key (.pem file) and the certificate for your provisioning profiles.</p> | {
"question_id": 12867878,
"question_date": "2012-10-12T22:18:50.117Z",
"question_score": 214,
"tags": "ios|iphone|xcode|keychain|codesign",
"answer_id": 12867936,
"answer_date": "2012-10-12T22:25:21.123Z",
"answer_score": 213
} |
Please answer the following Stack Overflow question:
Title: Verify a method call using Moq
<p>I am fairly new to unit testing in C# and learning to use Moq. Below is the class that I am trying to test.</p>
<pre><code>class MyClass
{
SomeClass someClass;
public MyClass(SomeClass someClass)
{
this.someClass = someClass;
}
public void MyMethod(string method)
{
method = "test"
someClass.DoSomething(method);
}
}
class Someclass
{
public DoSomething(string method)
{
// do something...
}
}
</code></pre>
<p>Below is my TestClass:</p>
<pre><code>class MyClassTest
{
[TestMethod()]
public void MyMethodTest()
{
string action="test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.SetUp(a => a.DoSomething(action));
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
mockSomeClass.Verify(v => v.DoSomething(It.IsAny<string>()));
}
}
</code></pre>
<p>I get the following exception:</p>
<pre><code>Expected invocation on the mock at least once, but was never performed
No setups configured.
No invocations performed..
</code></pre>
<p>I just want to verify if the method "MyMethod" is being called or not. Am I missing something?</p> | <p>You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.</p>
<p>You should be doing something more like this:</p>
<pre><code>class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
</code></pre>
<p>In other words, you are verifying that calling <code>MyClass#MyMethod</code>, your class will definitely call <code>SomeClass#DoSomething</code> once in that process. Note that you don't need the <code>Times</code> argument; I was just demonstrating its value.</p> | {
"question_id": 9136674,
"question_date": "2012-02-03T23:01:32.340Z",
"question_score": 214,
"tags": "c#|testing|methods|moq",
"answer_id": 9136721,
"answer_date": "2012-02-03T23:07:47.843Z",
"answer_score": 329
} |
Please answer the following Stack Overflow question:
Title: OPTION (RECOMPILE) is Always Faster; Why?
<p>I encountered an odd situation where appending <code>OPTION (RECOMPILE)</code> to my query causes it to run in half a second, while omitting it causes the query to take well over five minutes.</p>
<p>This is the case when the query is executed from Query Analyzer or from my C# program via <code>SqlCommand.ExecuteReader()</code>. Calling (or not calling) <code>DBCC FREEPROCCACHE</code> or <code>DBCC dropcleanbuffers</code> makes no difference; Query results are always returned instantaneously with <code>OPTION (RECOMPILE)</code> and greater than five minutes without it. The query is always called with the same parameters [for the sake of this test].</p>
<p>I'm using SQL Server 2008.</p>
<p>I'm fairly comfortable with writing SQL but have never used an <code>OPTION</code> command in a query before and was unfamiliar with the whole concept of plan caches until scanning the posts on this forum. My understanding from the posts is that <code>OPTION (RECOMPILE)</code> is an expensive operation. It apparently creates a new lookup strategy for the query. So why is it then, that subsequent queries that omit the <code>OPTION (RECOMPILE)</code> are so slow? Shouldn't the subsequent queries be making use of the lookup strategy that was computed on the previous call which included the recompilation hint?</p>
<p>Is it highly unusual to have a query that requires a recompilation hint on every single call?</p>
<p>Sorry for the entry-level question but I can't really make heads or tails of this.</p>
<p><strong>UPDATE: I've been asked to post the query...</strong></p>
<pre><code>select acctNo,min(date) earliestDate
from(
select acctNo,tradeDate as date
from datafeed_trans
where feedid=@feedID and feedDate=@feedDate
union
select acctNo,feedDate as date
from datafeed_money
where feedid=@feedID and feedDate=@feedDate
union
select acctNo,feedDate as date
from datafeed_jnl
where feedid=@feedID and feedDate=@feedDate
)t1
group by t1.acctNo
OPTION(RECOMPILE)
</code></pre>
<p>When running the test from Query Analyzer, I prepend the following lines:</p>
<pre><code>declare @feedID int
select @feedID=20
declare @feedDate datetime
select @feedDate='1/2/2009'
</code></pre>
<p>When calling it from my C# program, the parameters are passed in via the <code>SqlCommand.Parameters</code> property.</p>
<p>For the purposes of this discussion, you can assume that the parameters never change so we can rule out sub-optimal parameter smelling as the cause.</p> | <p>There are times that using <code>OPTION(RECOMPILE)</code> makes sense. In my experience the only time this is a viable option is when you are using dynamic SQL. Before you explore whether this makes sense in your situation I would recommend rebuilding your statistics. This can be done by running the following:</p>
<pre><code>EXEC sp_updatestats
</code></pre>
<p>And then recreating your execution plan. This will ensure that when your execution plan is created it will be using the latest information.</p>
<p>Adding <code>OPTION(RECOMPILE)</code> rebuilds the execution plan every time that your query executes. I have never heard that described as <code>creates a new lookup strategy</code> but maybe we are just using different terms for the same thing.</p>
<p>When a stored procedure is created (I suspect you are calling ad-hoc sql from .NET but <a href="https://dba.stackexchange.com/questions/123978/can-sp-executesql-be-configured-used-by-default">if you are using a parameterized query then this ends up being a stored proc call</a>) SQL Server attempts to determine the most effective execution plan for this query based on the data in your database and the parameters passed in (<a href="http://blogs.technet.com/b/mdegre/archive/2012/03/19/what-is-parameter-sniffing.aspx" rel="noreferrer">parameter sniffing</a>), and then caches this plan. This means that if you create the query where there are 10 records in your database and then execute it when there are 100,000,000 records the cached execution plan may no longer be the most effective.</p>
<p>In summary - I don't see any reason that <code>OPTION(RECOMPILE)</code> would be a benefit here. I suspect you just need to update your statistics and your execution plan. Rebuilding statistics can be an essential part of DBA work depending on your situation. If you are still having problems after updating your stats, I would suggest posting both execution plans.</p>
<p>And to answer your question - yes, I would say it is highly unusual for your best option to be recompiling the execution plan every time you execute the query.</p> | {
"question_id": 20864934,
"question_date": "2014-01-01T01:59:29.320Z",
"question_score": 214,
"tags": "sql|sql-server|sql-server-2008|compilation|query-hints",
"answer_id": 20865349,
"answer_date": "2014-01-01T03:41:03.153Z",
"answer_score": 200
} |
Please answer the following Stack Overflow question:
Title: Using the HTML5 "required" attribute for a group of checkboxes?
<p>When using the newer browsers that support HTML5 (FireFox 4 for example);<br>
and a form field has the attribute <code>required='required'</code>;<br>
and the form field is empty/blank;<br>
and the submit button is clicked;<br>
the browsers detects that the "required" field is empty and does not submit the form;<br> instead browser shows a hint asking the user to type text into the field.</p>
<p>Now, instead of a single text field, I have a <em>group of checkboxes</em>, out of which at least one should be checked/selected by the user.</p>
<p>How can I use the HTML5 <code>required</code> attribute on this group of checkboxes?
(Since only one of the checkboxes needs to be checked, I can't put the <code>required</code> attribute on each and every checkbox)</p>
<p>ps. I am using <a href="https://github.com/plataformatec/simple_form" rel="noreferrer">simple_form</a>, if that matters.</p>
<hr>
<p><strong>UPDATE</strong></p>
<p>Could the <a href="http://dev.w3.org/html5/spec-author-view/common-input-element-attributes.html#the-multiple-attribute" rel="noreferrer">HTML 5 <code>multiple</code> attribute</a> be helpful here? Has anyone use it before for doing something similar to my question?</p>
<h2>UPDATE</h2>
<p><strong>It <em>appears</em> that this feature is not supported by the HTML5 spec:</strong> <a href="http://www.w3.org/html/wg/tracker/issues/111?changelog" rel="noreferrer">ISSUE-111: What does input.@required mean for @type = checkbox?</a></p>
<p>(Issue status: <em>Issue has been marked closed without prejudice.</em>)
And <a href="http://www.w3.org/Bugs/Public/show_bug.cgi?id=9160#c1" rel="noreferrer">here is the explanation</a>.</p>
<h2>UPDATE 2</h2>
<p>It's an old question, but wanted to clarify that the original intent of the question was to be able to do the above without using Javascript - i.e. using a HTML5 way of doing it. In retrospect, I should've made the "without Javascript" more obvious.</p> | <p>Unfortunately HTML5 does not provide an out-of-the-box way to do that.</p>
<p>However, using jQuery, you can easily control if a checkbox group has at least one checked element.</p>
<p>Consider the following DOM snippet:</p>
<pre><code><div class="checkbox-group required">
<input type="checkbox" name="checkbox_name[]">
<input type="checkbox" name="checkbox_name[]">
<input type="checkbox" name="checkbox_name[]">
<input type="checkbox" name="checkbox_name[]">
</div>
</code></pre>
<p>You can use this expression:</p>
<pre><code>$('div.checkbox-group.required :checkbox:checked').length > 0
</code></pre>
<p>which returns <code>true</code> if at least one element is checked.
Based on that, you can implement your validation check.</p> | {
"question_id": 6218494,
"question_date": "2011-06-02T18:11:56.260Z",
"question_score": 214,
"tags": "forms|html|validation|checkbox",
"answer_id": 30055382,
"answer_date": "2015-05-05T14:10:01.153Z",
"answer_score": 113
} |
Please answer the following Stack Overflow question:
Title: pandas dataframe columns scaling with sklearn
<p>I have a pandas dataframe with mixed type columns, and I'd like to apply sklearn's min_max_scaler to some of the columns. Ideally, I'd like to do these transformations in place, but haven't figured out a way to do that yet. I've written the following code that works:</p>
<pre><code>import pandas as pd
import numpy as np
from sklearn import preprocessing
scaler = preprocessing.MinMaxScaler()
dfTest = pd.DataFrame({'A':[14.00,90.20,90.95,96.27,91.21],'B':[103.02,107.26,110.35,114.23,114.68], 'C':['big','small','big','small','small']})
min_max_scaler = preprocessing.MinMaxScaler()
def scaleColumns(df, cols_to_scale):
for col in cols_to_scale:
df[col] = pd.DataFrame(min_max_scaler.fit_transform(pd.DataFrame(dfTest[col])),columns=[col])
return df
dfTest
A B C
0 14.00 103.02 big
1 90.20 107.26 small
2 90.95 110.35 big
3 96.27 114.23 small
4 91.21 114.68 small
scaled_df = scaleColumns(dfTest,['A','B'])
scaled_df
A B C
0 0.000000 0.000000 big
1 0.926219 0.363636 small
2 0.935335 0.628645 big
3 1.000000 0.961407 small
4 0.938495 1.000000 small
</code></pre>
<p>I'm curious if this is the preferred/most efficient way to do this transformation. Is there a way I could use df.apply that would be better?</p>
<p>I'm also surprised I can't get the following code to work:</p>
<pre><code>bad_output = min_max_scaler.fit_transform(dfTest['A'])
</code></pre>
<p>If I pass an entire dataframe to the scaler it works:</p>
<pre><code>dfTest2 = dfTest.drop('C', axis = 1)
good_output = min_max_scaler.fit_transform(dfTest2)
good_output
</code></pre>
<p>I'm confused why passing a series to the scaler fails. In my full working code above I had hoped to just pass a series to the scaler then set the dataframe column = to the scaled series.</p> | <p>I am not sure if previous versions of <code>pandas</code> prevented this but now the following snippet works perfectly for me and produces exactly what you want without having to use <code>apply</code></p>
<pre><code>>>> import pandas as pd
>>> from sklearn.preprocessing import MinMaxScaler
>>> scaler = MinMaxScaler()
>>> dfTest = pd.DataFrame({'A':[14.00,90.20,90.95,96.27,91.21],
'B':[103.02,107.26,110.35,114.23,114.68],
'C':['big','small','big','small','small']})
>>> dfTest[['A', 'B']] = scaler.fit_transform(dfTest[['A', 'B']])
>>> dfTest
A B C
0 0.000000 0.000000 big
1 0.926219 0.363636 small
2 0.935335 0.628645 big
3 1.000000 0.961407 small
4 0.938495 1.000000 small
</code></pre> | {
"question_id": 24645153,
"question_date": "2014-07-09T03:57:55.123Z",
"question_score": 214,
"tags": "python|pandas|scikit-learn|dataframe",
"answer_id": 36475297,
"answer_date": "2016-04-07T11:48:04.410Z",
"answer_score": 322
} |
Please answer the following Stack Overflow question:
Title: SFTP in Python? (platform independent)
<p>I'm working on a simple tool that transfers files to a hard-coded location with the password also hard-coded. I'm a python novice, but thanks to ftplib, it was easy:</p>
<pre><code>import ftplib
info= ('someuser', 'password') #hard-coded
def putfile(file, site, dir, user=(), verbose=True):
"""
upload a file by ftp to a site/directory
login hard-coded, binary transfer
"""
if verbose: print 'Uploading', file
local = open(file, 'rb')
remote = ftplib.FTP(site)
remote.login(*user)
remote.cwd(dir)
remote.storbinary('STOR ' + file, local, 1024)
remote.quit()
local.close()
if verbose: print 'Upload done.'
if __name__ == '__main__':
site = 'somewhere.com' #hard-coded
dir = './uploads/' #hard-coded
import sys, getpass
putfile(sys.argv[1], site, dir, user=info)
</code></pre>
<p>The problem is that I can't find any library that supports sFTP. What's the normal way to do something like this securely? </p>
<p>Edit: Thanks to the answers here, I've gotten it working with Paramiko and this was the syntax.</p>
<pre><code>import paramiko
host = "THEHOST.com" #hard-coded
port = 22
transport = paramiko.Transport((host, port))
password = "THEPASSWORD" #hard-coded
username = "THEUSERNAME" #hard-coded
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
import sys
path = './THETARGETDIRECTORY/' + sys.argv[1] #hard-coded
localpath = sys.argv[1]
sftp.put(localpath, path)
sftp.close()
transport.close()
print 'Upload done.'
</code></pre>
<p>Thanks again!</p> | <p><a href="https://www.paramiko.org/" rel="noreferrer">Paramiko</a> supports SFTP. I've used it, and I've used Twisted. Both have their place, but you might find it easier to start with Paramiko.</p> | {
"question_id": 432385,
"question_date": "2009-01-11T04:48:19.177Z",
"question_score": 214,
"tags": "python|sftp",
"answer_id": 432403,
"answer_date": "2009-01-11T05:04:22.937Z",
"answer_score": 126
} |
Please answer the following Stack Overflow question:
Title: Multiple glibc libraries on a single host
<p>My linux (SLES-8) server currently has glibc-2.2.5-235, but I have a program which won't work on this version and requires glibc-2.3.3.</p>
<p>Is it possible to have multiple glibcs installed on the same host?</p>
<p>This is the error I get when I run my program on the old glibc:</p>
<pre><code>./myapp: /lib/i686/libc.so.6: version `GLIBC_2.3' not found (required by ./myapp)
./myapp: /lib/i686/libpthread.so.0: version `GLIBC_2.3.2' not found (required by ./myapp)
./myapp: /lib/i686/libc.so.6: version `GLIBC_2.3' not found (required by ./libxerces-c.so.27)
./myapp: /lib/ld-linux.so.2: version `GLIBC_2.3' not found (required by ./libstdc++.so.6)
./myapp: /lib/i686/libc.so.6: version `GLIBC_2.3' not found (required by ./libstdc++.so.6)
</code></pre>
<p>So I created a new directory called newglibc and copied the following files in:</p>
<pre><code>libpthread.so.0
libm.so.6
libc.so.6
ld-2.3.3.so
ld-linux.so.2 -> ld-2.3.3.so
</code></pre>
<p>and</p>
<pre><code>export LD_LIBRARY_PATH=newglibc:$LD_LIBRARY_PATH
</code></pre>
<p>But I get an error:</p>
<pre><code>./myapp: /lib/ld-linux.so.2: version `GLIBC_PRIVATE' not found (required by ./newglibc/libpthread.so.0)
./myapp: /lib/ld-linux.so.2: version `GLIBC_2.3' not found (required by libstdc++.so.6)
./myapp: /lib/ld-linux.so.2: version `GLIBC_PRIVATE' not found (required by ./newglibc/libm.so.6)
./myapp: /lib/ld-linux.so.2: version `GLIBC_2.3' not found (required by ./newglibc/libc.so.6)
./myapp: /lib/ld-linux.so.2: version `GLIBC_PRIVATE' not found (required by ./newglibc/libc.so.6)
</code></pre>
<p>So it appears that they are still linking to <code>/lib</code> and not picking up from where I put them.</p> | <p>It is very possible to have multiple versions of glibc on the same system (we do that every day).</p>
<p>However, you need to know that glibc consists of many pieces (200+ shared libraries) which all must match. One of the pieces is ld-linux.so.2, and it <em>must</em> match libc.so.6, or you'll see the errors you are seeing.</p>
<p>The absolute path to ld-linux.so.2 is hard-coded into the executable at link time, and can not be easily changed after the link is done (Update: can be done with <a href="http://nixos.org/patchelf.html" rel="noreferrer">patchelf</a>; see <a href="https://stackoverflow.com/a/44710599/50617">this answer</a> below).</p>
<p>To build an executable that will work with the new glibc, do this:</p>
<pre><code>g++ main.o -o myapp ... \
-Wl,--rpath=/path/to/newglibc \
-Wl,--dynamic-linker=/path/to/newglibc/ld-linux.so.2
</code></pre>
<p>The <code>-rpath</code> linker option will make the runtime loader search for libraries in <code>/path/to/newglibc</code> (so you wouldn't have to set <code>LD_LIBRARY_PATH</code> before running it), and the <code>-dynamic-linker</code> option will "bake" path to correct <code>ld-linux.so.2</code> into the application.</p>
<p>If you can't relink the <code>myapp</code> application (e.g. because it is a third-party binary), not all is lost, but it gets trickier. One solution is to set a proper <code>chroot</code> environment for it. Another possibility is to use <a href="http://bitwagon.com/rtldi/rtldi.html" rel="noreferrer">rtldi</a> and a <a href="http://en.wikipedia.org/wiki/Binary_editor" rel="noreferrer">binary editor</a>. Update: or you can use <a href="http://nixos.org/patchelf.html" rel="noreferrer">patchelf</a>.</p> | {
"question_id": 847179,
"question_date": "2009-05-11T08:20:37.167Z",
"question_score": 214,
"tags": "linux|gcc|glibc",
"answer_id": 851229,
"answer_date": "2009-05-12T05:10:45.170Z",
"answer_score": 285
} |
Please answer the following Stack Overflow question:
Title: PostgreSQL return result set as JSON array?
<p>I would like to have PostgreSQL return the result of a query as one JSON array. Given</p>
<pre><code>create table t (a int primary key, b text);
insert into t values (1, 'value1');
insert into t values (2, 'value2');
insert into t values (3, 'value3');
</code></pre>
<p>I would like something similar to</p>
<pre><code>[{"a":1,"b":"value1"},{"a":2,"b":"value2"},{"a":3,"b":"value3"}]
</code></pre>
<p>or </p>
<pre><code>{"a":[1,2,3], "b":["value1","value2","value3"]}
</code></pre>
<p>(actually it would be more useful to know both). I have tried some things like</p>
<pre><code>select row_to_json(row) from (select * from t) row;
select array_agg(row) from (select * from t) row;
select array_to_string(array_agg(row), '') from (select * from t) row;
</code></pre>
<p>And I feel I am close, but not there really. Should I be looking at other documentation except for <a href="http://www.postgresql.org/docs/9.3/static/functions-json.html" rel="noreferrer" title="9.15. JSON Functions and Operators">9.15. JSON Functions and Operators</a>?</p>
<p>By the way, I am not sure about my idea. Is this a usual design decision? My thinking is that I could, of course, take the result (for example) of the first of the above 3 queries and manipulate it slightly in the application before serving it to the client, but if PostgreSQL can create the final JSON object directly, it would be simpler, because I still have not included any dependency on any JSON library in my application. </p> | <h1>TL;DR</h1>
<pre><code>SELECT json_agg(t) FROM t
</code></pre>
<p>for a JSON array of objects, and </p>
<pre><code>SELECT
json_build_object(
'a', json_agg(t.a),
'b', json_agg(t.b)
)
FROM t
</code></pre>
<p>for a JSON object of arrays.</p>
<h1>List of objects</h1>
<p>This section describes how to generate a JSON array of objects, with each row being converted to a single object. The result looks like this:</p>
<pre><code>[{"a":1,"b":"value1"},{"a":2,"b":"value2"},{"a":3,"b":"value3"}]
</code></pre>
<h3>9.3 and up</h3>
<p>The <code>json_agg</code> function produces this result out of the box. It automatically figures out how to convert its input into JSON and aggregates it into an array.</p>
<pre><code>SELECT json_agg(t) FROM t
</code></pre>
<p>There is no <code>jsonb</code> (introduced in 9.4) version of <code>json_agg</code>. You can either aggregate the rows into an array and then convert them:</p>
<pre><code>SELECT to_jsonb(array_agg(t)) FROM t
</code></pre>
<p>or combine <code>json_agg</code> with a cast:</p>
<pre><code>SELECT json_agg(t)::jsonb FROM t
</code></pre>
<p>My testing suggests that aggregating them into an array first is a little faster. I suspect that this is because the cast has to parse the entire JSON result.</p>
<h3>9.2</h3>
<p>9.2 does not have the <code>json_agg</code> or <code>to_json</code> functions, so you need to use the older <code>array_to_json</code>:</p>
<pre><code>SELECT array_to_json(array_agg(t)) FROM t
</code></pre>
<p>You can optionally include a <code>row_to_json</code> call in the query:</p>
<pre><code>SELECT array_to_json(array_agg(row_to_json(t))) FROM t
</code></pre>
<p>This converts each row to a JSON object, aggregates the JSON objects as an array, and then converts the array to a JSON array.</p>
<p>I wasn't able to discern any significant performance difference between the two.</p>
<h1>Object of lists</h1>
<p>This section describes how to generate a JSON object, with each key being a column in the table and each value being an array of the values of the column. It's the result that looks like this:</p>
<pre><code>{"a":[1,2,3], "b":["value1","value2","value3"]}
</code></pre>
<h3>9.5 and up</h3>
<p>We can leverage the <code>json_build_object</code> function:</p>
<pre><code>SELECT
json_build_object(
'a', json_agg(t.a),
'b', json_agg(t.b)
)
FROM t
</code></pre>
<p>You can also aggregate the columns, creating a single row, and then convert that into an object:</p>
<pre><code>SELECT to_json(r)
FROM (
SELECT
json_agg(t.a) AS a,
json_agg(t.b) AS b
FROM t
) r
</code></pre>
<p>Note that aliasing the arrays is absolutely required to ensure that the object has the desired names.</p>
<p>Which one is clearer is a matter of opinion. If using the <code>json_build_object</code> function, I highly recommend putting one key/value pair on a line to improve readability.</p>
<p>You could also use <code>array_agg</code> in place of <code>json_agg</code>, but my testing indicates that <code>json_agg</code> is slightly faster.</p>
<p>There is no <code>jsonb</code> version of the <code>json_build_object</code> function. You can aggregate into a single row and convert:</p>
<pre><code>SELECT to_jsonb(r)
FROM (
SELECT
array_agg(t.a) AS a,
array_agg(t.b) AS b
FROM t
) r
</code></pre>
<p>Unlike the other queries for this kind of result, <code>array_agg</code> seems to be a little faster when using <code>to_jsonb</code>. I suspect this is due to overhead parsing and validating the JSON result of <code>json_agg</code>.</p>
<p>Or you can use an explicit cast:</p>
<pre><code>SELECT
json_build_object(
'a', json_agg(t.a),
'b', json_agg(t.b)
)::jsonb
FROM t
</code></pre>
<p>The <code>to_jsonb</code> version allows you to avoid the cast and is faster, according to my testing; again, I suspect this is due to overhead of parsing and validating the result.</p>
<h3>9.4 and 9.3</h3>
<p>The <code>json_build_object</code> function was new to 9.5, so you have to aggregate and convert to an object in previous versions:</p>
<pre><code>SELECT to_json(r)
FROM (
SELECT
json_agg(t.a) AS a,
json_agg(t.b) AS b
FROM t
) r
</code></pre>
<p>or</p>
<pre><code>SELECT to_jsonb(r)
FROM (
SELECT
array_agg(t.a) AS a,
array_agg(t.b) AS b
FROM t
) r
</code></pre>
<p>depending on whether you want <code>json</code> or <code>jsonb</code>.</p>
<p>(9.3 does not have <code>jsonb</code>.)</p>
<h3>9.2</h3>
<p>In 9.2, not even <code>to_json</code> exists. You must use <code>row_to_json</code>:</p>
<pre><code>SELECT row_to_json(r)
FROM (
SELECT
array_agg(t.a) AS a,
array_agg(t.b) AS b
FROM t
) r
</code></pre>
<h1>Documentation</h1>
<p>Find the documentation for the JSON functions in <a href="https://www.postgresql.org/docs/latest/functions-json.html#FUNCTIONS-JSON-TABLE" rel="noreferrer">JSON functions</a>.</p>
<p><code>json_agg</code> is on the <a href="https://www.postgresql.org/docs/11/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE" rel="noreferrer">aggregate functions</a> page.</p>
<h1>Design</h1>
<p>If performance is important, ensure you benchmark your queries against your own schema and data, rather than trust my testing.</p>
<p>Whether it's a good design or not really depends on your specific application. In terms of maintainability, I don't see any particular problem. It simplifies your app code and means there's less to maintain in that portion of the app. If PG can give you exactly the result you need out of the box, the only reason I can think of to not use it would be performance considerations. Don't reinvent the wheel and all.</p>
<h1>Nulls</h1>
<p>Aggregate functions typically give back <code>NULL</code> when they operate over zero rows. If this is a possibility, you might want to use <code>COALESCE</code> to avoid them. A couple of examples:</p>
<pre><code>SELECT COALESCE(json_agg(t), '[]'::json) FROM t
</code></pre>
<p>Or</p>
<pre><code>SELECT to_jsonb(COALESCE(array_agg(t), ARRAY[]::t[])) FROM t
</code></pre>
<p><sub>Credit to <a href="https://stackoverflow.com/users/29442/hannes-landeholm">Hannes Landeholm</a> for <a href="https://stackoverflow.com/questions/24006291/postgresql-return-result-set-as-json-array/24006432#comment45936823_24006432">pointing this out</a></sub></p> | {
"question_id": 24006291,
"question_date": "2014-06-03T02:40:03.157Z",
"question_score": 214,
"tags": "json|postgresql",
"answer_id": 24006432,
"answer_date": "2014-06-03T02:59:59.830Z",
"answer_score": 444
} |
Please answer the following Stack Overflow question:
Title: How to know that a string starts/ends with a specific string in jQuery?
<p>I want to know if a string starts with the specified character/string or ends with it in jQuery.</p>
<p><strong>For Example:</strong></p>
<pre><code>var str = 'Hello World';
if( str starts with 'Hello' ) {
alert('true');
} else {
alert('false');
}
if( str ends with 'World' ) {
alert('true');
} else {
alert('false');
}
</code></pre>
<p>If there is not any function then any alternative ?</p> | <p>One option is to use regular expressions:</p>
<pre><code>if (str.match("^Hello")) {
// do this if begins with Hello
}
if (str.match("World$")) {
// do this if ends in world
}
</code></pre> | {
"question_id": 3715309,
"question_date": "2010-09-15T06:52:26.217Z",
"question_score": 214,
"tags": "javascript|jquery|string",
"answer_id": 3715352,
"answer_date": "2010-09-15T06:57:38.317Z",
"answer_score": 402
} |
Please answer the following Stack Overflow question:
Title: How to center absolute div horizontally using CSS?
<p>I've a div and want it to be centered horizontally - although I'm giving it <code>margin:0 auto;</code> it's not centered...</p>
<pre><code>.container {
position: absolute;
top: 15px;
z-index: 2;
width:40%;
max-width: 960px;
min-width: 600px;
height: 60px;
overflow: hidden;
background: #fff;
margin:0 auto;
}
</code></pre> | <p>You need to set <code>left: 0</code> and <code>right: 0</code>.</p>
<p>This specifies how far to offset the margin edges from the sides of the window.</p>
<blockquote>
<p>Like 'top', but specifies how far a box's right margin edge is offset to the [left/right] of the [right/left] edge of the box's containing block.</p>
</blockquote>
<p><strong>Source:</strong>
<a href="http://www.w3.org/TR/CSS2/visuren.html#position-props" rel="noreferrer">http://www.w3.org/TR/CSS2/visuren.html#position-props</a></p>
<blockquote>
<p><strong>Note:</strong> The element must have a width <em>smaller</em> than the window or else it will take up the entire width of the window.</p>
<p>You could use media queries to specify a <em>minimum</em> margin, and then transition to <code>auto</code> for larger screen sizes.</p>
</blockquote>
<hr />
<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>.container {
left:0;
right:0;
margin-left: auto;
margin-right: auto;
position: absolute;
width: 40%;
outline: 1px solid black;
background: white;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
Donec ullamcorper nulla non metus auctor fringilla.
Maecenas faucibus mollis interdum.
Sed posuere consectetur est at lobortis.
Vivamus sagittis lacus vel augue laoreet rutrum faucibus dolor auctor.
Sed posuere consectetur est at lobortis.
</div></code></pre>
</div>
</div>
</p> | {
"question_id": 17976995,
"question_date": "2013-07-31T17:26:35.310Z",
"question_score": 214,
"tags": "css|html|center|absolute",
"answer_id": 17977312,
"answer_date": "2013-07-31T17:44:09.753Z",
"answer_score": 474
} |
Please answer the following Stack Overflow question:
Title: How to sort by two fields in Java?
<p>I have array of objects <code>person (int age; String name;)</code>.</p>
<p>How can I sort this array alphabetically by name and then by age?</p>
<p>Which algorithm would you use for this ?</p> | <p>You can use <code>Collections.sort</code> as follows:</p>
<pre><code>private static void order(List<Person> persons) {
Collections.sort(persons, new Comparator() {
public int compare(Object o1, Object o2) {
String x1 = ((Person) o1).getName();
String x2 = ((Person) o2).getName();
int sComp = x1.compareTo(x2);
if (sComp != 0) {
return sComp;
}
Integer x1 = ((Person) o1).getAge();
Integer x2 = ((Person) o2).getAge();
return x1.compareTo(x2);
}});
}
</code></pre>
<p><code>List<Persons></code> is now sorted by name, then by age.</p>
<p><code>String.compareTo</code> "Compares two strings lexicographically" - from the <a href="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html" rel="noreferrer">docs</a>.</p>
<p><code>Collections.sort</code> is a static method in the native Collections library. It does the actual sorting, you just need to provide a Comparator which defines how two elements in your list should be compared: this is achieved by providing your own implementation of the <code>compare</code> method.</p> | {
"question_id": 4805606,
"question_date": "2011-01-26T14:25:00.487Z",
"question_score": 214,
"tags": "java|sorting",
"answer_id": 4805676,
"answer_date": "2011-01-26T14:31:32.037Z",
"answer_score": 273
} |
Please answer the following Stack Overflow question:
Title: How can I make Jenkins CI with Git trigger on pushes to master?
<p>I'm trying to set up Jenkins-ci for a project using GitHub. I've already set up Jenkins with the appropriate plugins. I want Jenkins to run build scripts only whenever someone on the project pushes to master. So far I've been able to set it up so that a build will be triggered anytime anyone pushes to anywhere, but that is too broad. I've done this with post-receive service hooks on Git.</p>
<p>I've read the Jenkins wiki, and a couple of tutorials, but this particular detail is missing... is it something to do with polling maybe? Or should work be done on the Git side, so that Git only triggers Jenkins when <code>master</code> is changed?</p> | <p>As already noted by <em>gezzed</em> in his comment, meanwhile there is a good solution (described in <em><a href="http://kohsuke.org/2011/12/01/polling-must-die-triggering-jenkins-builds-from-a-git-hook/" rel="noreferrer">Polling must die: triggering Jenkins builds from a Git hook</a></em>):</p>
<ul>
<li><p>Set the Jenkins job's build trigger to <em>Poll SCM</em>, but do <em>not</em> specify a schedule.</p></li>
<li><p>Create a GitHub post-receive trigger to notify the URL</p>
<pre><code>http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>?token=<get token from git to build remotely>
</code></pre></li>
<li><p>This will trigger all builds that poll the specified Git repository.</p></li>
<li><p>However, polling actually checks whether anything has been pushed to the used branch.</p></li>
</ul>
<p>It works perfectly.</p> | {
"question_id": 5784329,
"question_date": "2011-04-25T23:19:45.387Z",
"question_score": 214,
"tags": "git|github|jenkins",
"answer_id": 9921495,
"answer_date": "2012-03-29T08:13:27.060Z",
"answer_score": 195
} |
Please answer the following Stack Overflow question:
Title: Convert to binary and keep leading zeros
<p>I'm trying to convert an integer to binary using the bin() function in Python. However, it always removes the leading zeros, which I actually need, such that the result is always 8-bit:</p>
<p>Example:</p>
<pre><code>bin(1) -> 0b1
# What I would like:
bin(1) -> 0b00000001
</code></pre>
<p>Is there a way of doing this?</p> | <p>Use the <a href="http://docs.python.org/2/library/functions.html#format" rel="noreferrer"><code>format()</code> function</a>:</p>
<pre><code>>>> format(14, '#010b')
'0b00001110'
</code></pre>
<p>The <code>format()</code> function simply formats the input following the <a href="http://docs.python.org/2/library/string.html#format-specification-mini-language" rel="noreferrer">Format Specification mini language</a>. The <code>#</code> makes the format include the <code>0b</code> prefix, and the <code>010</code> size formats the output to fit in 10 characters width, with <code>0</code> padding; 2 characters for the <code>0b</code> prefix, the other 8 for the binary digits.</p>
<p>This is the most compact and direct option.</p>
<p>If you are putting the result in a larger string, use an <a href="https://docs.python.org/3/reference/lexical_analysis.html#f-strings" rel="noreferrer">formatted string literal</a> (3.6+) or use <a href="https://docs.python.org/2/library/stdtypes.html#str.format" rel="noreferrer"><code>str.format()</code></a> and put the second argument for the <code>format()</code> function after the colon of the placeholder <code>{:..}</code>:</p>
<pre><code>>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'
</code></pre>
<p>As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using <code>format()</code>:</p>
<pre><code>>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format") # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193
</code></pre>
<p>But I'd use that only if performance in a tight loop matters, as <code>format(...)</code> communicates the intent better.</p>
<p>If you did not want the <code>0b</code> prefix, simply drop the <code>#</code> and adjust the length of the field:</p>
<pre><code>>>> format(14, '08b')
'00001110'
</code></pre> | {
"question_id": 16926130,
"question_date": "2013-06-04T19:41:19.523Z",
"question_score": 214,
"tags": "python|binary|formatting|bitwise-operators",
"answer_id": 16926357,
"answer_date": "2013-06-04T19:54:38.957Z",
"answer_score": 305
} |
Please answer the following Stack Overflow question:
Title: How does the bitwise complement operator (~ tilde) work?
<p>Why is it that ~2 is equal to -3? How does <code>~</code> operator work?</p> | <p>Remember that negative numbers are stored as the <strong>two's complement</strong> of the positive counterpart. As an example, here's the representation of -2 in two's complement: (8 bits)</p>
<pre><code>1111 1110
</code></pre>
<p>The way you get this is by taking the binary representation of a number, taking its complement (inverting all the bits) and adding one. Two starts as 0000 0010, and by inverting the bits we get 1111 1101. Adding one gets us the result above. The first bit is the sign bit, implying a negative.</p>
<p>So let's take a look at how we get ~2 = -3:</p>
<p>Here's two again:</p>
<pre><code>0000 0010
</code></pre>
<p>Simply flip all the bits and we get:</p>
<pre><code>1111 1101
</code></pre>
<p>Well, what's -3 look like in two's complement? Start with positive 3: 0000 0011, flip all the bits to 1111 1100, and add one to become negative value (-3), 1111 1101.</p>
<p>So if you simply invert the bits in 2, you get the two's complement representation of -3.</p>
<h2>The complement operator (~) JUST FLIPS BITS. It is up to the machine to interpret these bits.</h2> | {
"question_id": 791328,
"question_date": "2009-04-26T18:29:46.510Z",
"question_score": 214,
"tags": "operators|bitwise-operators|complement",
"answer_id": 791340,
"answer_date": "2009-04-26T18:35:04.250Z",
"answer_score": 322
} |
Please answer the following Stack Overflow question:
Title: VSCode -- how to set working directory for debugging a Python program
<p>How do I run a Python program under debug and set the working directory for the run?</p> | <p><a href="https://stackoverflow.com/questions/38623138/vscode-how-to-set-working-directory-for-debugging-a-python-program#comment93079003_38637243">@SpeedCoder5's comment</a> deserves to be an answer.</p>
<p>In <code>launch.json</code>, specify a dynamic working directory (i.e. the directory where the currently-open Python file is located) using:</p>
<pre><code>"cwd": "${fileDirname}"
</code></pre>
<p>This takes advantage of the <a href="https://code.visualstudio.com/docs/editor/variables-reference#_settings-command-variables-and-input-variables" rel="noreferrer">"variables reference" feature in VS Code</a>, and the predefined variable <code>fileDirname</code>.</p>
<p>If you're using the <code>Python: Current File (Integrated Terminal)</code> option when you run Python, your <code>launch.json</code> file might look like mine, below (<a href="https://code.visualstudio.com/docs/editor/debugging#_launch-configurations" rel="noreferrer">more info on <code>launch.json</code> files here</a>).</p>
<pre><code>{
"version": "0.2.0",
"configurations": [
{
"name": "Python: Current File (Integrated Terminal)",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"cwd": "${fileDirname}"
},
//... other settings, but I modified the "Current File" setting above ...
}
</code></pre>
<p><a href="https://code.visualstudio.com/docs/editor/debugging#_launch-versus-attach-configurations" rel="noreferrer">Remember the <code>launch.json</code> file controls the run/debug settings of your Visual Studio code project</a>; my <code>launch.json</code> file was auto-generated by VS Code, in the directory of my current "Open Project". I just edited the file manually to add <code>"cwd": "${fileDirname}"</code> as shown above.</p>
<p>Remember the <code>launch.json</code> file may be specific to your project, or specific to your directory, so confirm you're editing the <em>correct</em> <code>launch.json</code> (see comment)</p>
<p>If you don't have a <code>launch.json</code> file, <a href="https://code.visualstudio.com/docs/editor/debugging#_launch-configurations" rel="noreferrer">try this</a>:</p>
<blockquote>
<p>To create a launch.json file, open your project folder in VS Code (File > Open Folder) and then select the Configure gear icon on the Debug view top bar.</p>
</blockquote> | {
"question_id": 38623138,
"question_date": "2016-07-27T21:03:05.187Z",
"question_score": 214,
"tags": "python|visual-studio-code",
"answer_id": 55072246,
"answer_date": "2019-03-08T23:09:11.553Z",
"answer_score": 323
} |
Please answer the following Stack Overflow question:
Title: Determine if $.ajax error is a timeout
<p>I'm utilizing the magic of <code>jQuery.ajax( settings )</code>.</p>
<p>However, I'm wondering if anyone has played with the timeout setting much?</p>
<p>I know it's basically for dictating the local time for a request, but can it trigger anything if the timeout is reached? Or does it simply stop listening for a response?</p>
<p>Reading the jQuery site, I can see there are no arguments passed, so it seems like a simple setting with one capability. Which is fine. </p>
<p>But, I'd like to trigger an alert or some function if the timeout is reached. I can see that the error setting doesn't get triggered, in this case.</p>
<p>Here's my snippet:</p>
<pre><code>$("form#testform").submit(function(){
var allFormValues = $("form#testform").serialize();
$.ajax({
cache:false,
timeout:8000, // I chose 8 secs for kicks
type:"POST",
url:"someurl.php",
data:allFormValues,
error:function(){ alert("some error occurred") },
success:function(response){ alert(response); }
});
});
</code></pre>
<p>Does anyone know how to work more with timeout?</p> | <p>If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'. </p>
<p>Per the <a href="http://api.jquery.com/jQuery.ajax/" rel="noreferrer">jQuery documentation</a>:</p>
<blockquote>
<p>Possible values for the second
argument (besides null) are "timeout",
"error", "notmodified" and
"parsererror".</p>
</blockquote>
<p>You can handle your error accordingly then. </p>
<p>I created this <a href="http://jsfiddle.net/u3f9C/" rel="noreferrer">fiddle</a> that demonstrates this.</p>
<pre><code>$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 1000,
success: function(response) { alert(response); },
error: function(xmlhttprequest, textstatus, message) {
if(textstatus==="timeout") {
alert("got timeout");
} else {
alert(textstatus);
}
}
});
</code></pre>
<p>With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.</p>
<p>Hope this helps!</p> | {
"question_id": 3543683,
"question_date": "2010-08-22T22:17:30.410Z",
"question_score": 214,
"tags": "jquery|ajax|connection-timeout",
"answer_id": 3543713,
"answer_date": "2010-08-22T22:26:07.320Z",
"answer_score": 366
} |
Please answer the following Stack Overflow question:
Title: Vuejs: Event on route change
<p>On my main page I have dropdowns that show <code>v-show=show</code> by clicking on the link <code>@click = "show=!show"</code> and I want to set <code>show=false</code> when I change the route. Please advise me on how to realize this thing.</p> | <p>Setup a <a href="https://v2.vuejs.org/v2/guide/computed.html#Watchers" rel="noreferrer">watcher</a> on the <code>$route</code> in your component like this:</p>
<pre><code>watch:{
$route (to, from){
this.show = false;
}
}
</code></pre>
<p>This observes for route changes and when changed ,sets <code>show</code> to false</p> | {
"question_id": 46402809,
"question_date": "2017-09-25T10:17:50.877Z",
"question_score": 214,
"tags": "vue.js|vuejs2|vue-router",
"answer_id": 46403063,
"answer_date": "2017-09-25T10:32:18.600Z",
"answer_score": 443
} |
Please answer the following Stack Overflow question:
Title: Locating data volumes in Docker Desktop (Windows)
<p>I'm trying to learn docker at the moment and I'm getting confused about where data volumes actually exist.</p>
<p>I'm using <strong>Docker Desktop for Windows</strong>. (Windows 10)</p>
<p>In the docs they say that running docker inspect on the object will give you the source:<a href="https://docs.docker.com/engine/tutorials/dockervolumes/#locating-a-volume" rel="noreferrer">https://docs.docker.com/engine/tutorials/dockervolumes/#locating-a-volume</a></p>
<pre><code>$ docker inspect web
"Mounts": [
{
"Name": "fac362...80535",
"Source": "/var/lib/docker/volumes/fac362...80535/_data",
"Destination": "/webapp",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
}
]
</code></pre>
<p>however I don't see this, I get the following:</p>
<pre><code>$ docker inspect blog_postgres-data
[
{
"Driver": "local",
"Labels": null,
"Mountpoint": "/var/lib/docker/volumes/blog_postgres-data/_data",
"Name": "blog_postgres-data",
"Options": {},
"Scope": "local"
}
]
</code></pre>
<p>Can anyone help me? I just want to know where my data volume actually exists is it on my host machine? If so how can i get the path to it?</p> | <p>Your volume directory is <code>/var/lib/docker/volumes/blog_postgres-data/_data</code>, and <code>/var/lib/docker</code> usually mounted in <code>C:\Users\Public\Documents\Hyper-V\Virtual hard disks</code>. Anyway you can check it out by looking in Docker settings.</p>
<p>You can refer to <a href="https://docs.docker.com/docker-for-windows/#shared-drives" rel="noreferrer">these docs</a> for info on how to share drives with Docker on Windows.</p>
<p>BTW, <code>Source</code> is the location on the host and <code>Destination</code> is the location inside the container in the following output:</p>
<pre><code>"Mounts": [
{
"Name": "fac362...80535",
"Source": "/var/lib/docker/volumes/fac362...80535/_data",
"Destination": "/webapp",
"Driver": "local",
"Mode": "",
"RW": true,
"Propagation": ""
}
]
</code></pre>
<hr />
<p>Updated to answer questions in the comment:</p>
<blockquote>
<p>My main curiosity here is that sharing images etc is great but how do I share my data?</p>
</blockquote>
<p>Actually <code>volume</code> is designed for this purpose (manage data in Docker container). The data in a volume is persisted on the host FS and isolated from the life-cycle of a Docker container/image. You can share your data in a volume by:</p>
<ul>
<li><p>Mount Docker volume to host and reuse it</p>
<p><code>docker run -v /path/on/host:/path/inside/container image</code></p>
<p>Then all your data will persist in <code>/path/on/host</code>; you could back it up, copy it to another machine, and re-run your container with the same volume.</p>
</li>
<li><p>Create and mount a data container.</p>
<p>Create a data container: <code>docker create -v /dbdata --name dbstore training/postgres /bin/true</code></p>
<p>Run other containers based on this container using <code>--volumes-from</code>: <code>docker run -d --volumes-from dbstore --name db1 training/postgres</code>, then all data generated by <code>db1</code> will persist in the volume of container <code>dbstore</code>.</p>
</li>
</ul>
<p>For more information you could refer to the <a href="https://docs.docker.com/engine/tutorials/dockervolumes/" rel="noreferrer">official Docker volumes docs</a>.</p>
<p>Simply speaking, <code>volumes</code> is just a directory on your host with all your container data, so you could use any method you used before to backup/share your data.</p>
<blockquote>
<p>can I push a volume to docker-hub like I do with images?</p>
</blockquote>
<p>No. A Docker <em>image</em> is something you can push to a Docker hub (a.k.a. 'registry'); but data is not. You could backup/persist/share your data with any method you like, but pushing data to a Docker registry to share it does not make any sense.</p>
<blockquote>
<p>can I make backups etc?</p>
</blockquote>
<p>Yes, as posted above :-)</p> | {
"question_id": 43181654,
"question_date": "2017-04-03T10:00:05.720Z",
"question_score": 214,
"tags": "docker|docker-for-windows|docker-desktop",
"answer_id": 43182885,
"answer_date": "2017-04-03T11:00:08.227Z",
"answer_score": 79
} |
Please answer the following Stack Overflow question:
Title: take(1) vs first()
<p>I found a few implementation of <code>AuthGuard</code>s that use <code>take(1)</code>. In my project, I used <code>first()</code>.</p>
<p>Do both work the same way?</p>
<pre><code>import 'rxjs/add/operator/map';
import 'rxjs/add/operator/first';
import { Observable } from 'rxjs/Observable';
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AngularFire } from 'angularfire2';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private angularFire: AngularFire, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
return this.angularFire.auth.map(
(auth) => {
if (auth) {
this.router.navigate(['/dashboard']);
return false;
} else {
return true;
}
}
).first(); // Just change this to .take(1)
}
}
</code></pre> | <p>Operators <code>first()</code> and <code>take(1)</code> aren't the same.</p>
<p>The <code>first()</code> operator takes an optional <code>predicate</code> function and emits an <code>error</code> notification when no value matched when the source completed.</p>
<p>For example this will emit an error:</p>
<pre><code>import { EMPTY, range } from 'rxjs';
import { first, take } from 'rxjs/operators';
EMPTY.pipe(
first(),
).subscribe(console.log, err => console.log('Error', err));
</code></pre>
<p>... as well as this:</p>
<pre><code>range(1, 5).pipe(
first(val => val > 6),
).subscribe(console.log, err => console.log('Error', err));
</code></pre>
<p>While this will match the first value emitted:</p>
<pre><code>range(1, 5).pipe(
first(),
).subscribe(console.log, err => console.log('Error', err));
</code></pre>
<p>On the other hand <code>take(1)</code> just takes the first value and completes. No further logic is involved.</p>
<pre><code>range(1, 5).pipe(
take(1),
).subscribe(console.log, err => console.log('Error', err));
</code></pre>
<p>Then with empty source Observable it won't emit any error:</p>
<pre><code>EMPTY.pipe(
take(1),
).subscribe(console.log, err => console.log('Error', err));
</code></pre>
<p>Jan 2019: Updated for RxJS 6</p> | {
"question_id": 42345969,
"question_date": "2017-02-20T13:34:32.377Z",
"question_score": 214,
"tags": "angular|rxjs|angular2-observables",
"answer_id": 42346203,
"answer_date": "2017-02-20T13:44:56.633Z",
"answer_score": 284
} |
Please answer the following Stack Overflow question:
Title: Is an empty href valid?
<p>One of our web developers uses the following html as a placeholder for styling a drop down list.</p>
<pre><code><a href="" class="arrow"></a>
</code></pre>
<p>Is this considered anchor tag valid? </p>
<p>Since there is no href value, it shows up as broken on some of our link checker reports.</p> | <p>Although this question is already answered (<strong>tl;dr:</strong> yes, an empty <code>href</code> value is valid), none of the existing answers references the relevant specifications.</p>
<p>An empty string <strong>can’t be a URI.</strong> However, the <code>href</code> attribute doesn’t only take URIs as value, but also URI references. An empty string <strong>may be a URI reference.</strong></p>
<h2>HTML 4.01</h2>
<p>HTML 4.01 <a href="https://www.w3.org/TR/1999/REC-html401-19991224/types.html#type-uri" rel="nofollow noreferrer">uses</a> <strong>RFC 2396</strong>, where it says in section <a href="https://www.rfc-editor.org/rfc/rfc2396#section-4.2" rel="nofollow noreferrer">4.2. Same-document References</a> (bold emphasis mine):</p>
<blockquote>
<p>A URI reference that does not contain a URI is a reference to the current document. In other words, <strong>an empty URI reference within a document is interpreted as a reference to the start of that document</strong>, and a reference containing only a fragment identifier is a reference to the identified fragment of that document.</p>
</blockquote>
<p>RFC 2396 is obsoleted by <strong>RFC 3986</strong> (which is currently <a href="https://tools.ietf.org/html/std66" rel="nofollow noreferrer">IETF’s URI standard</a>), which <a href="https://stackoverflow.com/a/43338457/1591669">essentially says the same</a>.</p>
<h2>HTML5</h2>
<p>HTML5 <a href="https://www.w3.org/TR/2014/REC-html5-20141028/links.html#attr-hyperlink-href" rel="nofollow noreferrer">uses</a> (<a href="https://www.w3.org/TR/2014/REC-html5-20141028/infrastructure.html#valid-url-potentially-surrounded-by-spaces" rel="nofollow noreferrer"><em>valid URL potentially surrounded by spaces</em></a> → <a href="https://www.w3.org/TR/2014/REC-html5-20141028/infrastructure.html#valid-url" rel="nofollow noreferrer"><em>valid URL</em></a>) <strong>W3C’s URL spec</strong>, which has been discontinued. <strong>WHATWG’s URL Standard</strong> should be used instead (see the last section).</p>
<h2>HTML 5.1</h2>
<p>HTML 5.1 <a href="https://www.w3.org/TR/2016/REC-html51-20161101/links.html#element-attrdef-a-href" rel="nofollow noreferrer">uses</a> (<a href="https://www.w3.org/TR/2016/REC-html51-20161101/infrastructure.html#valid-url-potentially-surrounded-by-spaces" rel="nofollow noreferrer"><em>valid URL potentially surrounded by spaces</em></a> → <a href="https://www.w3.org/TR/2016/REC-html51-20161101/infrastructure.html#valid-url" rel="nofollow noreferrer"><em>valid URL</em></a>) <strong>WHATWG’s URL Standard</strong> (see the next section).</p>
<h2>WHATWG HTML</h2>
<p>WHATWG’s HTML <a href="https://html.spec.whatwg.org/multipage/semantics.html#attr-hyperlink-href" rel="nofollow noreferrer">uses</a> (<a href="https://html.spec.whatwg.org/multipage/infrastructure.html#valid-url-potentially-surrounded-by-spaces" rel="nofollow noreferrer"><em>valid URL potentially surrounded by spaces</em></a>) the definition of <a href="https://url.spec.whatwg.org/#valid-url-string" rel="nofollow noreferrer"><em>valid URL string</em></a> from <strong>WHATWG’s URL Standard</strong>, where it says that it can be a <a href="https://url.spec.whatwg.org/#relative-url-with-fragment-string" rel="nofollow noreferrer"><em>relative-URL-with-fragment string</em></a>, which must at least be a <a href="https://url.spec.whatwg.org/#relative-url-string" rel="nofollow noreferrer"><em>relative-URL string</em></a>, which can be a <a href="https://url.spec.whatwg.org/#path-relative-scheme-less-url-string" rel="nofollow noreferrer"><em>path-relative-scheme-less-URL string</em></a>, which is a <a href="https://url.spec.whatwg.org/#path-relative-url-string" rel="nofollow noreferrer"><em>path-relative-URL string</em></a> that doesn’t start with a scheme string followed by <code>:</code>, and its definition says (bold emphasis mine):</p>
<blockquote>
<p>A path-relative-URL string must be <strong>zero</strong> or more URL-path-segment strings, separated from each other by U+002F (/), and not start with U+002F (/).</p>
</blockquote> | {
"question_id": 5637969,
"question_date": "2011-04-12T15:44:18.173Z",
"question_score": 214,
"tags": "html|href",
"answer_id": 43340108,
"answer_date": "2017-04-11T08:04:25.497Z",
"answer_score": 77
} |
Please answer the following Stack Overflow question:
Title: How to limit the maximum value of a numeric field in a Django model?
<p>Django has various numeric fields available for use in models, e.g. <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#decimalfield" rel="noreferrer">DecimalField</a> and <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#positiveintegerfield" rel="noreferrer">PositiveIntegerField</a>. Although the former can be restricted to the number of decimal places stored and the overall number of characters stored, is there any way to restrict it to storing <em>only</em> numbers within a certain range, e.g. 0.0-5.0 ?</p>
<p>Failing that, is there any way to restrict a PositiveIntegerField to only store, for instance, numbers up to 50?</p>
<p><strong><em>Update: now that Bug 6845 <a href="http://code.djangoproject.com/ticket/6845#comment:71" rel="noreferrer">has been closed</a>, this StackOverflow question may be moot. - sampablokuper</em></strong></p> | <p>You could also create a custom model field type - see <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields" rel="noreferrer">http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields</a></p>
<p>In this case, you could 'inherit' from the built-in IntegerField and override its validation logic.</p>
<p>The more I think about this, I realize how useful this would be for many Django apps. Perhaps a IntegerRangeField type could be submitted as a patch for the Django devs to consider adding to trunk.</p>
<p>This is working for me:</p>
<pre><code>from django.db import models
class IntegerRangeField(models.IntegerField):
def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
self.min_value, self.max_value = min_value, max_value
models.IntegerField.__init__(self, verbose_name, name, **kwargs)
def formfield(self, **kwargs):
defaults = {'min_value': self.min_value, 'max_value':self.max_value}
defaults.update(kwargs)
return super(IntegerRangeField, self).formfield(**defaults)
</code></pre>
<p>Then in your model class, you would use it like this (field being the module where you put the above code):</p>
<pre><code>size = fields.IntegerRangeField(min_value=1, max_value=50)
</code></pre>
<p>OR for a range of negative and positive (like an oscillator range):</p>
<pre><code>size = fields.IntegerRangeField(min_value=-100, max_value=100)
</code></pre>
<p>What would be really cool is if it could be called with the range operator like this:</p>
<pre><code>size = fields.IntegerRangeField(range(1, 50))
</code></pre>
<p>But, that would require a lot more code since since you can specify a 'skip' parameter - range(1, 50, 2) - Interesting idea though...</p> | {
"question_id": 849142,
"question_date": "2009-05-11T17:29:57.330Z",
"question_score": 214,
"tags": "python|django|django-models|django-validation",
"answer_id": 849426,
"answer_date": "2009-05-11T18:31:21.033Z",
"answer_score": 143
} |
Please answer the following Stack Overflow question:
Title: Is there a way to use PhantomJS in Python?
<p>I want to use <a href="http://phantomjs.org/">PhantomJS</a> in <a href="http://www.python.org/">Python</a>. I googled this problem but couldn't find proper solutions.</p>
<p>I find <code>os.popen()</code> may be a good choice. But I couldn't pass some arguments to it.</p>
<p>Using <code>subprocess.Popen()</code> may be a proper solution for now. I want to know whether there's a better solution or not.</p>
<p>Is there a way to use PhantomJS in Python?</p> | <p>The easiest way to use PhantomJS in python is via Selenium. The simplest installation method is</p>
<ol>
<li>Install <a href="https://nodejs.org/" rel="noreferrer">NodeJS</a></li>
<li>Using Node's package manager install phantomjs: <code>npm -g install phantomjs-prebuilt</code></li>
<li>install selenium (in your virtualenv, if you are using that)</li>
</ol>
<p>After installation, you may use phantom as simple as:</p>
<pre><code>from selenium import webdriver
driver = webdriver.PhantomJS() # or add to your PATH
driver.set_window_size(1024, 768) # optional
driver.get('https://google.com/')
driver.save_screenshot('screen.png') # save a screenshot to disk
sbtn = driver.find_element_by_css_selector('button.gbqfba')
sbtn.click()
</code></pre>
<p>If your system path environment variable isn't set correctly, you'll need to specify the exact path as an argument to <code>webdriver.PhantomJS()</code>. Replace this:</p>
<pre><code>driver = webdriver.PhantomJS() # or add to your PATH
</code></pre>
<p>... with the following:</p>
<pre><code>driver = webdriver.PhantomJS(executable_path='/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs')
</code></pre>
<p>References:</p>
<ul>
<li><a href="http://selenium-python.readthedocs.io/" rel="noreferrer">http://selenium-python.readthedocs.io/</a></li>
<li><a href="https://stackoverflow.com/questions/14699718/how-do-i-set-a-proxy-for-phantomjs-ghostdriver-in-python-webdriver/15699530#15699530">How do I set a proxy for phantomjs/ghostdriver in python webdriver?</a></li>
<li><a href="https://dzone.com/articles/python-testing-phantomjs" rel="noreferrer">https://dzone.com/articles/python-testing-phantomjs</a></li>
</ul> | {
"question_id": 13287490,
"question_date": "2012-11-08T10:46:54.207Z",
"question_score": 214,
"tags": "python|phantomjs",
"answer_id": 15699761,
"answer_date": "2013-03-29T08:23:16.483Z",
"answer_score": 384
} |
Please answer the following Stack Overflow question:
Title: Static method in a generic class?
<p>In Java, I'd like to have something as:</p>
<pre><code>class Clazz<T> {
static void doIt(T object) {
// ...
}
}
</code></pre>
<p>But I get</p>
<pre>Cannot make a static reference to the non-static type T</pre>
<p>I don't understand generics beyond the basic uses and thus can't make much sense of that. It doesn't help that I wasn't able to find much info on the internet about the subject.</p>
<p>Could someone clarify if such use is possible, by a similar manner? Also, why was my original attempt unsuccessful?</p> | <p>You can't use a class's generic type parameters in static methods or static fields. The class's type parameters are only in scope for instance methods and instance fields. For static fields and static methods, they are shared among all instances of the class, even instances of different type parameters, so obviously they cannot depend on a particular type parameter.</p>
<p>It doesn't seem like your problem should require using the class's type parameter. If you describe what you are trying to do in more detail, maybe we can help you find a better way to do it.</p> | {
"question_id": 936377,
"question_date": "2009-06-01T19:35:34.233Z",
"question_score": 214,
"tags": "java|generics|static-methods",
"answer_id": 936951,
"answer_date": "2009-06-01T21:43:37.347Z",
"answer_score": 301
} |
Please answer the following Stack Overflow question:
Title: Create a tar.xz in one command
<p>I am trying to create a <code>.tar.xz</code> compressed archive in one command. What is the specific syntax for that?</p>
<p>I have tried <code>tar cf - file | xz file.tar.xz</code>, but that does not work.</p> | <p>Use the <code>-J</code> compression option for <code>xz</code>. And remember to <a href="http://linux.die.net/man/1/tar"><code>man tar</code></a> :)</p>
<pre><code>tar cfJ <archive.tar.xz> <files>
</code></pre>
<p>Edit 2015-08-10:</p>
<p>If you're passing the arguments to <code>tar</code> <strong>with dashes</strong> (ex: <code>tar -cf</code> as opposed to <code>tar cf</code>), <strong>then the <code>-f</code> option must come last</strong>, since it specifies the filename (thanks to <a href="https://stackoverflow.com/users/832230/a-b-b">@A-B-B</a> for pointing that out!). In that case, the command looks like:</p>
<pre><code>tar -cJf <archive.tar.xz> <files>
</code></pre> | {
"question_id": 18855850,
"question_date": "2013-09-17T17:08:40.747Z",
"question_score": 214,
"tags": "compression|archive|tar|xz",
"answer_id": 18855909,
"answer_date": "2013-09-17T17:12:34.137Z",
"answer_score": 338
} |
Please answer the following Stack Overflow question:
Title: Suppress Scientific Notation in Numpy When Creating Array From Nested List
<p>I have a nested Python list that looks like the following:</p>
<pre><code>my_list = [[3.74, 5162, 13683628846.64, 12783387559.86, 1.81],
[9.55, 116, 189688622.37, 260332262.0, 1.97],
[2.2, 768, 6004865.13, 5759960.98, 1.21],
[3.74, 4062, 3263822121.39, 3066869087.9, 1.93],
[1.91, 474, 44555062.72, 44555062.72, 0.41],
[5.8, 5006, 8254968918.1, 7446788272.74, 3.25],
[4.5, 7887, 30078971595.46, 27814989471.31, 2.18],
[7.03, 116, 66252511.46, 81109291.0, 1.56],
[6.52, 116, 47674230.76, 57686991.0, 1.43],
[1.85, 623, 3002631.96, 2899484.08, 0.64],
[13.76, 1227, 1737874137.5, 1446511574.32, 4.32],
[13.76, 1227, 1737874137.5, 1446511574.32, 4.32]]
</code></pre>
<p>I then import Numpy, and set print options to <code>(suppress=True)</code>. When I create an array:</p>
<pre><code>my_array = numpy.array(my_list)
</code></pre>
<p>I can't for the life of me suppress scientific notation:</p>
<pre><code>[[ 3.74000000e+00 5.16200000e+03 1.36836288e+10 1.27833876e+10
1.81000000e+00]
[ 9.55000000e+00 1.16000000e+02 1.89688622e+08 2.60332262e+08
1.97000000e+00]
[ 2.20000000e+00 7.68000000e+02 6.00486513e+06 5.75996098e+06
1.21000000e+00]
[ 3.74000000e+00 4.06200000e+03 3.26382212e+09 3.06686909e+09
1.93000000e+00]
[ 1.91000000e+00 4.74000000e+02 4.45550627e+07 4.45550627e+07
4.10000000e-01]
[ 5.80000000e+00 5.00600000e+03 8.25496892e+09 7.44678827e+09
3.25000000e+00]
[ 4.50000000e+00 7.88700000e+03 3.00789716e+10 2.78149895e+10
2.18000000e+00]
[ 7.03000000e+00 1.16000000e+02 6.62525115e+07 8.11092910e+07
1.56000000e+00]
[ 6.52000000e+00 1.16000000e+02 4.76742308e+07 5.76869910e+07
1.43000000e+00]
[ 1.85000000e+00 6.23000000e+02 3.00263196e+06 2.89948408e+06
6.40000000e-01]
[ 1.37600000e+01 1.22700000e+03 1.73787414e+09 1.44651157e+09
4.32000000e+00]
[ 1.37600000e+01 1.22700000e+03 1.73787414e+09 1.44651157e+09
4.32000000e+00]]
</code></pre>
<p>If I create a simple numpy array directly:</p>
<pre><code>new_array = numpy.array([1.5, 4.65, 7.845])
</code></pre>
<p>I have no problem and it prints as follows:</p>
<pre><code>[ 1.5 4.65 7.845]
</code></pre>
<p>Does anyone know what my problem is?</p> | <p>This is what you need:</p>
<pre><code>np.set_printoptions(suppress=True)
</code></pre>
<p>Here is the <a href="https://numpy.org/doc/stable/reference/generated/numpy.set_printoptions.html" rel="noreferrer">documentation</a>.</p> | {
"question_id": 9777783,
"question_date": "2012-03-19T20:54:15.010Z",
"question_score": 214,
"tags": "python|numpy|number-formatting|scientific-notation",
"answer_id": 10854323,
"answer_date": "2012-06-01T16:46:21.903Z",
"answer_score": 355
} |
Please answer the following Stack Overflow question:
Title: How can I use if/else in a dictionary comprehension?
<p>Does there exist a way in Python 2.7+ to make something like the following?</p>
<pre><code>{ something_if_true if condition else something_if_false for key, value in dict_.items() }
</code></pre>
<p>I know you can make anything with just 'if':</p>
<pre><code>{ something_if_true for key, value in dict_.items() if condition}
</code></pre> | <p>You've already got it: <code>A if test else B</code> is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:</p>
<pre><code>{ (some_key if condition else default_key):(something_if_true if condition
else something_if_false) for key, value in dict_.items() }
</code></pre>
<p>The final <code>if</code> clause acts as a filter, which is different from having the conditional expression.</p> | {
"question_id": 9442724,
"question_date": "2012-02-25T09:04:45.907Z",
"question_score": 214,
"tags": "python|dictionary|dictionary-comprehension",
"answer_id": 9442777,
"answer_date": "2012-02-25T09:17:15.253Z",
"answer_score": 390
} |
Please answer the following Stack Overflow question:
Title: Do I need to close() both FileReader and BufferedReader?
<p>I'm reading a local file using a BufferedReader wrapped around a FileReader:</p>
<pre><code>BufferedReader reader = new BufferedReader(new FileReader(fileName));
// read the file
// (error handling snipped)
reader.close();
</code></pre>
<p>Do I need to <code>close()</code> the <code>FileReader</code> as well, or will the wrapper handle that?
I've seen code where people do something like this:</p>
<pre><code>FileReader fReader = new FileReader(fileName);
BufferedReader bReader = new BufferedReader(fReader);
// read the file
// (error handling snipped)
bReader.close();
fReader.close();
</code></pre>
<p>This method is called from a servlet, and I'd like to make sure I don't leave any handles open.</p> | <p>no.</p>
<pre><code>BufferedReader.close()
</code></pre>
<p><strong>closes the stream</strong> according to javadoc for <a href="http://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#close--" rel="noreferrer">BufferedReader</a> and <a href="http://docs.oracle.com/javase/8/docs/api/java/io/InputStreamReader.html#close--" rel="noreferrer">InputStreamReader</a></p>
<p>as well as</p>
<pre><code>FileReader.close()
</code></pre>
<p>does.</p> | {
"question_id": 1388602,
"question_date": "2009-09-07T10:15:47.777Z",
"question_score": 214,
"tags": "java|io|bufferedreader|filereader",
"answer_id": 1388627,
"answer_date": "2009-09-07T10:20:10.323Z",
"answer_score": 219
} |
Please answer the following Stack Overflow question:
Title: How do you print in Sublime Text 2
<p>Sublime Text 2 seems like a great editor. I just started using it a week ago in eval mode and it doesn't seem to have any printing functionality. This seems preposterous to me, but I can't find it anywhere.</p>
<p>Is this a feature unlocked after purchase? I see no mention of that on the company website.</p>
<p>Can anyone help?</p> | <p>This isn't supported yet. You can use plugins to export the text into HTML or RTF first, and then you can print it out, if you want.</p>
<p>Here is for example the <a href="https://github.com/n1k0/SublimeHighlight">SublimeHighlight</a> plugin which you can use for exporting.</p> | {
"question_id": 16004842,
"question_date": "2013-04-14T21:56:38.493Z",
"question_score": 214,
"tags": "sublimetext2",
"answer_id": 16004879,
"answer_date": "2013-04-14T22:01:15.250Z",
"answer_score": 86
} |
Please answer the following Stack Overflow question:
Title: Add missing dates to pandas dataframe
<p>My data can have multiple events on a given date or NO events on a date. I take these events, get a count by date and plot them. However, when I plot them, my two series don't always match. </p>
<pre><code>idx = pd.date_range(df['simpleDate'].min(), df['simpleDate'].max())
s = df.groupby(['simpleDate']).size()
</code></pre>
<p>In the above code <strong>idx</strong> becomes a range of say 30 dates. 09-01-2013 to 09-30-2013
However <strong>S</strong> may only have 25 or 26 days because no events happened for a given date. I then get an AssertionError as the sizes dont match when I try to plot:</p>
<pre><code>fig, ax = plt.subplots()
ax.bar(idx.to_pydatetime(), s, color='green')
</code></pre>
<p>What's the proper way to tackle this? Do I want to remove dates with no values from <strong>IDX</strong> or (which I'd rather do) is add to the series the missing date with a count of 0. I'd rather have a full graph of 30 days with 0 values. If this approach is right, any suggestions on how to get started? Do I need some sort of dynamic <code>reindex</code> function?</p>
<p>Here's a snippet of <strong>S</strong> ( <code>df.groupby(['simpleDate']).size()</code> ), notice no entries for 04 and 05.</p>
<pre><code>09-02-2013 2
09-03-2013 10
09-06-2013 5
09-07-2013 1
</code></pre> | <p>You could use <code>Series.reindex</code>:</p>
<pre><code>import pandas as pd
idx = pd.date_range('09-01-2013', '09-30-2013')
s = pd.Series({'09-02-2013': 2,
'09-03-2013': 10,
'09-06-2013': 5,
'09-07-2013': 1})
s.index = pd.DatetimeIndex(s.index)
s = s.reindex(idx, fill_value=0)
print(s)
</code></pre>
<p>yields</p>
<pre><code>2013-09-01 0
2013-09-02 2
2013-09-03 10
2013-09-04 0
2013-09-05 0
2013-09-06 5
2013-09-07 1
2013-09-08 0
...
</code></pre> | {
"question_id": 19324453,
"question_date": "2013-10-11T17:58:15.307Z",
"question_score": 214,
"tags": "python|date|plot|pandas|dataframe",
"answer_id": 19324591,
"answer_date": "2013-10-11T18:08:29.603Z",
"answer_score": 382
} |
Please answer the following Stack Overflow question:
Title: "Cloning" row or column vectors
<p>Sometimes it is useful to "clone" a row or column vector to a matrix. By cloning I mean converting a row vector such as</p>
<pre><code>[1, 2, 3]
</code></pre>
<p>Into a matrix</p>
<pre><code>[[1, 2, 3],
[1, 2, 3],
[1, 2, 3]]
</code></pre>
<p>or a column vector such as</p>
<pre><code>[[1],
[2],
[3]]
</code></pre>
<p>into</p>
<pre><code>[[1, 1, 1]
[2, 2, 2]
[3, 3, 3]]
</code></pre>
<p>In MATLAB or octave this is done pretty easily:</p>
<pre><code> x = [1, 2, 3]
a = ones(3, 1) * x
a =
1 2 3
1 2 3
1 2 3
b = (x') * ones(1, 3)
b =
1 1 1
2 2 2
3 3 3
</code></pre>
<p>I want to repeat this in numpy, but unsuccessfully</p>
<pre><code>In [14]: x = array([1, 2, 3])
In [14]: ones((3, 1)) * x
Out[14]:
array([[ 1., 2., 3.],
[ 1., 2., 3.],
[ 1., 2., 3.]])
# so far so good
In [16]: x.transpose() * ones((1, 3))
Out[16]: array([[ 1., 2., 3.]])
# DAMN
# I end up with
In [17]: (ones((3, 1)) * x).transpose()
Out[17]:
array([[ 1., 1., 1.],
[ 2., 2., 2.],
[ 3., 3., 3.]])
</code></pre>
<p>Why wasn't the first method (<code>In [16]</code>) working? Is there a way to achieve this task in python in a more elegant way?</p> | <p>Here's an elegant, Pythonic way to do it:</p>
<pre><code>>>> array([[1,2,3],]*3)
array([[1, 2, 3],
[1, 2, 3],
[1, 2, 3]])
>>> array([[1,2,3],]*3).transpose()
array([[1, 1, 1],
[2, 2, 2],
[3, 3, 3]])
</code></pre>
<p>the problem with <code>[16]</code> seems to be that the transpose has no effect for an array. you're probably wanting a matrix instead:</p>
<pre><code>>>> x = array([1,2,3])
>>> x
array([1, 2, 3])
>>> x.transpose()
array([1, 2, 3])
>>> matrix([1,2,3])
matrix([[1, 2, 3]])
>>> matrix([1,2,3]).transpose()
matrix([[1],
[2],
[3]])
</code></pre> | {
"question_id": 1550130,
"question_date": "2009-10-11T07:54:05.503Z",
"question_score": 214,
"tags": "python|numpy|linear-algebra",
"answer_id": 1550137,
"answer_date": "2009-10-11T07:59:23.153Z",
"answer_score": 106
} |
Please answer the following Stack Overflow question:
Title: Getting Django admin url for an object
<p>Before Django 1.0 there was an easy way to get the admin url of an object, and I had written a small filter that I'd use like this: <code><a href="{{ object|admin_url }}" .... > ... </a></code></p>
<p>Basically I was using the url reverse function with the view name being <code>'django.contrib.admin.views.main.change_stage'</code></p>
<pre><code>reverse( 'django.contrib.admin.views.main.change_stage', args=[app_label, model_name, object_id] )
</code></pre>
<p>to get the url.</p>
<p>As you might have guessed, I'm trying to update to the latest version of Django, and this is one of the obstacles I came across, that method for getting the admin url doesn't work anymore.</p>
<p>How can I do this in django 1.0? (or 1.1 for that matter, as I'm trying to update to the latest version in the svn).</p> | <p>I had a similar issue where I would try to call <code>reverse('admin_index')</code> and was constantly getting <code>django.core.urlresolvers.NoReverseMatch</code> errors.</p>
<p>Turns out I had the old format admin urls in my urls.py file.</p>
<p>I had this in my urlpatterns:</p>
<pre><code>(r'^admin/(.*)', admin.site.root),
</code></pre>
<p>which gets the admin screens working but is the deprecated way of doing it. I needed to change it to this:</p>
<pre><code>(r'^admin/', include(admin.site.urls) ),
</code></pre>
<p>Once I did that, all the goodness that was promised in the <a href="https://docs.djangoproject.com/en/stable/ref/contrib/admin/#admin-reverse-urls" rel="nofollow noreferrer">Reversing Admin URLs</a> docs started working.</p> | {
"question_id": 694477,
"question_date": "2009-03-29T11:19:22.157Z",
"question_score": 214,
"tags": "django|django-admin|django-urls",
"answer_id": 850229,
"answer_date": "2009-05-11T21:40:14.190Z",
"answer_score": 65
} |
Please answer the following Stack Overflow question:
Title: Adding up BigDecimals using Streams
<p>I have a collection of BigDecimals (in this example, a <code>LinkedList</code>) that I would like to add together. Is it possible to use streams for this?</p>
<p>I noticed the <code>Stream</code> class has several methods</p>
<pre><code>Stream::mapToInt
Stream::mapToDouble
Stream::mapToLong
</code></pre>
<p>Each of which has a convenient <code>sum()</code> method. But, as we know, <code>float</code> and <code>double</code> arithmetic is almost always a bad idea.</p>
<p>So, is there a convenient way to sum up BigDecimals?</p>
<p>This is the code I have so far.</p>
<pre><code>public static void main(String[] args) {
LinkedList<BigDecimal> values = new LinkedList<>();
values.add(BigDecimal.valueOf(.1));
values.add(BigDecimal.valueOf(1.1));
values.add(BigDecimal.valueOf(2.1));
values.add(BigDecimal.valueOf(.1));
// Classical Java approach
BigDecimal sum = BigDecimal.ZERO;
for(BigDecimal value : values) {
System.out.println(value);
sum = sum.add(value);
}
System.out.println("Sum = " + sum);
// Java 8 approach
values.forEach((value) -> System.out.println(value));
System.out.println("Sum = " + values.stream().mapToDouble(BigDecimal::doubleValue).sum());
System.out.println(values.stream().mapToDouble(BigDecimal::doubleValue).summaryStatistics().toString());
}
</code></pre>
<p>As you can see, I am summing up the BigDecimals using <code>BigDecimal::doubleValue()</code>, but this is (as expected) not precise.</p>
<p><strong>Post-answer edit for posterity:</strong></p>
<p>Both answers were extremely helpful. I wanted to add a little: my real-life scenario does not involve a collection of raw <code>BigDecimal</code>s, they are wrapped in an invoice. But, I was able to modify Aman Agnihotri's answer to account for this by using the <code>map()</code> function for stream:</p>
<pre><code>public static void main(String[] args) {
LinkedList<Invoice> invoices = new LinkedList<>();
invoices.add(new Invoice("C1", "I-001", BigDecimal.valueOf(.1), BigDecimal.valueOf(10)));
invoices.add(new Invoice("C2", "I-002", BigDecimal.valueOf(.7), BigDecimal.valueOf(13)));
invoices.add(new Invoice("C3", "I-003", BigDecimal.valueOf(2.3), BigDecimal.valueOf(8)));
invoices.add(new Invoice("C4", "I-004", BigDecimal.valueOf(1.2), BigDecimal.valueOf(7)));
// Classical Java approach
BigDecimal sum = BigDecimal.ZERO;
for(Invoice invoice : invoices) {
BigDecimal total = invoice.unit_price.multiply(invoice.quantity);
System.out.println(total);
sum = sum.add(total);
}
System.out.println("Sum = " + sum);
// Java 8 approach
invoices.forEach((invoice) -> System.out.println(invoice.total()));
System.out.println("Sum = " + invoices.stream().map((x) -> x.total()).reduce((x, y) -> x.add(y)).get());
}
static class Invoice {
String company;
String invoice_number;
BigDecimal unit_price;
BigDecimal quantity;
public Invoice() {
unit_price = BigDecimal.ZERO;
quantity = BigDecimal.ZERO;
}
public Invoice(String company, String invoice_number, BigDecimal unit_price, BigDecimal quantity) {
this.company = company;
this.invoice_number = invoice_number;
this.unit_price = unit_price;
this.quantity = quantity;
}
public BigDecimal total() {
return unit_price.multiply(quantity);
}
public void setUnit_price(BigDecimal unit_price) {
this.unit_price = unit_price;
}
public void setQuantity(BigDecimal quantity) {
this.quantity = quantity;
}
public void setInvoice_number(String invoice_number) {
this.invoice_number = invoice_number;
}
public void setCompany(String company) {
this.company = company;
}
public BigDecimal getUnit_price() {
return unit_price;
}
public BigDecimal getQuantity() {
return quantity;
}
public String getInvoice_number() {
return invoice_number;
}
public String getCompany() {
return company;
}
}
</code></pre> | <h2>Original answer</h2>
<p>Yes, this is possible:</p>
<pre><code>List<BigDecimal> bdList = new ArrayList<>();
//populate list
BigDecimal result = bdList.stream()
.reduce(BigDecimal.ZERO, BigDecimal::add);
</code></pre>
<p>What it does is:</p>
<ol>
<li>Obtain a <code>List<BigDecimal></code>.</li>
<li>Turn it into a <code>Stream<BigDecimal></code></li>
<li><p>Call the reduce method.</p>
<p>3.1. We supply an identity value for addition, namely <code>BigDecimal.ZERO</code>.</p>
<p>3.2. We specify the <code>BinaryOperator<BigDecimal></code>, which adds two <code>BigDecimal</code>'s, via a method reference <code>BigDecimal::add</code>.</p></li>
</ol>
<h2>Updated answer, after edit</h2>
<p>I see that you have added new data, therefore the new answer will become:</p>
<pre><code>List<Invoice> invoiceList = new ArrayList<>();
//populate
Function<Invoice, BigDecimal> totalMapper = invoice -> invoice.getUnit_price().multiply(invoice.getQuantity());
BigDecimal result = invoiceList.stream()
.map(totalMapper)
.reduce(BigDecimal.ZERO, BigDecimal::add);
</code></pre>
<p>It is mostly the same, except that I have added a <code>totalMapper</code> variable, that has a function from <code>Invoice</code> to <code>BigDecimal</code> and returns the total price of that invoice.</p>
<p>Then I obtain a <code>Stream<Invoice></code>, map it to a <code>Stream<BigDecimal></code> and then reduce it to a <code>BigDecimal</code>.</p>
<p>Now, from an OOP design point I would advice you to also actually use the <code>total()</code> method, which you have already defined, then it even becomes easier:</p>
<pre><code>List<Invoice> invoiceList = new ArrayList<>();
//populate
BigDecimal result = invoiceList.stream()
.map(Invoice::total)
.reduce(BigDecimal.ZERO, BigDecimal::add);
</code></pre>
<p>Here we directly use the method reference in the <code>map</code> method.</p> | {
"question_id": 22635945,
"question_date": "2014-03-25T13:22:36.417Z",
"question_score": 214,
"tags": "java|bigdecimal|java-8|java-stream",
"answer_id": 22636014,
"answer_date": "2014-03-25T13:25:15.403Z",
"answer_score": 421
} |
Please answer the following Stack Overflow question:
Title: Attempt to set a non-property-list object as an NSUserDefaults
<p>I thought I knew what was causing this error, but I can't seem to figure out what I did wrong.</p>
<p>Here is the full error message I am getting:</p>
<pre>
Attempt to set a non-property-list object (
"<BC_Person: 0x8f3c140>"
) as an NSUserDefaults value for key personDataArray
</pre>
<p>I have a <code>Person</code> class that I think is conforming to the <code>NSCoding</code> protocol, where I have both of these methods in my person class:</p>
<pre><code>- (void)encodeWithCoder:(NSCoder *)coder {
[coder encodeObject:self.personsName forKey:@"BCPersonsName"];
[coder encodeObject:self.personsBills forKey:@"BCPersonsBillsArray"];
}
- (id)initWithCoder:(NSCoder *)coder {
self = [super init];
if (self) {
self.personsName = [coder decodeObjectForKey:@"BCPersonsName"];
self.personsBills = [coder decodeObjectForKey:@"BCPersonsBillsArray"];
}
return self;
}
</code></pre>
<p>At some point in the app, the <code>NSString</code> in the <code>BC_PersonClass</code> is set, and I have a <code>DataSave</code> class that I think is handling the encoding the properties in my <code>BC_PersonClass</code>.
Here is the code I am using from the <code>DataSave</code> class:</p>
<pre><code>- (void)savePersonArrayData:(BC_Person *)personObject
{
// NSLog(@"name of the person %@", personObject.personsName);
[mutableDataArray addObject:personObject];
// set the temp array to the mutableData array
tempMuteArray = [NSMutableArray arrayWithArray:mutableDataArray];
// save the person object as nsData
NSData *personEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:personObject];
// first add the person object to the mutable array
[tempMuteArray addObject:personEncodedObject];
// NSLog(@"Objects in the array %lu", (unsigned long)mutableDataArray.count);
// now we set that data array to the mutable array for saving
dataArray = [[NSArray alloc] initWithArray:mutableDataArray];
//dataArray = [NSArray arrayWithArray:mutableDataArray];
// save the object to NS User Defaults
NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
[userData setObject:dataArray forKey:@"personDataArray"];
[userData synchronize];
}
</code></pre>
<p>I hope this is enough code to give you an idea o what I am trying to do.
Again I know my problem lie with how I am encoding my properties in my BC_Person class, I just can't seem to figure out what though I'm doing wrong.</p>
<p>Thanks for the help!</p> | <p>The code you posted tries to save an array of custom objects to <code>NSUserDefaults</code>. You can't do that. Implementing the <code>NSCoding</code> methods doesn't help. You can only store things like <code>NSArray</code>, <code>NSDictionary</code>, <code>NSString</code>, <code>NSData</code>, <code>NSNumber</code>, and <code>NSDate</code> in <code>NSUserDefaults</code>.</p>
<p>You need to convert the object to <code>NSData</code> (like you have in some of the code) and store that <code>NSData</code> in <code>NSUserDefaults</code>. You can even store an <code>NSArray</code> of <code>NSData</code> if you need to.</p>
<p>When you read back the array you need to unarchive the <code>NSData</code> to get back your <code>BC_Person</code> objects.</p>
<p>Perhaps you want this:</p>
<pre><code>- (void)savePersonArrayData:(BC_Person *)personObject {
[mutableDataArray addObject:personObject];
NSMutableArray *archiveArray = [NSMutableArray arrayWithCapacity:mutableDataArray.count];
for (BC_Person *personObject in mutableDataArray) {
NSData *personEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:personObject];
[archiveArray addObject:personEncodedObject];
}
NSUserDefaults *userData = [NSUserDefaults standardUserDefaults];
[userData setObject:archiveArray forKey:@"personDataArray"];
}
</code></pre> | {
"question_id": 19720611,
"question_date": "2013-11-01T04:05:32.413Z",
"question_score": 214,
"tags": "ios|objective-c|encoding|nsuserdefaults",
"answer_id": 19720674,
"answer_date": "2013-11-01T04:13:56.177Z",
"answer_score": 284
} |
Please answer the following Stack Overflow question:
Title: Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat
<p>If I run <code>gradle assembleDebug</code> from the command line, I am suddenly getting this error:</p>
<pre><code>UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dx.util.DexException: Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat$AccessibilityServiceInfoVersionImpl;
at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:592)
at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:550)
at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:531)
at com.android.dx.merge.DexMerger.mergeDexBuffers(DexMerger.java:168)
at com.android.dx.merge.DexMerger.merge(DexMerger.java:186)
at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:300)
at com.android.dx.command.dexer.Main.run(Main.java:232)
at com.android.dx.command.dexer.Main.main(Main.java:174)
at com.android.dx.command.Main.main(Main.java:91)
</code></pre>
<p>If I grep for v4 I see two files inside my build folder.</p>
<pre><code>Binary file build/pre-dexed/debug/support-v4-19.0.0-2ba5fdd60a6c3836b3104a863fe42897da1fa9d1.jar matches
Binary file build/pre-dexed/debug/support-v4-r7-227d905d79b23b20866531d4f700446c040a2ccb.jar matches
</code></pre>
<p>My gradle file includes only this support library:</p>
<pre><code>compile 'com.android.support:support-v13:19.0.0'
</code></pre>
<p>I am stumped as to how the r7 library is included somehow. I've run <code>gradle clean</code> and it always appears there when I rerun assembleDebug.</p>
<p>If I grep for r7 inside the build directory, I see it inside the file: </p>
<pre><code>Binary file build/exploded-bundles/ComGoogleAndroidGmsPlayServices4030.aar/classes.jar matches
</code></pre>
<p>If I don't include v13, then other things don't compile.</p>
<p>But doesn't v13 include v4 support library?</p>
<p>Is this an incompatibility between play services AAR bundle and the v13 library?</p>
<p>I grabbed the gradle file from gradleplease.appspot.com.</p>
<p>Removing play services does not fix it; same error.</p>
<p>My dependencies inside build.gradle:</p>
<pre><code> dependencies {
// Google Play Services
//compile 'com.google.android.gms:play-services:4.0.30'
// Support Libraries
//compile 'com.android.support:support-v4:19.0.0'
///compile 'com.android.support:appcompat-v7:19.0.0'
//compile 'com.android.support:gridlayout-v7:19.0.0'
compile 'com.android.support:support-v13:19.0.0'
compile 'org.eclipse.mylyn.github:org.eclipse.egit.github.core:2.1.5'
compile 'commons-codec:commons-codec:1.9'
compile 'com.madgag:markdownj-core:0.4.1'
compile 'com.wu-man:android-oauth-client:0.0.2'
compile 'com.google.http-client:google-http-client-jackson2:1.17.0-rc'
compile 'org.apache.commons:commons-lang3:3.2'
compile 'com.google.code.gson:gson:2.2.4'
}
</code></pre> | <p>Run <strong><code>gradle -q dependencies</code></strong> (or <strong><code>gradle -q :projectName:dependencies</code></strong>) to generate a dependency report. You should see where <code>r7</code> is coming from, such as:</p>
<pre><code>compile - Classpath for compiling the main sources.
+--- com.commonsware.cwac:camera-v9:0.5.4
| +--- com.actionbarsherlock:actionbarsherlock:4.4.0
| | \--- com.google.android:support-v4:r7
| +--- com.commonsware.cwac:camera:0.5.4
| \--- com.android.support:support-v4:18.0.+ -> 18.0.0
\--- com.android.support:support-v4:18.0.+ -> 18.0.0
</code></pre>
<p>Then, use the <code>exclude</code> directive to block that dependency. In my case, it is coming from my CWAC-Camera library, and so I use:</p>
<pre><code>dependencies {
compile('com.commonsware.cwac:camera-v9:0.5.4') {
exclude module: 'support-v4'
}
compile 'com.android.support:support-v4:18.0.+'
}
</code></pre>
<p>(where the second <code>compile</code> statement indicates what version you actually want)</p>
<p>That should clear matters up, as you will see if you run the dependency report again:</p>
<pre><code>compile - Classpath for compiling the main sources.
+--- com.commonsware.cwac:camera-v9:0.5.4
| +--- com.actionbarsherlock:actionbarsherlock:4.4.0
| \--- com.commonsware.cwac:camera:0.5.4
\--- com.android.support:support-v4:18.0.+ -> 18.0.0
</code></pre> | {
"question_id": 20989317,
"question_date": "2014-01-08T07:20:45.763Z",
"question_score": 214,
"tags": "android|gradle|android-support-library|android-gradle-plugin",
"answer_id": 21100040,
"answer_date": "2014-01-13T19:47:19.713Z",
"answer_score": 305
} |
Please answer the following Stack Overflow question:
Title: Observable.of is not a function
<p>I am having issue with importing <code>Observable.of</code> function in my project. My Intellij sees everything. In my code I have:</p>
<pre><code>import {Observable} from 'rxjs/Observable';
</code></pre>
<p>and in my code I use it like that:</p>
<pre><code>return Observable.of(res);
</code></pre>
<p>Any ideas?</p> | <p>Actually I have imports messed up. In latest version of RxJS we can import it like that:</p>
<pre><code>import 'rxjs/add/observable/of';
</code></pre> | {
"question_id": 36568388,
"question_date": "2016-04-12T09:00:40.630Z",
"question_score": 214,
"tags": "angular|rxjs",
"answer_id": 36568586,
"answer_date": "2016-04-12T09:08:28.353Z",
"answer_score": 238
} |
Please answer the following Stack Overflow question:
Title: jQuery Ajax calls and the Html.AntiForgeryToken()
<p>I have implemented in my app the mitigation to <a href="https://en.wikipedia.org/wiki/Cross-site_request_forgery" rel="nofollow noreferrer">CSRF attacks</a> following the informations that I have read on some blog post around the internet. In particular these post have been the driver of my implementation</p>
<ul>
<li><a href="https://web.archive.org/web/20160301164154/http://blogs.msdn.com:80/b/aspnetue/archive/2010/09/17/second_2d00_post.aspx" rel="nofollow noreferrer">Best Practices for ASP.NET MVC</a> from the ASP.NET and Web Tools Developer Content Team</li>
<li><a href="https://haacked.com/archive/2009/04/02/anatomy-of-csrf-attack.aspx/" rel="nofollow noreferrer">Anatomy of a Cross-site Request Forgery Attack</a> from Phil Haack blog</li>
<li><a href="http://davidhayden.com/blog/dave/archive/2009/04/29/AntiForgeryTokenInMVCFramework.aspx" rel="nofollow noreferrer">AntiForgeryToken in the ASP.NET MVC Framework - Html.AntiForgeryToken and ValidateAntiForgeryToken Attribute</a> from David Hayden blog</li>
</ul>
<p>Basically those articles and recommendations says that to prevent the CSRF attack anybody should implement the following code:</p>
<ol>
<li><p>Add the <code>[ValidateAntiForgeryToken]</code> on every action that accept the POST Http verb</p>
<p>[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SomeAction( SomeModel model ) {
}</p>
</li>
<li><p>Add the <code><%= Html.AntiForgeryToken() %></code> helper inside forms that submits data to the server</p>
</li>
</ol>
<p>Anyway in some parts of my app I am doing Ajax POSTs with jQuery to the server without having any form at all. This happens for example where I am letting the user to click on an image to do a specific action.</p>
<p>Suppose I have a table with a list of activities. I have an image on a column of the table that says "Mark activity as completed" and when the user click on that activity I am doing the Ajax POST as in the following sample:</p>
<pre><code>$("a.markAsDone").click(function (event) {
event.preventDefault();
$.ajax({
type: "post",
dataType: "html",
url: $(this).attr("rel"),
data: {},
success: function (response) {
// ....
}
});
});
</code></pre>
<p>How can I use the <code><%= Html.AntiForgeryToken() %></code> in these cases? Should I include the helper call inside the data parameter of the Ajax call?</p>
<p>Sorry for the long post and thanks very much for helping out</p>
<p><strong>EDIT</strong>:</p>
<p>As per <a href="https://stackoverflow.com/questions/4074199/jquery-ajax-calls-and-the-html-antiforgerytoken/4074289#4074289">jayrdub</a> answer I have used in the following way</p>
<pre><code>$("a.markAsDone").click(function (event) {
event.preventDefault();
$.ajax({
type: "post",
dataType: "html",
url: $(this).attr("rel"),
data: {
AddAntiForgeryToken({}),
id: parseInt($(this).attr("title"))
},
success: function (response) {
// ....
}
});
});
</code></pre> | <p>I use a simple js function like this</p>
<pre><code>AddAntiForgeryToken = function(data) {
data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
return data;
};
</code></pre>
<p>Since every form on a page will have the same value for the token, just put something like this in your top-most master page</p>
<pre><code><%-- used for ajax in AddAntiForgeryToken() --%>
<form id="__AjaxAntiForgeryForm" action="#" method="post"><%= Html.AntiForgeryToken()%></form>
</code></pre>
<p>Then in your ajax call do (edited to match your second example)</p>
<pre><code>$.ajax({
type: "post",
dataType: "html",
url: $(this).attr("rel"),
data: AddAntiForgeryToken({ id: parseInt($(this).attr("title")) }),
success: function (response) {
// ....
}
});
</code></pre> | {
"question_id": 4074199,
"question_date": "2010-11-02T00:39:14.680Z",
"question_score": 214,
"tags": "asp.net-mvc|ajax|asp.net-mvc-2|csrf|antiforgerytoken",
"answer_id": 4074289,
"answer_date": "2010-11-02T01:14:02.450Z",
"answer_score": 261
} |
Please answer the following Stack Overflow question:
Title: Maven dependencies are failing with a 501 error
<p>Recently <em>Maven</em> build jobs running in <em>Jenkins</em> are failing with the below exception saying that they couldn't pull dependencies from <em>Maven Central</em> and should use <em>HTTPS</em>. I'm not sure how to change the requests from <em>HTTP</em> to <em>HTTPS</em>. Could someone guide me on this matter?</p>
<blockquote>
<p>[ERROR] Unresolveable build extension:<br />
Plugin <code>org.apache.maven.wagon:wagon-ssh:2.1</code> or one of its dependencies could not be resolved:<br />
Failed to collect dependencies for <code>org.apache.maven.wagon:wagon-ssh:jar:2.1 ()</code>:<br />
Failed to read artifact descriptor for <code>org.apache.maven.wagon:wagon-ssh:jar:2.1</code>:<br />
Could not transfer artifact <code>org.apache.maven.wagon:wagon-ssh:pom:2.1</code> from/to central (<a href="http://repo.maven.apache.org/maven2" rel="noreferrer">http://repo.maven.apache.org/maven2</a>):<br />
Failed to transfer file: <a href="http://repo.maven.apache.org/maven2/org/apache/maven/wagon/wagon-ssh/2.1/wagon-ssh-2.1.pom" rel="noreferrer">http://repo.maven.apache.org/maven2/org/apache/maven/wagon/wagon-ssh/2.1/wagon-ssh-2.1.pom</a>.<br />
Return code is: <code>501, ReasonPhrase:HTTPS Required. -> [Help 2]</code></p>
<p>Waiting for <em>Jenkins</em> to finish collecting <code>data[ERROR]</code><br />
Plugin <code>org.apache.maven.plugins:maven-clean-plugin:2.4.1</code> or one of its dependencies could not be resolved:<br />
Failed to read artifact descriptor for <code>org.apache.maven.plugins:maven-clean-plugin:jar:2.4.1</code>:<br />
Could not transfer artifact <code>org.apache.maven.plugins:maven-clean-plugin:pom:2.4.1</code> from/to central (<a href="http://repo.maven.apache.org/maven2" rel="noreferrer">http://repo.maven.apache.org/maven2</a>):<br />
Failed to transfer file: <a href="http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-clean-plugin/2.4.1/maven-clean-plugin-2.4.1.pom" rel="noreferrer">http://repo.maven.apache.org/maven2/org/apache/maven/plugins/maven-clean-plugin/2.4.1/maven-clean-plugin-2.4.1.pom</a>.<br />
Return code is: <code>501 , ReasonPhrase:HTTPS Required. -> [Help 1]</code></p>
</blockquote> | <p>The reason for the observed error is explained in <em><a href="https://support.sonatype.com/hc/en-us/articles/360041287334" rel="noreferrer">Central 501 HTTPS Required</a></em></p>
<blockquote>
<p>Effective January 15, 2020, The Central Repository no longer supports
insecure communication over plain HTTP and requires that all requests
to the repository are encrypted over HTTPS.</p>
</blockquote>
<p>It looks like latest versions of Maven (tried with 3.6.0, 3.6.1) are already using the HTTPS URL by default.</p>
<p>Here are the dates when the major repositories will switch:</p>
<p><em><a href="https://www.alphabot.com/security/blog/2020/java/Your-Java-builds-might-break-starting-January-13th.html" rel="noreferrer">Your Java builds might break starting January 13th (if you haven't yet switched repo access to HTTPS)</a></em></p>
<p>Update: Seems like from maven 3.2.3 maven central is accessed via HTTPS
See <a href="https://stackoverflow.com/a/25411658/5820670">https://stackoverflow.com/a/25411658/5820670</a></p>
<p>Maven Change log
(<a href="http://maven.apache.org/docs/3.2.3/release-notes.html" rel="noreferrer">http://maven.apache.org/docs/3.2.3/release-notes.html</a>)</p> | {
"question_id": 59763531,
"question_date": "2020-01-16T05:31:52.600Z",
"question_score": 214,
"tags": "java|maven|jenkins|maven-central",
"answer_id": 59764670,
"answer_date": "2020-01-16T07:19:28.323Z",
"answer_score": 173
} |
Please answer the following Stack Overflow question:
Title: OAuth: how to test with local URLs?
<p>I am trying to test <a href="https://en.wikipedia.org/wiki/OAuth" rel="noreferrer">OAuth</a> buttons, but they all (Facebook, Twitter, LinkedIn) come back with errors that seem to signal that I can not test or use them from a <em>local</em> URL.</p>
<p>How do people usually work in development with OAuth stuff if they all seem to require a <em>non-dev</em> and <em>non-local</em> connections environments?</p> | <p><strong>Update October 2016</strong>: Easiest now: use <a href="http://lvh.me" rel="noreferrer">lvh.me</a> which always points to <code>127.0.0.1</code>, but make sure to verify that this is still true every time you need to invoke it (because domains can expire or get taken over, and DNS poisoning is always a concern)</p>
<p><strong>Previous Answer</strong>:</p>
<p>Since the callback request is issued by the browser, as a HTTP redirect response, you can set up your .hosts file or equivalent to point a domain that is not <code>localhost</code> to 127.0.0.1.</p>
<p>Say for example you register the following callback with Twitter: <code>http://www.publicdomain.com/callback/</code>. Make sure that <code>www.publicdomain.com</code> points to 127.0.0.1 in your hosts file, AND that twitter can do a successful DNS lookup on <a href="http://www.publicdomain.com" rel="noreferrer">www.publicdomain.com</a>, i.e the domain needs to exist and the specific callback should probably return a 200 status message if requested.</p>
<p><strong>EDIT</strong>:</p>
<p>I just read the following article: <a href="https://web.archive.org/web/20171219093121/www.tonyamoyal.com/2009/08/17/how-to-quickly-set-up-a-test-for-twitter-oauth-authentication-from-your-local-machine/" rel="noreferrer">http://www.tonyamoyal.com/2009/08/17/how-to-quickly-set-up-a-test-for-twitter-oauth-authentication-from-your-local-machine</a>, which was linked to from this question: <a href="https://stackoverflow.com/questions/800827/twitter-oauth-callbackurl-localhost-development">Twitter oAuth callbackUrl - localhost development</a>.</p>
<p>To quote the article:</p>
<blockquote>
<p>You can use bit.ly, a URL shortening service. Just shorten the [localhost URL such as http//localhost:8080/twitter_callback] and register the shortened URL as the callback in your Twitter app.</p>
</blockquote>
<p>This should be easier than fiddling around in the .hosts file.</p>
<p>Note that now (Aug '14) bit.ly is not allowing link forwarding to localhost; however Google link shortener works.</p>
<p>PS edit: (Nov '18): Google link shortener stopped giving support for localhost or 127.0.0.1.</p> | {
"question_id": 10456174,
"question_date": "2012-05-04T21:10:16.370Z",
"question_score": 214,
"tags": "oauth|localhost",
"answer_id": 10459981,
"answer_date": "2012-05-05T07:56:47.880Z",
"answer_score": 157
} |
Please answer the following Stack Overflow question:
Title: How do I add an existing Solution to GitHub from Visual Studio 2013
<p>I have looked through many web pages on the new Git integration in VS 2013 and they do not deal with adding an existing solution to Github. In fact I can't find much on using GitHub instead of Visual Studio Online.</p>
<p>Can anyone tell me how I start from an existing solution and add it to Github using the tools in VS 2013.</p> | <p>OK this worked for me.</p>
<ol>
<li>Open the solution in Visual Studio 2013</li>
<li>Select File | Add to Source Control</li>
<li>Select the Microsoft Git Provider</li>
</ol>
<p>That creates a local GIT repository</p>
<ol start="3">
<li>Surf to GitHub</li>
<li>Create a new repository DO NOT SELECT Initialize this repository with a README </li>
</ol>
<p>That creates an empty repository with no Master branch</p>
<ol>
<li>Once created open the repository and copy the URL (it's on the right of the screen in the current version)</li>
<li>Go back to Visual Studio
<ul>
<li>Make sure you have the Microsoft Git Provider selected under Tools/Options/Source Control/Plug-in Selection</li>
</ul></li>
<li>Open Team Explorer</li>
<li>Select Home | Unsynced Commits</li>
<li>Enter the GitHub URL into the yellow box (use HTTPS URL, not the default shown SSH one)</li>
<li>Click Publish</li>
<li>Select Home | Changes</li>
<li>Add a Commit comment</li>
<li>Select Commit and Push from the drop down</li>
</ol>
<p>Your solution is now in GitHub</p> | {
"question_id": 19982053,
"question_date": "2013-11-14T15:46:28.417Z",
"question_score": 214,
"tags": "git|github|visual-studio-2013",
"answer_id": 20004092,
"answer_date": "2013-11-15T15:05:52.983Z",
"answer_score": 354
} |
Please answer the following Stack Overflow question:
Title: Difference between a User and a Login in SQL Server
<p>I have recently been running into many different areas of SQL Server that I normally don't mess with. One of them that has me confused is the area of Logins and Users. Seems like it should be a pretty simple topic...</p>
<p>It appears that each login can only have 1 user and each user can only have 1 login. </p>
<p>A login can be associated to multiple tables thus associating that user to many tables. </p>
<p>So my question is why even have a login and a user? they seem to be pretty much one in the same. What are the differences, or what is it that I seem to be missing?</p> | <p>A "Login" grants the principal entry into the SERVER.</p>
<p>A "User" grants a login entry into a single DATABASE.</p>
<p>One "Login" can be associated with many users (one per database).</p>
<p>Each of the above objects can have permissions granted to it at its own level. See the following articles for an explanation of each</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms181127(SQL.90).aspx" rel="noreferrer">Principals</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms190928(SQL.90).aspx" rel="noreferrer">Database Users</a></li>
</ul> | {
"question_id": 1134319,
"question_date": "2009-07-15T21:55:25.073Z",
"question_score": 214,
"tags": "sql|sql-server|sql-server-2005",
"answer_id": 1134357,
"answer_date": "2009-07-15T22:01:31.660Z",
"answer_score": 237
} |
Please answer the following Stack Overflow question:
Title: When do I need to use a semicolon vs a slash in Oracle SQL?
<p>We have been having some debate this week at my company as to how we should write our SQL scripts. </p>
<p>Background:
Our database is Oracle 10g (upgrading to 11 soon). Our DBA team uses SQLPlus in order to deploy our scripts to production.</p>
<p>Now, we had a deploy recently that failed because it had used both a semicolon and a forward slash (<code>/</code>). The semicolon was at the end of each statement and the slash was between statements.</p>
<pre><code>alter table foo.bar drop constraint bar1;
/
alter table foo.can drop constraint can1;
/
</code></pre>
<p>There were some triggers being added later on in the script, some views created as well as some stored procedures. Having both the <code>;</code> and the <code>/</code> caused each statement to run twice causing errors (especially on the inserts, which needed to be unique).</p>
<p>In SQL Developer this does not happen, in TOAD this does not happen. If you run certain commands they will not work without the <code>/</code> in them.</p>
<p>In PL/SQL if you have a subprogram (DECLARE, BEGIN, END) the semicolon used will be considered as part of the subprogram, so you have to use the slash.</p>
<p>So my question is this: If your database is Oracle, what is the proper way to write your SQL script? Since you know that your DB is Oracle should you always use the <code>/</code>?</p> | <p>It's a matter of preference, but I prefer to see scripts that consistently use the slash - this way all "units" of work (creating a PL/SQL object, running a PL/SQL anonymous block, and executing a DML statement) can be picked out more easily by eye.</p>
<p>Also, if you eventually move to something like Ant for deployment it will simplify the definition of targets to have a consistent statement delimiter.</p> | {
"question_id": 1079949,
"question_date": "2009-07-03T15:57:50.593Z",
"question_score": 214,
"tags": "sql|oracle|sqlplus",
"answer_id": 1080204,
"answer_date": "2009-07-03T17:12:25.697Z",
"answer_score": 31
} |
Please answer the following Stack Overflow question:
Title: Create a hexadecimal colour based on a string with JavaScript
<p>I want to create a function that will accept any old string (will usually be a single word) and from that <em>somehow</em> generate a hexadecimal value between <code>#000000</code> and <code>#FFFFFF</code>, so I can use it as a colour for a HTML element. </p>
<p>Maybe even a shorthand hex value (e.g: <code>#FFF</code>) if that's less complicated. In fact, a colour from a 'web-safe' palette would be ideal.</p> | <p>Just porting over the Java from <a href="https://stackoverflow.com/questions/2464745/compute-hex-color-code-for-an-arbitrary-string">Compute hex color code for an arbitrary string</a> to Javascript:</p>
<pre><code>function hashCode(str) { // java String#hashCode
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
return hash;
}
function intToRGB(i){
var c = (i & 0x00FFFFFF)
.toString(16)
.toUpperCase();
return "00000".substring(0, 6 - c.length) + c;
}
</code></pre>
<p>To convert you would do:</p>
<pre><code>intToRGB(hashCode(your_string))
</code></pre> | {
"question_id": 3426404,
"question_date": "2010-08-06T17:55:06.683Z",
"question_score": 214,
"tags": "javascript|string|colors|hex",
"answer_id": 3426956,
"answer_date": "2010-08-06T19:11:51.350Z",
"answer_score": 232
} |
Please answer the following Stack Overflow question:
Title: Change default timeout for mocha
<p>If we have a unit test file my-spec.js and running with mocha: </p>
<pre><code>mocha my-spec.js
</code></pre>
<p>The default timeout will be 2000 ms. It can be overwritten for partial test with a command line parameter: </p>
<pre><code>mocha my-spec.js --timeout 5000
</code></pre>
<p>Is it possible to change the default timeout globally for all tests?
i.e. the default timeout value will be different from 2000 ms when you call:</p>
<pre><code>mocha my-spec.js
</code></pre> | <p>By default Mocha will read a file named <code>test/mocha.opts</code> that can contain command line arguments. So you could create such a file that contains:</p>
<pre><code>--timeout 5000
</code></pre>
<p>Whenever you run Mocha at the command line, it will read this file and set a timeout of 5 seconds by default.</p>
<p>Another way which may be better depending on your situation is to set it like this in a top level <code>describe</code> call in your test file:</p>
<pre><code>describe("something", function () {
this.timeout(5000);
// tests...
});
</code></pre>
<p>This would allow you to set a timeout only on a per-file basis.</p>
<p>You could use both methods if you want a global default of 5000 but set something different for some files.</p>
<hr>
<p>Note that you cannot generally use an arrow function if you are going to call <code>this.timeout</code> (or access any other member of <code>this</code> that Mocha sets for you). For instance, <strong>this will usually not work</strong>:</p>
<pre><code>describe("something", () => {
this.timeout(5000); //will not work
// tests...
});
</code></pre>
<p>This is because an arrow function takes <code>this</code> from the scope the function appears in. Mocha will call the function with a good value for <code>this</code> but that value is not passed inside the arrow function. The documentation for Mocha says on <a href="https://mochajs.org/#arrow-functions" rel="noreferrer">this topic</a>:</p>
<blockquote>
<p>Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context. </p>
</blockquote> | {
"question_id": 23492043,
"question_date": "2014-05-06T10:23:17.667Z",
"question_score": 214,
"tags": "javascript|unit-testing|mocha.js",
"answer_id": 23492442,
"answer_date": "2014-05-06T10:42:04.997Z",
"answer_score": 375
} |
Please answer the following Stack Overflow question:
Title: Is there a way to ignore a single FindBugs warning?
<p>With PMD, if you want to ignore a specific warning, you can use <code>// NOPMD</code> to have that line be ignored.</p>
<p>Is there something similar for FindBugs?</p> | <p>The FindBugs initial approach involves XML configuration files aka <a href="http://findbugs.sourceforge.net/manual/filter.html" rel="noreferrer">filters</a>. This is really less convenient than the PMD solution but FindBugs works on bytecode, not on the source code, so comments are obviously not an option. Example:</p>
<pre class="lang-xml prettyprint-override"><code><Match>
<Class name="com.mycompany.Foo" />
<Method name="bar" />
<Bug pattern="DLS_DEAD_STORE_OF_CLASS_LITERAL" />
</Match>
</code></pre>
<p>However, to solve this issue, FindBugs later introduced another solution based on <a href="http://findbugs.sourceforge.net/manual/annotations.html" rel="noreferrer">annotations</a> (see <a href="http://findbugs.sourceforge.net/api/edu/umd/cs/findbugs/annotations/SuppressFBWarnings.html" rel="noreferrer"><code>SuppressFBWarnings</code></a>) that you can use at the class or at the method level (more convenient than XML in my opinion). Example (maybe not the best one but, well, it's just an example):</p>
<pre><code>@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
value="HE_EQUALS_USE_HASHCODE",
justification="I know what I'm doing")
</code></pre>
<p>Note that since FindBugs 3.0.0 <code>SuppressWarnings</code> has been deprecated in favor of <code>@SuppressFBWarnings</code> because of the name clash with Java's <code>SuppressWarnings</code>.</p> | {
"question_id": 1829904,
"question_date": "2009-12-02T00:21:50.553Z",
"question_score": 214,
"tags": "java|warnings|findbugs|suppress-warnings",
"answer_id": 1829960,
"answer_date": "2009-12-02T00:34:33.163Z",
"answer_score": 336
} |
Please answer the following Stack Overflow question:
Title: What's the difference between subprocess Popen and call (how can I use them)?
<p>I want to call an external program from Python. I have used both <code>Popen()</code> and <code>call()</code> to do that. </p>
<p>What's the difference between the two?</p>
<p>My specific goal is to run the following command from Python. I am not sure how redirects work.</p>
<pre><code>./my_script.sh > output
</code></pre>
<p>I read <a href="http://docs.python.org/library/subprocess.html" rel="noreferrer">the documentation</a> and it says that <code>call()</code> is a convenience function or a shortcut function. Do we lose any power by using <code>call()</code> instead of <code>Popen()</code>?</p> | <p>There are two ways to do the redirect. Both apply to either <code>subprocess.Popen</code> or <code>subprocess.call</code>.</p>
<ol>
<li><p>Set the keyword argument <code>shell = True</code> or <code>executable = /path/to/the/shell</code> and specify the command just as you have it there.</p></li>
<li><p>Since you're just redirecting the output to a file, set the keyword argument</p>
<pre><code>stdout = an_open_writeable_file_object
</code></pre>
<p>where the object points to the <code>output</code> file.</p></li>
</ol>
<p><a href="http://docs.python.org/library/subprocess.html#subprocess.Popen" rel="noreferrer"><code>subprocess.Popen</code></a> is more general than <a href="http://docs.python.org/library/subprocess.html#subprocess.call" rel="noreferrer"><code>subprocess.call</code></a>.</p>
<p><code>Popen</code> doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to <code>Popen</code> returns a <code>Popen</code> object.</p>
<p><code>call</code> <em>does</em> block. While it supports all the same arguments as the <code>Popen</code> constructor, so you can still set the process' output, environmental variables, etc., your script waits for the program to complete, and <code>call</code> returns a code representing the process' exit status. </p>
<pre><code>returncode = call(*args, **kwargs)
</code></pre>
<p>is basically the same as calling </p>
<pre><code>returncode = Popen(*args, **kwargs).wait()
</code></pre>
<p><code>call</code> is just a convenience function. It's implementation in CPython is in <a href="http://hg.python.org/cpython/file/e0df7db13d55/Lib/subprocess.py#l459" rel="noreferrer">subprocess.py</a>:</p>
<pre><code>def call(*popenargs, timeout=None, **kwargs):
"""Run command with arguments. Wait for command to complete or
timeout, then return the returncode attribute.
The arguments are the same as for the Popen constructor. Example:
retcode = call(["ls", "-l"])
"""
with Popen(*popenargs, **kwargs) as p:
try:
return p.wait(timeout=timeout)
except:
p.kill()
p.wait()
raise
</code></pre>
<p>As you can see, it's a thin wrapper around <code>Popen</code>.</p> | {
"question_id": 7681715,
"question_date": "2011-10-06T23:44:34.483Z",
"question_score": 214,
"tags": "python|subprocess|popen",
"answer_id": 7681815,
"answer_date": "2011-10-06T23:59:09Z",
"answer_score": 303
} |
Please answer the following Stack Overflow question:
Title: ProcessStartInfo hanging on "WaitForExit"? Why?
<p>I have the following code:</p>
<pre><code>info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args));
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd()); //need the StandardOutput contents
</code></pre>
<p>I know that the output from the process I am starting is around 7MB long. Running it in the Windows console works fine. Unfortunately programmatically this hangs indefinitely at <code>WaitForExit</code>. Note also this code does NOT hang for smaller outputs (like 3KB).</p>
<p>Is it possible that the internal <code>StandardOutput</code> in <code>ProcessStartInfo</code> can't buffer 7MB? If so, what should I do instead? If not, what am I doing wrong?</p> | <p>The problem is that if you redirect <code>StandardOutput</code> and/or <code>StandardError</code> the internal buffer can become full. Whatever order you use, there can be a problem:</p>
<ul>
<li>If you wait for the process to exit before reading <code>StandardOutput</code> the process can block trying to write to it, so the process never ends.</li>
<li>If you read from <code>StandardOutput</code> using ReadToEnd then <em>your</em> process can block if the process never closes <code>StandardOutput</code> (for example if it never terminates, or if it is blocked writing to <code>StandardError</code>).</li>
</ul>
<p>The solution is to use asynchronous reads to ensure that the buffer doesn't get full. To avoid any deadlocks and collect up all output from both <code>StandardOutput</code> and <code>StandardError</code> you can do this:</p>
<p>EDIT: See answers below for how avoid an <strong>ObjectDisposedException</strong> if the timeout occurs.</p>
<pre><code>using (Process process = new Process())
{
process.StartInfo.FileName = filename;
process.StartInfo.Arguments = arguments;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
process.OutputDataReceived += (sender, e) => {
if (e.Data == null)
{
outputWaitHandle.Set();
}
else
{
output.AppendLine(e.Data);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
{
errorWaitHandle.Set();
}
else
{
error.AppendLine(e.Data);
}
};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
if (process.WaitForExit(timeout) &&
outputWaitHandle.WaitOne(timeout) &&
errorWaitHandle.WaitOne(timeout))
{
// Process completed. Check process.ExitCode here.
}
else
{
// Timed out.
}
}
}
</code></pre> | {
"question_id": 139593,
"question_date": "2008-09-26T13:46:56.390Z",
"question_score": 214,
"tags": "c#|processstartinfo",
"answer_id": 7608823,
"answer_date": "2011-09-30T10:05:02.207Z",
"answer_score": 453
} |
Please answer the following Stack Overflow question:
Title: ToList()-- does it create a new list?
<p>Let's say I have a class</p>
<pre><code>public class MyObject
{
public int SimpleInt{get;set;}
}
</code></pre>
<p>And I have a <code>List<MyObject></code>, and I <code>ToList()</code> it and then change one of the <code>SimpleInt</code>, will my change be propagated back to the original list. In other words, what would be the output of the following method?</p>
<pre><code>public void RunChangeList()
{
var objs = new List<MyObject>(){new MyObject(){SimpleInt=0}};
var whatInt = ChangeToList(objs );
}
public int ChangeToList(List<MyObject> objects)
{
var objectList = objects.ToList();
objectList[0].SimpleInt=5;
return objects[0].SimpleInt;
}
</code></pre>
<p>Why? </p>
<p>P/S: I'm sorry if it seems obvious to find out. But I don't have compiler with me now...</p> | <p>Yes, <code>ToList</code> will create a new list, but because in this case <code>MyObject</code> is a reference type then the new list will contain references to the same objects as the original list.</p>
<p>Updating the <code>SimpleInt</code> property of an object referenced in the new list will also affect the equivalent object in the original list.</p>
<p>(If <code>MyObject</code> was declared as a <code>struct</code> rather than a <code>class</code> then the new list would contain copies of the elements in the original list, and updating a property of an element in the new list would <em>not</em> affect the equivalent element in the original list.)</p> | {
"question_id": 2774099,
"question_date": "2010-05-05T14:29:21.727Z",
"question_score": 214,
"tags": "c#|linq",
"answer_id": 2774121,
"answer_date": "2010-05-05T14:32:04.117Z",
"answer_score": 257
} |
Please answer the following Stack Overflow question:
Title: Ordering of batch normalization and dropout?
<p><em>The original question was in regard to TensorFlow implementations specifically. However, the answers are for implementations in general. This general answer is also the correct answer for TensorFlow.</em></p>
<p>When using batch normalization and dropout in TensorFlow (specifically using the contrib.layers) do I need to be worried about the ordering?</p>
<p>It seems possible that if I use dropout followed immediately by batch normalization there might be trouble. For example, if the shift in the batch normalization trains to the larger scale numbers of the training outputs, but then that same shift is applied to the smaller (due to the compensation for having more outputs) scale numbers without dropout during testing, then that shift may be off. Does the TensorFlow batch normalization layer automatically compensate for this? Or does this not happen for some reason I'm missing?</p>
<p>Also, are there other pitfalls to look out for in when using these two together? For example, assuming I'm using them in the correct order in regards to the above (assuming there <em>is</em> a correct order), could there be trouble with using both batch normalization and dropout on multiple successive layers? I don't immediately see a problem with that, but I might be missing something.</p>
<p>Thank you much!</p>
<p><strong>UPDATE:</strong></p>
<p>An experimental test <em>seems</em> to suggest that ordering <em>does</em> matter. I ran the same network twice with only the batch norm and dropout reverse. When the dropout is before the batch norm, validation loss seems to be going up as training loss is going down. They're both going down in the other case. But in my case the movements are slow, so things may change after more training and it's just a single test. A more definitive and informed answer would still be appreciated.</p> | <p>In the <a href="https://arxiv.org/pdf/1502.03167.pdf" rel="noreferrer">Ioffe and Szegedy 2015</a>, the authors state that "we would like to ensure that for any parameter values, the network always produces activations with the desired distribution". So the Batch Normalization Layer is actually inserted right after a Conv Layer/Fully Connected Layer, but before feeding into ReLu (or any other kinds of) activation. See <a href="https://www.youtube.com/watch?v=jhUZ800C650&index=5&list=PLLvH2FwAQhnpj1WEB-jHmPuUeQ8mX-XXG" rel="noreferrer">this video</a> at around time 53 min for more details.</p>
<p>As far as dropout goes, I believe dropout is applied after activation layer. In the <a href="https://www.cs.toronto.edu/~hinton/absps/JMLRdropout.pdf" rel="noreferrer">dropout paper</a> figure 3b, the dropout factor/probability matrix r(l) for hidden layer l is applied to it on y(l), where y(l) is the result after applying activation function f. </p>
<p>So in summary, the order of using batch normalization and dropout is:</p>
<p>-> CONV/FC -> BatchNorm -> ReLu(or other activation) -> Dropout -> CONV/FC -></p> | {
"question_id": 39691902,
"question_date": "2016-09-25T21:12:23.370Z",
"question_score": 214,
"tags": "python|neural-network|tensorflow|conv-neural-network",
"answer_id": 40295999,
"answer_date": "2016-10-27T23:59:30.593Z",
"answer_score": 227
} |
Please answer the following Stack Overflow question:
Title: What does #defining WIN32_LEAN_AND_MEAN exclude exactly?
<p>I found the explanation defining <code>WIN32_LEAN_AND_MEAN</code> <em>"reduces the size of the Win32 header files by excluding some of the less frequently used APIs"</em>. Somewhere else I read that it speeds up the build process.</p>
<p>So what does <code>WIN32_LEAN_AND_MEAN</code> exclude exactly? Should I care about this pre-processor directive? Does it speed up the build process?</p>
<p>I've also seen a pre-processor directive in projects named something along the lines of extra lean. Is this another esoteric pre-processor incantation I should know about?</p> | <p>Directly from the Windows.h header file:</p>
<pre><code>#ifndef WIN32_LEAN_AND_MEAN
#include <cderr.h>
#include <dde.h>
#include <ddeml.h>
#include <dlgs.h>
#ifndef _MAC
#include <lzexpand.h>
#include <mmsystem.h>
#include <nb30.h>
#include <rpc.h>
#endif
#include <shellapi.h>
#ifndef _MAC
#include <winperf.h>
#include <winsock.h>
#endif
#ifndef NOCRYPT
#include <wincrypt.h>
#include <winefs.h>
#include <winscard.h>
#endif
#ifndef NOGDI
#ifndef _MAC
#include <winspool.h>
#ifdef INC_OLE1
#include <ole.h>
#else
#include <ole2.h>
#endif /* !INC_OLE1 */
#endif /* !MAC */
#include <commdlg.h>
#endif /* !NOGDI */
#endif /* WIN32_LEAN_AND_MEAN */
</code></pre>
<p>If you want to know what each of the headers actually do, typing the header names into the search in the <a href="http://msdn.microsoft.com/en-us/library/ms123401.aspx" rel="noreferrer">MSDN</a> library will usually produce a list of the functions in that header file.</p>
<p>Also, from <a href="http://web.archive.org/web/20121219084749/http://support.microsoft.com/kb/166474" rel="noreferrer">Microsoft's support page</a>:</p>
<blockquote>
<p>To speed the build process, Visual C++ and the Windows Headers provide
the following new defines:</p>
<pre><code>VC_EXTRALEAN
WIN32_LEAN_AND_MEAN
</code></pre>
<p>You can use them to reduce the size of the Win32 header files.</p>
</blockquote>
<p>Finally, if you choose to use either of these preprocessor defines, and something you need is missing, you can just include that specific header file yourself. Typing the name of the function you're after into MSDN will usually produce an entry which will tell you which header to include if you want to use it, at the bottom of the page.</p> | {
"question_id": 11040133,
"question_date": "2012-06-14T19:35:01.330Z",
"question_score": 214,
"tags": "windows|visual-c++",
"answer_id": 11040290,
"answer_date": "2012-06-14T19:45:49.603Z",
"answer_score": 199
} |
Please answer the following Stack Overflow question:
Title: How do I create ColorStateList programmatically?
<p>I am trying to create a <code>ColorStateList</code> programatically using this: </p>
<pre><code>ColorStateList stateList = new ColorStateList(states, colors);
</code></pre>
<p>But I am not sure what are the two parameters.</p>
<p>As per the documentation:</p>
<blockquote>
<pre><code>public ColorStateList (int[][] states, int[] colors)
</code></pre>
<p>Added in API level 1</p>
<p>Creates a ColorStateList that returns the specified mapping from states to colors. </p>
</blockquote>
<p>Can somebody please explain me how to create this?</p>
<p>What is the meaning of two-dimensional array for states?</p> | <p>See <a href="http://developer.android.com/reference/android/R.attr.html#state_above_anchor" rel="noreferrer">http://developer.android.com/reference/android/R.attr.html#state_above_anchor</a> for a list of available states.</p>
<p>If you want to set colors for disabled, unfocused, unchecked states etc. just negate the states:</p>
<pre><code>int[][] states = new int[][] {
new int[] { android.R.attr.state_enabled}, // enabled
new int[] {-android.R.attr.state_enabled}, // disabled
new int[] {-android.R.attr.state_checked}, // unchecked
new int[] { android.R.attr.state_pressed} // pressed
};
int[] colors = new int[] {
Color.BLACK,
Color.RED,
Color.GREEN,
Color.BLUE
};
ColorStateList myList = new ColorStateList(states, colors);
</code></pre> | {
"question_id": 15543186,
"question_date": "2013-03-21T09:04:55.017Z",
"question_score": 214,
"tags": "android|android-color",
"answer_id": 17788095,
"answer_date": "2013-07-22T12:52:01.627Z",
"answer_score": 409
} |
Please answer the following Stack Overflow question:
Title: App store link for "rate/review this app"
<p>I want to put a "rate/review this app" feature into my app.</p>
<p>Is there a way to link directly to the screen in the app store where they review the app? So the customer doesn't have to click through the main app link. Thanks.</p>
<p>EDIT: starting a bounty on this due to the lack of response. Just to make sure it is crystal clear: I am aware that I can link to my app's page in the store, and ask the user to click from there to the "review this app" screen. The question is whether it is possible to link directly to the "review this app" screen so they don't have to click through anything.</p> | <p><a href="https://github.com/arashpayan/appirater/blob/2.0.5/Appirater.m#L53" rel="noreferrer">For versions lower than iOS 7 use the old one:</a></p>
<pre><code>itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=YOUR_APP_ID
</code></pre>
<p><a href="https://github.com/arashpayan/appirater/blob/2.0.5/Appirater.m#L54" rel="noreferrer">This works on my end (Xcode 5 - iOS 7 - <strong>Device</strong>!):</a></p>
<pre><code>itms-apps://itunes.apple.com/app/idYOUR_APP_ID
</code></pre>
<p><a href="https://github.com/arashpayan/appirater/blob/2.0.5/Appirater.m#L55" rel="noreferrer">For iOS 8 or later:</a></p>
<pre><code>itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=YOUR_APP_ID&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software
</code></pre>
<p>Code snippet (you can just copy & paste it):</p>
<pre><code>#define YOUR_APP_STORE_ID 545174222 //Change this one to your ID
static NSString *const iOS7AppStoreURLFormat = @"itms-apps://itunes.apple.com/app/id%d";
static NSString *const iOSAppStoreURLFormat = @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%d";
[NSURL URLWithString:[NSString stringWithFormat:([[UIDevice currentDevice].systemVersion floatValue] >= 7.0f)? iOS7AppStoreURLFormat: iOSAppStoreURLFormat, YOUR_APP_STORE_ID]]; // Would contain the right link
</code></pre> | {
"question_id": 3124080,
"question_date": "2010-06-26T13:49:29.543Z",
"question_score": 214,
"tags": "iphone|app-store",
"answer_id": 3167015,
"answer_date": "2010-07-02T15:20:15.587Z",
"answer_score": 361
} |
Please answer the following Stack Overflow question:
Title: C multi-line macro: do/while(0) vs scope block
<blockquote>
<p><strong>Possible Duplicates:</strong><br>
<a href="https://stackoverflow.com/questions/923822/whats-the-use-of-do-while0-when-we-define-a-macro">What’s the use of do while(0) when we define a macro?</a><br>
<a href="https://stackoverflow.com/questions/154136/why-are-there-sometimes-meaningless-do-while-and-if-else-statements-in-c-c-macr">Why are there sometimes meaningless do/while and if/else statements in C/C++ macros? </a><br>
<a href="https://stackoverflow.com/questions/257418/do-while-0-what-is-it-good-for">do { … } while (0) what is it good for?</a> </p>
</blockquote>
<p>I've seen some multi-line C macros that are wrapped inside a do/while(0) loop like:</p>
<pre>
#define FOO \
do { \
do_stuff_here \
do_more_stuff \
} while (0)
</pre>
<p>What are the benefits (if any) of writing the code that way as opposed to using a basic block:</p>
<pre>
#define FOO \
{ \
do_stuff_here \
do_more_stuff \
}
</pre> | <p>Andrey Tarasevich provides the following explanation:</p>
<ol>
<li><a href="https://groups.google.com/g/comp.lang.c/c/xGZxls194mI/m/dEIpTKz2okMJ" rel="noreferrer">On Google Groups</a></li>
<li><a href="https://bytes.com/topic/c/answers/219859-do-while-0-macro-substitutions#post885394" rel="noreferrer">On bytes.com</a></li>
</ol>
<p>[Minor changes to formatting made. Parenthetical annotations added in square brackets <code>[]</code>].</p>
<blockquote>
<p>The whole idea of using 'do/while' version is to make a macro which will
expand into a regular statement, not into a compound statement. This is
done in order to make the use of function-style macros uniform with the
use of ordinary functions in all contexts.</p>
<p>Consider the following code sketch:</p>
<pre><code>if (<condition>)
foo(a);
else
bar(a);
</code></pre>
<p>where <code>foo</code> and <code>bar</code> are ordinary functions. Now imagine that you'd
like to replace function <code>foo</code> with a macro of the above nature [named <code>CALL_FUNCS</code>]:</p>
<pre><code>if (<condition>)
CALL_FUNCS(a);
else
bar(a);
</code></pre>
<p>Now, if your macro is defined in accordance with the second approach
(just <code>{</code> and <code>}</code>) the code will no longer compile, because the 'true'
branch of <code>if</code> is now represented by a compound statement. And when you
put a <code>;</code> after this compound statement, you finished the whole <code>if</code>
statement, thus orphaning the <code>else</code> branch (hence the compilation error).</p>
<p>One way to correct this problem is to remember not to put <code>;</code> after
macro "invocations":</p>
<pre><code>if (<condition>)
CALL_FUNCS(a)
else
bar(a);
</code></pre>
<p>This will compile and work as expected, but this is not uniform. The
more elegant solution is to make sure that macro expand into a regular
statement, not into a compound one. One way to achieve that is to define
the macro as follows:</p>
<pre><code>#define CALL_FUNCS(x) \
do { \
func1(x); \
func2(x); \
func3(x); \
} while (0)
</code></pre>
<p>Now this code:</p>
<pre><code>if (<condition>)
CALL_FUNCS(a);
else
bar(a);
</code></pre>
<p>will compile without any problems.</p>
<p>However, note the small but important difference between my definition
of <code>CALL_FUNCS</code> and the first version in your message. I didn't put a
<code>;</code> after <code>} while (0)</code>. Putting a <code>;</code> at the end of that definition
would immediately defeat the entire point of using 'do/while' and make
that macro pretty much equivalent to the compound-statement version.</p>
<p>I don't know why the author of the code you quoted in your original
message put this <code>;</code> after <code>while (0)</code>. In this form both variants are
equivalent. The whole idea behind using 'do/while' version is not to
include this final <code>;</code> into the macro (for the reasons that I explained
above).</p>
</blockquote> | {
"question_id": 1067226,
"question_date": "2009-07-01T04:06:35.837Z",
"question_score": 214,
"tags": "c|macros|multiline",
"answer_id": 1067238,
"answer_date": "2009-07-01T04:11:14.980Z",
"answer_score": 322
} |
Please answer the following Stack Overflow question:
Title: Undoing accidental git stash pop
<p>I stashed some local changes before doing a complicated merge, did the merge, then stupidly forgot to commit before running <code>git stash pop</code>. The pop created some problems (bad method calls in a big codebase) that are proving hard to track down. I ran <code>git stash show</code>, so I at least know which files were changed. If nothing else, I guess this is a lesson to commit more.</p>
<p>My question: is it possible to undo the stash pop without also undoing the merge? </p> | <p>Try using <a href="https://stackoverflow.com/questions/89332/recover-dropped-stash-in-git">How to recover a dropped stash in Git?</a> to find the stash you popped. I think there are always two commits for a stash, since it preserves the index and the working copy (so often the index commit will be empty). Then <code>git show</code> them to see the diff and use <code>patch -R</code> to unapply them.</p> | {
"question_id": 6543519,
"question_date": "2011-07-01T04:15:27.527Z",
"question_score": 214,
"tags": "git|git-stash",
"answer_id": 6543671,
"answer_date": "2011-07-01T04:44:42.297Z",
"answer_score": 77
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.