input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: What's the difference between 'extends' and 'implements' in TypeScript
<p>I would like to know what <em><strong>Man</strong></em> and <em><strong>Child</strong></em> have in common and how they differ.</p>
<pre class="lang-ts prettyprint-override"><code>class Person {
name: string;
age: number;
}
class Child extends Person {}
class Man implements Person {}
</code></pre> | <h3>Short version</h3>
<ul>
<li><strong><code>extends</code></strong> means:</li>
</ul>
<p>The <strong>new class is a child</strong>. It gets benefits coming with inheritance. It has all the properties and methods of its parent. It can override some of these and implement new ones, but the parent stuff is already included.</p>
<ul>
<li><strong><code>implements</code></strong> means:</li>
</ul>
<p>The <strong>new class</strong> can be treated as <strong>the same <em>"shape"</em></strong>, but <strong>it is not a child</strong>. It could be passed to any method where <code>Person</code> is required, regardless of having a different parent than <code>Person</code>.</p>
<h3>More ...</h3>
<p>In <a href="https://en.wikipedia.org/wiki/Object-oriented_programming" rel="noreferrer">OOP</a> (languages like C# or Java) we would use</p>
<p><strong><code>extends</code></strong> to profit from <a href="https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)" rel="noreferrer">inheritance</a>.</p>
<blockquote>
<p>... Inheritance in most class-based object-oriented languages is a mechanism in which one object acquires all the properties and behaviours of the parent object. Inheritance allows programmers to: create classes that are built upon existing classes ...</p>
</blockquote>
<p><strong><code>implements</code></strong> will be more for <a href="https://en.wikipedia.org/wiki/Polymorphism_(computer_science)" rel="noreferrer">polymorphism</a>.</p>
<blockquote>
<p>... polymorphism is the provision of a single interface to entities of different types...</p>
</blockquote>
<p>So we can have a completely different inheritance tree for our class <code>Man</code>:</p>
<pre><code>class Man extends Human ...
</code></pre>
<p>but if we also declare that <code>Man</code> can pretend to be the <code>Person</code> type:</p>
<pre><code>class Man extends Human
implements Person ...
</code></pre>
<p>...then we can use it anywhere <code>Person</code> is required. We just have to fulfil <code>Person</code>'s "interface" (i.e. implement all its public stuff).</p>
<h3><code>implement</code> other class? That is really cool stuff</h3>
<p>Javascript's nice face (one of the benefits) is built-in support for <a href="https://en.wikipedia.org/wiki/Duck_typing" rel="noreferrer">duck typing</a>.</p>
<blockquote>
<p>"If it walks like a duck and it quacks like a duck, then it must be a duck."</p>
</blockquote>
<p>So, in Javascript, if two different objects have one similar method (e.g. <code>render()</code>) they can be passed to a function which expects it:</p>
<pre><code>function(engine){
engine.render() // any type implementing render() can be passed
}
</code></pre>
<p>To not lose that in Typescript, we can do the same with more typed support. And that is where</p>
<pre><code>class implements class
</code></pre>
<p>has its role, where it makes sense.</p>
<p><em>In OOP languages as <code>C#</code>, no way to do that.</em></p>
<h3>The documentation should help here:</h3>
<blockquote>
<h1><a href="http://www.typescriptlang.org/docs/handbook/interfaces.html#interfaces-extending-classes" rel="noreferrer">Interfaces Extending Classes</a></h1>
<p>When an interface type extends a class type it inherits the members of
the class but not their implementations. It is as if the interface had
declared all of the members of the class without providing an
implementation. Interfaces inherit even the private and protected
members of a base class. This means that when you create an interface
that extends a class with private or protected members, that interface
type can only be implemented by that class or a subclass of it.</p>
<p>This is useful when you have a large inheritance hierarchy, but want
to specify that your code works with only subclasses that have certain
properties. The subclasses don’t have to be related besides inheriting
from the base class. For example:</p>
<pre><code>class Control {
private state: any;
}
interface SelectableControl extends Control {
select(): void;
}
class Button extends Control implements SelectableControl {
select() { }
}
class TextBox extends Control {
select() { }
}
// Error: Property 'state' is missing in type 'Image'.
class Image implements SelectableControl {
private state: any;
select() { }
}
class Location {
}
</code></pre>
</blockquote>
<p>So, while</p>
<ul>
<li><code>extends</code> means it gets all from its parent</li>
<li><code>implements</code> in this case it's almost like implementing an interface. A child object can pretend that it is its parent... but it does not get any implementation.</li>
</ul> | {
"question_id": 38834625,
"question_date": "2016-08-08T16:49:59.207Z",
"question_score": 223,
"tags": "typescript|extends|implements",
"answer_id": 38834997,
"answer_date": "2016-08-08T17:13:53.217Z",
"answer_score": 295
} |
Please answer the following Stack Overflow question:
Title: Absolute positioning ignoring padding of parent
<p>How do you make an absolute positioned element honor the padding of its parent? I want an inner div to stretch across the width of its parent and to be positioned at the bottom of that parent, basically a footer. But the child has to honor the padding of the parent and it's not doing that. The child is pressed right up against the edge of the parent.</p>
<p>So I want this:</p>
<p><img src="https://i.stack.imgur.com/PNk2V.png" alt="enter image description here" /></p>
<p>but I'm getting this:</p>
<p><img src="https://i.stack.imgur.com/ADkGU.png" alt="enter image description here" /></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <html>
<body>
<div style="background-color: blue; padding: 10px; position: relative; height: 100px;">
<div style="background-color: gray; position: absolute; left: 0px; right: 0px; bottom: 0px;">css sux</div>
</div>
</body>
</html></code></pre>
</div>
</div>
</p>
<p>I can make it happen with a margin around the inner div, but I'd prefer not to have to add that.</p> | <p>First, let's see <em>why</em> this is happening.</p>
<p>The reason is that, surprisingly, when a box has <code>position: absolute</code> its containing box is the parent's padding box (that is, the box around its padding). This is surprising because usually (that is, when using static or relative positioning) the containing box is the parent's <em>content</em> box.</p>
<p>Here is the <a href="http://www.w3.org/TR/CSS21/visudet.html#containing-block-details" rel="noreferrer">relevant part of the CSS specification</a>:</p>
<blockquote>
<p>In the case that the ancestor is an inline element, the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element.... Otherwise, the containing block is formed by the padding edge of the ancestor.</p>
</blockquote>
<p>The simplest approach—as suggested in Winter's answer—is to use <code>padding: inherit</code> on the absolutely positioned <code>div</code>. It only works, though, if you don't want the absolutely positioned <code>div</code> to have any additional padding of its own. I think the most general-purpose solutions (in that both elements can have their own independent padding) are:</p>
<ol>
<li><p>Add an extra relatively positioned <code>div</code> (with no padding) around the absolutely positioned <code>div</code>. That new <code>div</code> will respect the padding of its parent, and the absolutely positioned <code>div</code> will then fill it.</p>
<p>The downside, of course, is that you're messing with the HTML simply for presentational purposes.</p>
</li>
<li><p>Repeat the padding (or add to it) on the absolutely positioned element.</p>
<p>The downside here is that you have to repeat the values in your CSS, which is brittle if you're writing the CSS directly. However, if you're using a pre-processing tool like <code>SASS</code> or <code>LESS</code> you can avoid that problem by using a variable. This is the method I personally use.</p>
</li>
</ol> | {
"question_id": 17115344,
"question_date": "2013-06-14T18:49:11.543Z",
"question_score": 223,
"tags": "css|padding|css-position",
"answer_id": 30826028,
"answer_date": "2015-06-14T04:47:27.263Z",
"answer_score": 258
} |
Please answer the following Stack Overflow question:
Title: How can I download a file from a URL and save it in Rails?
<p>I have a URL to an image which i want to save locally, so that I can use Paperclip to produce a thumbnail for my application. What's the best way to download and save the image? (I looked into ruby file handling but did not come across anything.) </p> | <p>Try this:</p>
<pre><code>require 'open-uri'
open('image.png', 'wb') do |file|
file << open('http://example.com/image.png').read
end
</code></pre> | {
"question_id": 2515931,
"question_date": "2010-03-25T13:36:54.230Z",
"question_score": 223,
"tags": "ruby-on-rails|ruby|file-handling",
"answer_id": 2517286,
"answer_date": "2010-03-25T16:19:47.653Z",
"answer_score": 332
} |
Please answer the following Stack Overflow question:
Title: What's the difference between xsd:include and xsd:import?
<p>What's the difference between <code>xsd:include</code> and <code>xsd:import</code>? When would you use one instead of the other, and when might it not matter?</p> | <p>The fundamental difference between <code>include</code> and <code>import</code> is that you must use <code>import</code> to refer to declarations or definitions that are in a <em>different</em> target namespace and you must use <code>include</code> to refer to declarations or definitions that are (or will be) in the <em>same</em> target namespace.</p>
<p>Source: <a href="https://web.archive.org/web/20070804031046/http://xsd.stylusstudio.com/2002Jun/post08016.htm" rel="noreferrer">https://web.archive.org/web/20070804031046/http://xsd.stylusstudio.com/2002Jun/post08016.htm</a></p> | {
"question_id": 2357943,
"question_date": "2010-03-01T18:08:21.530Z",
"question_score": 223,
"tags": "xml|xsd",
"answer_id": 2357988,
"answer_date": "2010-03-01T18:15:05.673Z",
"answer_score": 222
} |
Please answer the following Stack Overflow question:
Title: Are there best practices for (Java) package organization?
<p>A little while ago, I saw a question answered here regarding the fine-grained organization of java packages. For example, <code>my.project.util</code>, <code>my.project.factory</code>, <code>my.project.service</code>, etc.</p>
<p>I can't find it now, so I may as well ask the question.</p>
<p>Are there best practices with regards to the organization of packages in Java and what goes in them?</p>
<p>How do you organize your classes in your Java project? </p>
<p>For instance, a project I'm working on with a few people has a package called beans. It started out being a project containing simple beans, but has ended up (through poor experience and lack of time) containing everything (almost). I've cleaned them up a little, by putting some factory classes in a factory package (classes with static methods that create beans) but we have other classes that do business logic and others that do simple processing (not with business logic) like retrieving a message for a code from a properties file.</p>
<p>Your thoughts and comments are appreciated.</p> | <p>Package organization or package structuring is usually a heated discussion. Below are some simple guidelines for package naming and structuring:</p>
<ul>
<li>Follow java <a href="http://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html" rel="noreferrer">package naming conventions</a></li>
<li>Structure your packages according to their functional role as well as their business role
<ul>
<li>Break down your packages according to their functionality or modules. e.g. <code>com.company.product.modulea</code></li>
<li>Further break down could be based on layers in your software. But don't go overboard if you have only few classes in the package, then it makes sense to have everything in the package. e.g. <code>com.company.product.module.web</code> or <code>com.company.product.module.util</code> etc.</li>
<li>Avoid going overboard with structuring, IMO avoid separate packaging for exceptions, factories, etc. unless there's a pressing need.</li>
</ul></li>
<li>If your project is small, keep it simple with few packages. e.g. <code>com.company.product.model</code> and <code>com.company.product.util</code>, etc.</li>
<li>Take a look at some of the popular open source projects out there on <a href="http://projects.apache.org/" rel="noreferrer">Apache projects</a>. See how they use structuring, for various sized projects.</li>
<li>Also consider build and distribution when naming ( allowing you to distribute your api or SDK in a different package, see servlet api)</li>
</ul>
<p>After a few experiments and trials you should be able to come up with a structuring that you are comfortable with. Don't be fixated on one convention, be open to changes.</p> | {
"question_id": 3226282,
"question_date": "2010-07-12T06:20:05.267Z",
"question_score": 223,
"tags": "java|package|naming-conventions",
"answer_id": 3226371,
"answer_date": "2010-07-12T06:41:32.397Z",
"answer_score": 191
} |
Please answer the following Stack Overflow question:
Title: Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE] even if app appears to not be installed
<p>When trying to deploy my app to the Android device I am getting the following error:</p>
<pre><code>Deployment failed because of an internal error: Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE]
</code></pre>
<p>I am aware of <a href="https://stackoverflow.com/questions/11891848/install-failed-update-incompatible-when-i-try-to-install-compiled-trebuchet-apk">this question</a> but the app is not installed. It has been removed/partially removed by Visual Studio during the attempt to deploy. </p>
<p>In the past I solved this by downloading the app from the google play store and then removing it from settings->Application manager. However, now i am getting the error "incompatible update" when it is trying to install it. </p>
<p>I tried to remove it using Titanium Backup and few other things but no luck. </p>
<p><strong>EDIT 1</strong></p>
<p>I realised (from @Motz) that I haven't mentioned that the obvious solution doesn't work. Namely, the app doesn't appear in Settings->Apps</p> | <p>I've seen this several times. Usually, it's due to having a signed release version on my phone, then trying to deploy the debug version on top. It gets stuck in an invalid state where it's not fully uninstalled.</p>
<p>The solution that works for me is to open a command prompt and type:</p>
<pre><code>adb uninstall my.package.id
</code></pre>
<p>That usually completes the uninstall in order for me to continue development.</p> | {
"question_id": 26794862,
"question_date": "2014-11-07T05:44:35.023Z",
"question_score": 223,
"tags": "android|visual-studio-2013|xamarin|xamarin.android",
"answer_id": 26804896,
"answer_date": "2014-11-07T15:45:21.067Z",
"answer_score": 582
} |
Please answer the following Stack Overflow question:
Title: Why is my Git Submodule HEAD detached from master?
<p>I am using Git submodules. After pulling changes from server, many times my submodule head gets detached from master branch. </p>
<p>Why does it happen?</p>
<p>I have to always do:</p>
<pre><code>git branch
git checkout master
</code></pre>
<p>How can I make sure that my submodule is always pointing to master branch?</p> | <p><strong>EDIT:</strong></p>
<p><strong>See <a href="https://stackoverflow.com/users/5101148/simba">@Simba</a> <a href="https://stackoverflow.com/a/55570998/1318830">Answer</a> for valid solution</strong></p>
<blockquote>
<p><code>submodule.<name>.update</code> is what you want to change, see the <a href="https://git-scm.com/docs/git-submodule#Documentation/git-submodule.txt-update--init--remote-N--no-fetch--no-recommend-shallow-f--force--checkout--rebase--merge--referenceltrepositorygt--depthltdepthgt--recursive--jobsltngt--ltpathgt82308203" rel="noreferrer">docs</a> - <strong>default <code>checkout</code></strong><br>
<code>submodule.<name>.branch</code> specify remote branch to be tracked - <strong>default <code>master</code></strong> </p>
</blockquote>
<hr>
<p><strong>OLD ANSWER:</strong></p>
<p>Personally I hate answers here which direct to external links which may stop working over time and check my answer <a href="https://stackoverflow.com/questions/18770545/why-my-git-submodule-head-gets-detached-from-master/#">here</a> <em>(Unless question is duplicate)</em> - directing to question which does cover subject between the lines of other subject, but overall equals: "I'm not answering, read the documentation."</p>
<p><strong>So back to the question: Why does it happen?</strong></p>
<p>Situation you described </p>
<blockquote>
<p>After pulling changes from server, many times my submodule head gets detached from master branch.</p>
</blockquote>
<p>This is a common case when one does not use <em>submodules</em> too often or has just started with <em>submodules</em>. I believe that I am correct in stating, that <strong>we all</strong> have been there at some point where our <em>submodule</em>'s HEAD gets detached. </p>
<ul>
<li><strong>Cause: Your submodule is not tracking correct branch (default master).<br>
Solution: Make sure your submodule is tracking the correct branch</strong></li>
</ul>
<pre class="lang-bash prettyprint-override"><code>$ cd <submodule-path>
# if the master branch already exists locally:
# (From git docs - branch)
# -u <upstream>
# --set-upstream-to=<upstream>
# Set up <branchname>'s tracking information so <upstream>
# is considered <branchname>'s upstream branch.
# If no <branchname> is specified, then it defaults to the current branch.
$ git branch -u <origin>/<branch> <branch>
# else:
$ git checkout -b <branch> --track <origin>/<branch>
</code></pre>
<ul>
<li><strong>Cause: Your parent repo is not configured to track submodules branch.<br>
Solution: Make your submodule track its remote branch by adding new submodules with the following two commands.</strong>
<ul>
<li>First you tell git to track your remote <code><branch></code>.</li>
<li>you tell git to perform rebase or merge instead of checkout</li>
<li>you tell git to update your submodule from remote.</li>
</ul></li>
</ul>
<pre class="lang-bash prettyprint-override"><code> $ git submodule add -b <branch> <repository> [<submodule-path>]
$ git config -f .gitmodules submodule.<submodule-path>.update rebase
$ git submodule update --remote
</code></pre>
<ul>
<li><strong>If you haven't added your existing submodule like this you can easily fix that:</strong>
<ul>
<li>First you want to make sure that your submodule has the branch checked out which you want to be tracked. </li>
</ul></li>
</ul>
<pre class="lang-bash prettyprint-override"><code> $ cd <submodule-path>
$ git checkout <branch>
$ cd <parent-repo-path>
# <submodule-path> is here path releative to parent repo root
# without starting path separator
$ git config -f .gitmodules submodule.<submodule-path>.branch <branch>
$ git config -f .gitmodules submodule.<submodule-path>.update <rebase|merge>
</code></pre>
<p>In the common cases, you already have fixed by now your DETACHED HEAD since it was related to one of the configuration issues above.</p>
<p><strong>fixing DETACHED HEAD when <code>.update = checkout</code></strong></p>
<pre class="lang-bash prettyprint-override"><code>$ cd <submodule-path> # and make modification to your submodule
$ git add .
$ git commit -m"Your modification" # Let's say you forgot to push it to remote.
$ cd <parent-repo-path>
$ git status # you will get
Your branch is up-to-date with '<origin>/<branch>'.
Changes not staged for commit:
modified: path/to/submodule (new commits)
# As normally you would commit new commit hash to your parent repo
$ git add -A
$ git commit -m"Updated submodule"
$ git push <origin> <branch>.
$ git status
Your branch is up-to-date with '<origin>/<branch>'.
nothing to commit, working directory clean
# If you now update your submodule
$ git submodule update --remote
Submodule path 'path/to/submodule': checked out 'commit-hash'
$ git status # will show again that (submodule has new commits)
$ cd <submodule-path>
$ git status
HEAD detached at <hash>
# as you see you are DETACHED and you are lucky if you found out now
# since at this point you just asked git to update your submodule
# from remote master which is 1 commit behind your local branch
# since you did not push you submodule chage commit to remote.
# Here you can fix it simply by. (in submodules path)
$ git checkout <branch>
$ git push <origin>/<branch>
# which will fix the states for both submodule and parent since
# you told already parent repo which is the submodules commit hash
# to track so you don't see it anymore as untracked.
</code></pre>
<p>But if you managed to make some changes locally already for submodule and commited, pushed these to remote then when you executed 'git checkout ', Git notifies you:</p>
<pre class="lang-bash prettyprint-override"><code>$ git checkout <branch>
Warning: you are leaving 1 commit behind, not connected to any of your branches:
If you want to keep it by creating a new branch, this may be a good time to do so with:
</code></pre>
<p>The recommended option to create a temporary branch can be good, and then you can just merge these branches etc. However I personally would use just <code>git cherry-pick <hash></code> in this case.</p>
<pre class="lang-bash prettyprint-override"><code>$ git cherry-pick <hash> # hash which git showed you related to DETACHED HEAD
# if you get 'error: could not apply...' run mergetool and fix conflicts
$ git mergetool
$ git status # since your modifications are staged just remove untracked junk files
$ rm -rf <untracked junk file(s)>
$ git commit # without arguments
# which should open for you commit message from DETACHED HEAD
# just save it or modify the message.
$ git push <origin> <branch>
$ cd <parent-repo-path>
$ git add -A # or just the unstaged submodule
$ git commit -m"Updated <submodule>"
$ git push <origin> <branch>
</code></pre>
<p>Although there are some more cases you can get your submodules into DETACHED HEAD state, I hope that you understand now a bit more how to debug your particular case.</p> | {
"question_id": 18770545,
"question_date": "2013-09-12T17:18:42.217Z",
"question_score": 223,
"tags": "git|git-submodules",
"answer_id": 36375256,
"answer_date": "2016-04-02T15:38:02.633Z",
"answer_score": 191
} |
Please answer the following Stack Overflow question:
Title: How do I add a placeholder on a CharField in Django?
<p>Take this very simple form for example:</p>
<pre><code>class SearchForm(Form):
q = forms.CharField(label='search')
</code></pre>
<p>This gets rendered in the template:</p>
<pre class="lang-html prettyprint-override"><code><input type="text" name="q" id="id_q" />
</code></pre>
<p>However, I want to add the <code>placeholder</code> attribute to this field with a value of <code>Search</code> so that the HTML would look something like:</p>
<pre class="lang-html prettyprint-override"><code><input type="text" name="q" id="id_q" placeholder="Search" />
</code></pre>
<p>Preferably I would like to pass the placeholder value in to <code>CharField</code> in the form class through a dictionary or something like:</p>
<pre><code>q = forms.CharField(label='search', placeholder='Search')
</code></pre>
<p>What would be the best way to accomplish this?</p> | <p>Look at the <a href="http://docs.djangoproject.com/en/dev/ref/forms/widgets/">widgets documentation</a>. Basically it would look like:</p>
<pre><code>q = forms.CharField(label='search',
widget=forms.TextInput(attrs={'placeholder': 'Search'}))
</code></pre>
<p>More writing, yes, but the separation allows for better abstraction of more complicated cases.</p>
<p>You can also declare a <code>widgets</code> attribute containing a <code><field name> => <widget instance></code> mapping directly on the <code>Meta</code> of your <code>ModelForm</code> sub-class.</p> | {
"question_id": 4101258,
"question_date": "2010-11-04T20:51:57.033Z",
"question_score": 223,
"tags": "python|django|django-forms",
"answer_id": 4101282,
"answer_date": "2010-11-04T20:54:08.050Z",
"answer_score": 334
} |
Please answer the following Stack Overflow question:
Title: What is the difference between Optional.flatMap and Optional.map?
<p>What's the difference between these two methods: <code>Optional.flatMap()</code> and <code>Optional.map()</code>?</p>
<p>An example would be appreciated.</p> | <p>Use <code>map</code> if the function returns the object you need or <code>flatMap</code> if the function returns an <code>Optional</code>. For example:</p>
<pre><code>public static void main(String[] args) {
Optional<String> s = Optional.of("input");
System.out.println(s.map(Test::getOutput));
System.out.println(s.flatMap(Test::getOutputOpt));
}
static String getOutput(String input) {
return input == null ? null : "output for " + input;
}
static Optional<String> getOutputOpt(String input) {
return input == null ? Optional.empty() : Optional.of("output for " + input);
}
</code></pre>
<p>Both print statements print the same thing.</p> | {
"question_id": 30864583,
"question_date": "2015-06-16T10:09:56.383Z",
"question_score": 223,
"tags": "java|java-8|option-type",
"answer_id": 30864741,
"answer_date": "2015-06-16T10:16:39.107Z",
"answer_score": 218
} |
Please answer the following Stack Overflow question:
Title: gitignore does not ignore folder
<p>In the root of my project I have a <code>foo</code> folder. Inside the <code>foo</code> folder I have a <code>bar</code> folder. I would like to ignore all changes to all files inside my <code>bar</code> folder. I have this in my <code>gitignore</code>:</p>
<pre><code>/foo/bar
</code></pre>
<p>The folder is checked: it exists and it has the files to be ignored. <code>gitignore</code> is <code>commit</code>ted. However, I have a file where I make a moification and is inside my <code>bar</code> folder. When I type</p>
<pre><code>git status
</code></pre>
<p>inside my <code>git bash</code> I see the file which should have been ignored. What could be the reason and how can I successfully ignore all files inside my bar folder?</p>
<p>Note, that the files were previously ignored with the same line, but I had to temporarily remove that line to <code>commit</code> something on the server. After the <code>commit</code>, I put back the line into the <code>gitignore</code>. This was a while ago, but now I have observed that the files will be in <code>git status</code>. I would expect to be able to modify the ignored files without they appearing in the <code>git status</code>.</p> | <p>I'm guessing this folder has been checked into git before? </p>
<p>Run <code>git rm -r --cached <folder></code> and check again.</p> | {
"question_id": 24410208,
"question_date": "2014-06-25T13:34:05.450Z",
"question_score": 223,
"tags": "git|gitignore",
"answer_id": 24410260,
"answer_date": "2014-06-25T13:36:38.170Z",
"answer_score": 559
} |
Please answer the following Stack Overflow question:
Title: How do you move a file?
<p>I'm using TortoiseSVN against the SourceForge SVN repository. I'd like to move a file from one folder to another in order to maintain its revision history. Is this possible? If so, how do you do it?</p>
<p>(My current strategy has been to copy the file into the new folder and check it in and then delete the file from the current folder.)</p> | <p>Subversion has native support for moving files.</p>
<pre><code>svn move SOURCE DESTINATION
</code></pre>
<p>See the online help (svn help move) for more information.</p> | {
"question_id": 46080,
"question_date": "2008-09-05T15:45:53.380Z",
"question_score": 223,
"tags": "svn|tortoisesvn",
"answer_id": 46083,
"answer_date": "2008-09-05T15:46:55.907Z",
"answer_score": 97
} |
Please answer the following Stack Overflow question:
Title: How to resolve "must be an instance of string, string given" prior to PHP 7?
<p>Here is my code:</p>
<pre><code>function phpwtf(string $s) {
echo "$s\n";
}
phpwtf("Type hinting is da bomb");
</code></pre>
<p>Which results in this error:</p>
<blockquote>
<p>Catchable fatal error: Argument 1 passed to phpwtf() must be an instance of string, string given</p>
</blockquote>
<p>It's more than a little Orwellian to see PHP recognize and reject the desired type in the same breath. <em>There are five lights, damn it.</em></p>
<p>What is the equivalent of type hinting for strings in PHP? Bonus consideration to the answer that explains exactly what is going on here.</p> | <p>Prior to PHP 7 <a href="http://php.net/manual/en/language.oop5.typehinting.php">type hinting</a> can only be used to force the types of objects and arrays. Scalar types are not type-hintable. In this case an object of the class <code>string</code> is expected, but you're giving it a (scalar) <code>string</code>. The error message may be funny, but it's not supposed to work to begin with. Given the dynamic typing system, this actually makes some sort of perverted sense.</p>
<p>You can only <em>manually</em> "type hint" scalar types:</p>
<pre><code>function foo($string) {
if (!is_string($string)) {
trigger_error('No, you fool!');
return;
}
...
}
</code></pre> | {
"question_id": 4103480,
"question_date": "2010-11-05T03:53:17.383Z",
"question_score": 223,
"tags": "php|types|type-hinting",
"answer_id": 4103536,
"answer_date": "2010-11-05T04:09:38.970Z",
"answer_score": 212
} |
Please answer the following Stack Overflow question:
Title: In TensorFlow, what is the difference between Session.run() and Tensor.eval()?
<p>TensorFlow has two ways to evaluate part of graph: <code>Session.run</code> on a list of variables and <code>Tensor.eval</code>. Is there a difference between these two?</p> | <p>If you have a <code>Tensor</code> t, calling <a href="https://www.tensorflow.org/api_docs/python/tf/Tensor#eval" rel="noreferrer"><code>t.eval()</code></a> is equivalent to calling <code>tf.get_default_session().run(t)</code>.</p>
<p>You can make a session the default as follows:</p>
<pre><code>t = tf.constant(42.0)
sess = tf.Session()
with sess.as_default(): # or `with sess:` to close on exit
assert sess is tf.get_default_session()
assert t.eval() == sess.run(t)
</code></pre>
<p>The most important difference is that you can use <code>sess.run()</code> to fetch the values of many tensors in the same step:</p>
<pre><code>t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.mul(t, u)
ut = tf.mul(u, t)
with sess.as_default():
tu.eval() # runs one step
ut.eval() # runs one step
sess.run([tu, ut]) # evaluates both tensors in a single step
</code></pre>
<p>Note that each call to <code>eval</code> and <code>run</code> will execute the whole graph from scratch. To cache the result of a computation, assign it to a <a href="https://www.tensorflow.org/how_tos/variables/" rel="noreferrer"><code>tf.Variable</code></a>.</p> | {
"question_id": 33610685,
"question_date": "2015-11-09T13:52:52.940Z",
"question_score": 223,
"tags": "python|tensorflow",
"answer_id": 33610914,
"answer_date": "2015-11-09T14:05:45.853Z",
"answer_score": 249
} |
Please answer the following Stack Overflow question:
Title: Show all Elasticsearch aggregation results/buckets and not just 10
<p>I'm trying to list all buckets on an aggregation, but it seems to be showing only the first 10.</p>
<p>My search:</p>
<pre><code>curl -XPOST "http://localhost:9200/imoveis/_search?pretty=1" -d'
{
"size": 0,
"aggregations": {
"bairro_count": {
"terms": {
"field": "bairro.raw"
}
}
}
}'
</code></pre>
<p>Returns:</p>
<pre><code>{
"took" : 2,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
"failed" : 0
},
"hits" : {
"total" : 16920,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"bairro_count" : {
"buckets" : [ {
"key" : "Barra da Tijuca",
"doc_count" : 5812
}, {
"key" : "Centro",
"doc_count" : 1757
}, {
"key" : "Recreio dos Bandeirantes",
"doc_count" : 1027
}, {
"key" : "Ipanema",
"doc_count" : 927
}, {
"key" : "Copacabana",
"doc_count" : 842
}, {
"key" : "Leblon",
"doc_count" : 833
}, {
"key" : "Botafogo",
"doc_count" : 594
}, {
"key" : "Campo Grande",
"doc_count" : 456
}, {
"key" : "Tijuca",
"doc_count" : 361
}, {
"key" : "Flamengo",
"doc_count" : 328
} ]
}
}
}
</code></pre>
<p>I have much more than 10 keys for this aggregation. In this example I'd have 145 keys, and I want the count for each of them. Is there some pagination on buckets? Can I get all of them?</p>
<p>I'm using Elasticsearch 1.1.0 </p> | <p>The size param should be a param for the terms query example:</p>
<pre><code>curl -XPOST "http://localhost:9200/imoveis/_search?pretty=1" -d'
{
"size": 0,
"aggregations": {
"bairro_count": {
"terms": {
"field": "bairro.raw",
"size": 10000
}
}
}
}'
</code></pre>
<p>Use <code>size: 0</code> for ES version 2 and prior.</p>
<p>Setting <code>size:0</code> is deprecated in 2.x onwards, due to memory issues inflicted on your cluster with high-cardinality field values. You can read more about it in the github <a href="https://github.com/elastic/elasticsearch/issues/18838" rel="noreferrer">issue here</a> .</p>
<p>It is recommended to explicitly set reasonable value for <code>size</code> a number between 1 to 2147483647.</p> | {
"question_id": 22927098,
"question_date": "2014-04-08T03:41:33.130Z",
"question_score": 223,
"tags": "elasticsearch|aggregation",
"answer_id": 22927215,
"answer_date": "2014-04-08T03:55:25.963Z",
"answer_score": 254
} |
Please answer the following Stack Overflow question:
Title: How can I create nonexistent subdirectories recursively using Bash?
<p>I am creating a quick backup script that will dump some databases into a nice/neat directory structure and I realized that I need to test to make sure that the directories exist before I create them. The code I have works, but is there a better way to do it?</p>
<pre><code>[ -d "$BACKUP_DIR" ] || mkdir "$BACKUP_DIR"
[ -d "$BACKUP_DIR/$client" ] || mkdir "$BACKUP_DIR/$client"
[ -d "$BACKUP_DIR/$client/$year" ] || mkdir "$BACKUP_DIR/$client/$year"
[ -d "$BACKUP_DIR/$client/$year/$month" ] || mkdir "$BACKUP_DIR/$client/$year/$month"
[ -d "$BACKUP_DIR/$client/$year/$month/$day" ] || mkdir "$BACKUP_DIR/$client/$year/$month/$day"
</code></pre> | <p>You can use the <code>-p</code> parameter, which is <a href="http://unixhelp.ed.ac.uk/CGI/man-cgi?mkdir" rel="noreferrer">documented as</a>:</p>
<blockquote>
<p>-p, --parents</p>
<p>no error if existing, make parent directories as needed</p>
</blockquote>
<p>So:</p>
<pre><code>mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"
</code></pre> | {
"question_id": 1731767,
"question_date": "2009-11-13T20:42:03.577Z",
"question_score": 223,
"tags": "bash|shell|recursion|subdirectory",
"answer_id": 1731775,
"answer_date": "2009-11-13T20:42:53.663Z",
"answer_score": 494
} |
Please answer the following Stack Overflow question:
Title: How do you move a commit to the staging area in git?
<p>If you want to move a commit to the staging area - that is uncommit it and move all of the changes which were in it into the staging area (effectively putting the branch in the state that it would have been in prior to the commit) - how do you do it? Or is it something that you can't do?</p>
<p>The closest that I know how to do is to copy all of the files that were changed in the commit to somewhere else, reset the branch to the commit before the commit that you're trying to move into the staging area, move all of the copied files back into the repository, and then add them to the staging area. It works, but it's not exactly a nice solution. What I'd like to be able to do is just undo the commit and move its changing into the staging area. Can it be done? And if so, how?</p> | <pre><code>git reset --soft HEAD^
</code></pre>
<p>This will reset your index to <code>HEAD^</code> (the previous commit) but leave your changes in the staging area.</p>
<p>There are some <a href="https://git-scm.com/docs/git-reset#_discussion" rel="noreferrer">handy diagrams</a> in the <a href="http://git-scm.com/docs/git-reset" rel="noreferrer"><code>git-reset</code></a> docs</p>
<p>If you are on Windows you might need to use this format:</p>
<pre><code>git reset --soft HEAD~1
</code></pre> | {
"question_id": 7214039,
"question_date": "2011-08-27T10:48:13.670Z",
"question_score": 223,
"tags": "git|commit|staging",
"answer_id": 7214061,
"answer_date": "2011-08-27T10:52:43.780Z",
"answer_score": 406
} |
Please answer the following Stack Overflow question:
Title: JSDoc: Return object structure
<p>How can I tell JSDoc about the structure of an object that is returned. I have found the <code>@return {{field1: type, field2: type, ...}} description</code> syntax and tried it:</p>
<pre><code>/**
* Returns a coordinate from a given mouse or touch event
* @param {TouchEvent|MouseEvent|jQuery.Event} e
* A valid mouse or touch event or a jQuery event wrapping such an
* event.
* @param {string} [type="page"]
* A string representing the type of location that should be
* returned. Can be either "page", "client" or "screen".
* @return {{x: Number, y: Number}}
* The location of the event
*/
var getEventLocation = function(e, type) {
...
return {x: xLocation, y: yLocation};
}
</code></pre>
<p>While this parses successfully, the resulting documentation simply states:</p>
<pre><code>Returns:
The location of an event
Type: Object
</code></pre>
<p>I am developing an API and need people to know about the object that they will get returned. Is this possible in JSDoc? I am using JSDoc3.3.0-beta1.</p> | <p>Define your structure separately <a href="https://jsdoc.app/tags-typedef.html" rel="noreferrer">using a @typdef</a>:</p>
<pre><code>/**
* @typedef {Object} Point
* @property {number} x - The X Coordinate
* @property {number} y - The Y Coordinate
*/
</code></pre>
<p>And use it as the return type:</p>
<pre><code>/**
* Returns a coordinate from a given mouse or touch event
* @param {TouchEvent|MouseEvent|jQuery.Event} e
* A valid mouse or touch event or a jQuery event wrapping such an
* event.
* @param {string} [type="page"]
* A string representing the type of location that should be
* returned. Can be either "page", "client" or "screen".
* @return {Point}
* The location of the event
*/
var getEventLocation = function(e, type) {
...
return {x: xLocation, y: yLocation};
}
</code></pre> | {
"question_id": 28763257,
"question_date": "2015-02-27T10:49:17.797Z",
"question_score": 223,
"tags": "javascript|documentation-generation|jsdoc|code-documentation|jsdoc3",
"answer_id": 28763616,
"answer_date": "2015-02-27T11:06:44.987Z",
"answer_score": 368
} |
Please answer the following Stack Overflow question:
Title: What is the purpose of the "send" function on Python generators?
<p>I understand <code>yield</code>. But what does a generator's <code>send</code> function do? The documentation says:</p>
<blockquote>
<pre><code>generator.send(value)
</code></pre>
<p>Resumes the execution and “sends” a value into the generator function. The <code>value</code> argument becomes the result of the current <code>yield</code> expression. The <code>send()</code> method returns the next value yielded by the generator, or raises <code>StopIteration</code> if the generator exits without yielding another value.</p>
</blockquote>
<p>What does that mean? I thought <code>value</code> was the input to the generator function? The phrase "The <code>send()</code> method returns the next value yielded by the generator" seems to be also the exact purpose of <code>yield</code>, which also returns the next value yielded by the generator.</p>
<p>Is there an example of a generator utilizing <code>send</code> that accomplishes something <code>yield</code> cannot?</p> | <p>It's used to send values into a generator that just yielded. Here is an artificial (non-useful) explanatory example:</p>
<pre><code>>>> def double_inputs():
... while True:
... x = yield
... yield x * 2
...
>>> gen = double_inputs()
>>> next(gen) # run up to the first yield
>>> gen.send(10) # goes into 'x' variable
20
>>> next(gen) # run up to the next yield
>>> gen.send(6) # goes into 'x' again
12
>>> next(gen) # run up to the next yield
>>> gen.send(94.3) # goes into 'x' again
188.5999999999999
</code></pre>
<p>You can't do this just with <code>yield</code>.</p>
<p>As to why it's useful, one of the best use cases I've seen is Twisted's <code>@defer.inlineCallbacks</code>. Essentially it allows you to write a function like this:</p>
<pre><code>@defer.inlineCallbacks
def doStuff():
result = yield takesTwoSeconds()
nextResult = yield takesTenSeconds(result * 10)
defer.returnValue(nextResult / 10)
</code></pre>
<p>What happens is that <code>takesTwoSeconds()</code> returns a <code>Deferred</code>, which is a value promising a value will be computed later. Twisted can run the computation in another thread. When the computation is done, it passes it into the deferred, and the value then gets sent back to the <code>doStuff()</code> function. Thus the <code>doStuff()</code> can end up looking more or less like a normal procedural function, except it can be doing all sorts of computations & callbacks etc. The alternative before this functionality would be to do something like:</p>
<pre><code>def doStuff():
returnDeferred = defer.Deferred()
def gotNextResult(nextResult):
returnDeferred.callback(nextResult / 10)
def gotResult(result):
takesTenSeconds(result * 10).addCallback(gotNextResult)
takesTwoSeconds().addCallback(gotResult)
return returnDeferred
</code></pre>
<p>It's a lot more convoluted and unwieldy.</p> | {
"question_id": 19302530,
"question_date": "2013-10-10T17:38:19.150Z",
"question_score": 223,
"tags": "python|generator",
"answer_id": 19302694,
"answer_date": "2013-10-10T17:47:01.287Z",
"answer_score": 210
} |
Please answer the following Stack Overflow question:
Title: Which is better in python, del or delattr?
<p>This may be silly, but it's been nagging the back of my brain for a while. </p>
<p>Python gives us two built-in ways to delete attributes from objects, the <strong>del</strong> command word and the <strong>delattr</strong> built-in function. I prefer <strong>delattr</strong> because it I think its a bit more explicit:</p>
<pre><code>del foo.bar
delattr(foo, "bar")
</code></pre>
<p>But I'm wondering if there might be under-the-hood differences between them.</p> | <p>The first is more efficient than the second. <code>del foo.bar</code> compiles to two bytecode instructions:</p>
<pre><code> 2 0 LOAD_FAST 0 (foo)
3 DELETE_ATTR 0 (bar)
</code></pre>
<p>whereas <code>delattr(foo, "bar")</code> takes five:</p>
<pre><code> 2 0 LOAD_GLOBAL 0 (delattr)
3 LOAD_FAST 0 (foo)
6 LOAD_CONST 1 ('bar')
9 CALL_FUNCTION 2
12 POP_TOP
</code></pre>
<p>This translates into the first running <em>slightly</em> faster (but it's not a huge difference – .15 μs on my machine).</p>
<p>Like the others have said, you should really only use the second form when the attribute that you're deleting is determined dynamically.</p>
<p>[Edited to show the bytecode instructions generated inside a function, where the compiler can use <code>LOAD_FAST</code> and <code>LOAD_GLOBAL</code>]</p> | {
"question_id": 1120927,
"question_date": "2009-07-13T17:33:33.783Z",
"question_score": 223,
"tags": "python|del",
"answer_id": 1121068,
"answer_date": "2009-07-13T17:58:51.470Z",
"answer_score": 321
} |
Please answer the following Stack Overflow question:
Title: Cannot pass null argument when using type hinting
<p>The following code:</p>
<pre class="lang-php prettyprint-override"><code>class Type {
}
function foo(Type $t) {
}
foo(null);
</code></pre>
<p>failed at run time:</p>
<blockquote>
<p>PHP Fatal error: Argument 1 passed to foo() must not be null</p>
</blockquote>
<p>Why is it not allowed to pass null just like other languages?</p> | <p><strong>PHP 7.1 or newer</strong> (released 2nd December 2016)</p>
<p>You can explicitly declare a variable to be <code>null</code> with this syntax</p>
<pre><code>function foo(?Type $t) {
}
</code></pre>
<p>this will result in</p>
<pre><code>$this->foo(new Type()); // ok
$this->foo(null); // ok
$this->foo(); // error
</code></pre>
<p>So, if you want an optional argument you can follow the convention <code>Type $t = null</code> whereas if you need to make an argument accept both <code>null</code> and its type, you can follow above example.</p>
<p>You can read more <a href="https://wiki.php.net/rfc/nullable_types" rel="noreferrer">here</a>.</p>
<hr>
<p><strong>PHP 7.0 or older</strong></p>
<p>You have to add a default value like</p>
<pre><code>function foo(Type $t = null) {
}
</code></pre>
<p>That way, you can pass it a null value.</p>
<p>This is documented in the section in the manual about <a href="http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration" rel="noreferrer">Type Declarations</a>:</p>
<blockquote>
<p>The declaration can be made to accept <code>NULL</code> values if the default value of the parameter is set to <code>NULL</code>.</p>
</blockquote> | {
"question_id": 14584145,
"question_date": "2013-01-29T13:31:44.390Z",
"question_score": 223,
"tags": "php|type-hinting",
"answer_id": 14584208,
"answer_date": "2013-01-29T13:34:31.110Z",
"answer_score": 422
} |
Please answer the following Stack Overflow question:
Title: What's the difference between ContentControl and ContentPresenter?
<p>I'm not sure when I should use <code>ContentPresenter</code> instead of <code>ContentControl</code> (and vice-versa). At the moment, I'm using <code>ContentControl</code> pretty much all the time in my <code>DataTemplate</code>s. When would <code>ContentPresenter</code> be a better choice? and why?</p> | <p><code>ContentControl</code> is a base class for controls that contain other elements and have a <code>Content</code>-property (for example, <code>Button</code>).</p>
<p><code>ContentPresenter</code> is used inside control templates to display content.</p>
<p><code>ContentControl</code>, when used directly (it's supposed to be used as a base class), has a control template that uses ContentPresenter to display it's content.</p>
<p>My rules of thumb (not applicable in every case, use your judgment):</p>
<ol>
<li>Inside <code>ControlTemplate</code> use <code>ContentPresenter</code></li>
<li>Outside of <code>ControlTemplate</code> (including <code>DataTemplate</code> and outside templates) try not to use any of them, if you need to, you must prefer <code>ContentPresenter</code></li>
<li>Subclass <code>ContentControl</code> if you are creating a custom "lookless" control that host content and you can't get the same result by changing an existing control's template (that should be extremely rare).</li>
</ol> | {
"question_id": 1287995,
"question_date": "2009-08-17T13:34:06.187Z",
"question_score": 223,
"tags": ".net|wpf|contentcontrol|contentpresenter",
"answer_id": 1288353,
"answer_date": "2009-08-17T14:44:41.537Z",
"answer_score": 188
} |
Please answer the following Stack Overflow question:
Title: Can every recursion be converted into iteration?
<p>A <a href="http://www.reddit.com/r/programming/comments/8oh88/effectively_walking_trees_and_graphs_in_python/c09xm45" rel="noreferrer">reddit thread</a> brought up an apparently interesting question:</p>
<blockquote>
<p>Tail recursive functions can trivially be converted into iterative functions. Other ones, can be transformed by using an explicit stack. Can <em>every</em> recursion be transformed into iteration?</p>
</blockquote>
<p>The (counter?)example in the post is the pair:</p>
<pre><code>(define (num-ways x y)
(case ((= x 0) 1)
((= y 0) 1)
(num-ways2 x y) ))
(define (num-ways2 x y)
(+ (num-ways (- x 1) y)
(num-ways x (- y 1))
</code></pre> | <p>Can you always turn a recursive function into an iterative one? Yes, absolutely, and the Church-Turing thesis proves it if memory serves. In lay terms, it states that what is computable by recursive functions is computable by an iterative model (such as the Turing machine) and vice versa. The thesis does not tell you precisely how to do the conversion, but it does say that it's definitely possible.</p>
<p>In many cases, converting a recursive function is easy. Knuth offers several techniques in "The Art of Computer Programming". And often, a thing computed recursively can be computed by a completely different approach in less time and space. The classic example of this is Fibonacci numbers or sequences thereof. You've surely met this problem in your degree plan.</p>
<p>On the flip side of this coin, we can certainly imagine a programming system so advanced as to treat a recursive definition of a formula as an invitation to memoize prior results, thus offering the speed benefit without the hassle of telling the computer exactly which steps to follow in the computation of a formula with a recursive definition. Dijkstra almost certainly did imagine such a system. He spent a long time trying to separate the implementation from the semantics of a programming language. Then again, his non-deterministic and multiprocessing programming languages are in a league above the practicing professional programmer.</p>
<p>In the final analysis, many functions are just plain easier to understand, read, and write in recursive form. Unless there's a compelling reason, you probably shouldn't (manually) convert these functions to an explicitly iterative algorithm. Your computer will handle that job correctly.</p>
<p>I can see one compelling reason. Suppose you've a prototype system in a super-high level language like [<em>donning asbestos underwear</em>] Scheme, Lisp, Haskell, OCaml, Perl, or Pascal. Suppose conditions are such that you need an implementation in C or Java. (Perhaps it's politics.) Then you could certainly have some functions written recursively but which, translated literally, would explode your runtime system. For example, infinite tail recursion is possible in Scheme, but the same idiom causes a problem for existing C environments. Another example is the use of lexically nested functions and static scope, which Pascal supports but C doesn't.</p>
<p>In these circumstances, you might try to overcome political resistance to the original language. You might find yourself reimplementing Lisp badly, as in Greenspun's (tongue-in-cheek) tenth law. Or you might just find a completely different approach to solution. But in any event, there is surely a way.</p> | {
"question_id": 931762,
"question_date": "2009-05-31T09:48:04.583Z",
"question_score": 223,
"tags": "language-agnostic|recursion|iteration",
"answer_id": 933979,
"answer_date": "2009-06-01T08:32:02.673Z",
"answer_score": 212
} |
Please answer the following Stack Overflow question:
Title: git working on two branches simultaneously
<p>I have a project with many branches.</p>
<p>I would like to work on <strong>several</strong> branches simultaneously without switching back and forth with <code>git checkout</code>.</p>
<p>Is there any way I can do that besides copying the whole repository somewhere else?</p> | <p>Git 2.5+ (Q2 2015) supports this feature!</p>
<p>If you have a git repo <code>cool-app</code>, cd to root (<code>cd cool-app</code>), run <code>git worktree add ../cool-app-feature-A feature/A</code>. This checks out the branch <code>feature/A</code> in it's own new dedicated directory, <code>cool-app-feature-A</code>.</p>
<p>That replaces an older script <code>contrib/workdir/git-new-workdir</code>, with a more robust mechanism where those "linked" working trees are actually recorded in the main repo new <code>$GIT_DIR/worktrees</code> folder (so that work on any OS, including Windows).</p>
<p>Again, once you have cloned a repo (in a folder like <code>/path/to/myrepo</code>), you can add worktrees for different branches in <em>different</em> independent paths (<code>/path/to/br1</code>, <code>/path/to/br2</code>), while having those working trees linked to the main repo history (no need to use a <code>--git-dir</code> option anymore)</p>
<p>See more at "<strong><a href="https://stackoverflow.com/a/30185564/6309">Multiple working directories with Git?</a></strong>".</p>
<p>And once you have created a <a href="https://stackoverflow.com/a/49331132/6309">worktree, you can move or remove it</a> (with Git 2.17+, Q2 2018).</p> | {
"question_id": 2048470,
"question_date": "2010-01-12T11:22:10.867Z",
"question_score": 223,
"tags": "git|branch",
"answer_id": 30186843,
"answer_date": "2015-05-12T09:29:49.757Z",
"answer_score": 231
} |
Please answer the following Stack Overflow question:
Title: Getting "The JSON request was too large to be deserialized"
<p>I'm getting this Error:</p>
<blockquote>
<p>The JSON request was too large to be deserialized.</p>
</blockquote>
<p>Here's a scenario where this occurs. I have a class of country which hold a list of shipping ports of that country</p>
<pre><code>public class Country
{
public int Id { get; set; }
public string Name { get; set; }
public List<Port> Ports { get; set; }
}
</code></pre>
<p>I use KnockoutJS on the client side to make a cascading drop downs. So we have an array of two drop downs, where the first one is country, and the second one is ports of that country.</p>
<p>Everything is working fine so far, this my client side script:</p>
<pre><code>var k1 = k1 || {};
$(document).ready(function () {
k1.MarketInfoItem = function (removeable) {
var self = this;
self.CountryOfLoadingId = ko.observable();
self.PortOfLoadingId = ko.observable();
self.CountryOfDestinationId = ko.observable();
self.PortOfDestinationId = ko.observable();
};
k1.viewModel = function () {
var marketInfoItems = ko.observableArray([]),
countries = ko.observableArray([]),
saveMarketInfo = function () {
var jsonData = ko.toJSON(marketInfoItems);
$.ajax({
url: 'SaveMarketInfos',
type: "POST",
data: jsonData,
datatype: "json",
contentType: "application/json charset=utf-8",
success: function (data) {
if (data) {
window.location.href = "Fin";
} else {
alert("Can not save your market information now!");
}
},
error: function (data) { alert("Can not save your contacts now!"); }
});
},
loadData = function () {
$.getJSON('../api/ListService/GetCountriesWithPorts', function (data) {
countries(data);
});
};
return {
MarketInfoItems: marketInfoItems,
Countries: countries,
LoadData: loadData,
SaveMarketInfo: saveMarketInfo,
};
} ();
</code></pre>
<p>The problem occurs when a country like China is selected, which has <em>lots</em> of ports. So if you have 3 or 4 times "China" in your array and I want to send it to the server to save. The error occurs.</p>
<p>What should I do to remedy this?</p> | <p><s>You have to adjust the <a href="http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.maxjsonlength.aspx" rel="noreferrer">maxJsonLength</a> property to a higher value in <code>web.config</code> to resolve the issue.</p>
<pre class="lang-xml prettyprint-override"><code><system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483644"/>
</webServices>
</scripting>
</system.web.extensions>
</code></pre>
<p></s></p>
<p>Set a higher value for <code>aspnet:MaxJsonDeserializerMembers</code> in the appSettings:</p>
<pre class="lang-xml prettyprint-override"><code><appSettings>
<add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>
</code></pre>
<p>If those options are not working you could try creating a custom json value provider factory using JSON.NET as specified in this <a href="https://stackoverflow.com/questions/9509721/jsonvalueproviderfactory-throws-request-too-large">thread</a>.</p> | {
"question_id": 10966328,
"question_date": "2012-06-10T04:15:36.817Z",
"question_score": 223,
"tags": "asp.net-mvc|knockout.js",
"answer_id": 10969382,
"answer_date": "2012-06-10T14:14:00.490Z",
"answer_score": 434
} |
Please answer the following Stack Overflow question:
Title: What is the difference between is_a and instanceof?
<p>I am aware that <a href="http://php.net/manual/en/language.operators.type.php" rel="noreferrer"><code>instanceof</code></a> is an operator and that <a href="http://www.php.net/manual/en/function.is-a.php" rel="noreferrer"><code>is_a</code></a> is a method.</p>
<p>Is the method slower in performance? What would you prefer to use?</p> | <p><strong>Update</strong></p>
<p>As of <a href="https://www.php.net/manual/en/function.is-a.php#refsect1-function.is-a-changelog" rel="noreferrer">PHP 5.3.9</a>, the functionality of <code>is_a()</code> has changed. The original answer below states that <code>is_a()</code> <em>must</em> accept an <code>Object</code> as the first argument, but PHP versions >= 5.3.9 now accept an optional third boolean argument <code>$allow_string</code> (defaults to <code>false</code>) to allow comparisons of string class names instead:</p>
<pre><code>class MyBaseClass {}
class MyExtendingClass extends MyBaseClass {}
// Original behavior, evaluates to false.
is_a(MyExtendingClass::class, MyBaseClass::class);
// New behavior, evaluates to true.
is_a(MyExtendingClass::class, MyBaseClass::class, true);
</code></pre>
<p>The key difference in the new behavior between <code>instanceof</code> and <code>is_a()</code> is that <code>instanceof</code> will always check that the target is an instantiated object of the specified class (including extending classes), whereas <code>is_a()</code> only requires that the object be instantiated when the <code>$allow_string</code> argument is set to the default value of <code>false</code>.</p>
<hr>
<p><strong>Original</strong></p>
<p>Actually, <code>is_a</code> is a function, whereas <code>instanceof</code> is a language construct. <code>is_a</code> will be significantly slower (since it has all the overhead of executing a function call), but the overall execution time is minimal in either method.</p>
<p>It's no longer deprecated as of 5.3, so there's no worry there.</p>
<p>There is one difference however. <code>is_a</code> being a function takes an object as parameter 1, and a string (variable, constant, or literal) as parameter 2. So:</p>
<pre><code>is_a($object, $string); // <- Only way to call it
</code></pre>
<p><code>instanceof</code> takes an object as parameter 1, and can take a class name (variable), object instance (variable), or class identifier (class name written without quotes) as parameter 2.</p>
<pre><code>$object instanceof $string; // <- string class name
$object instanceof $otherObject; // <- object instance
$object instanceof ClassName; // <- identifier for the class
</code></pre> | {
"question_id": 3017684,
"question_date": "2010-06-10T19:19:05.270Z",
"question_score": 223,
"tags": "php",
"answer_id": 3017737,
"answer_date": "2010-06-10T19:26:44.040Z",
"answer_score": 226
} |
Please answer the following Stack Overflow question:
Title: What is the '@=' symbol for in Python?
<p>I know <code>@</code> is for decorators, but what is <code>@=</code> for in Python? Is it just reservation for some future idea?</p>
<p>This is just one of my many questions while reading <code>tokenizer.py</code>.</p> | <p>From <a href="https://docs.python.org/3.5/reference/expressions.html#binary-arithmetic-operations" rel="noreferrer">the</a> <a href="https://docs.python.org/3.5/reference/simple_stmts.html#augmented-assignment-statements" rel="noreferrer">documentation</a>:</p>
<blockquote>
<p>The <code>@</code> (at) operator is intended to be used for matrix multiplication. No builtin Python types implement this operator.</p>
</blockquote>
<p>The <code>@</code> operator was introduced in Python 3.5. <code>@=</code> is matrix multiplication followed by assignment, as you would expect. They map to <code>__matmul__</code>, <code>__rmatmul__</code> or <code>__imatmul__</code> similar to how <code>+</code> and <code>+=</code> map to <code>__add__</code>, <code>__radd__</code> or <code>__iadd__</code>.</p>
<p>The operator and the rationale behind it are discussed in detail in <a href="http://www.python.org/dev/peps/pep-0465/" rel="noreferrer">PEP 465</a>.</p> | {
"question_id": 27385633,
"question_date": "2014-12-09T17:59:34.587Z",
"question_score": 223,
"tags": "python|python-3.x|operators|matrix-multiplication|python-3.5",
"answer_id": 27385659,
"answer_date": "2014-12-09T18:00:48.133Z",
"answer_score": 248
} |
Please answer the following Stack Overflow question:
Title: Compare double to zero using epsilon
<p>Today, I was looking through some C++ code (written by somebody else) and found this section:</p>
<pre><code>double someValue = ...
if (someValue < std::numeric_limits<double>::epsilon() &&
someValue > -std::numeric_limits<double>::epsilon()) {
someValue = 0.0;
}
</code></pre>
<p>I'm trying to figure out whether this even makes sense.</p>
<p>The documentation for <code>epsilon()</code> says:</p>
<blockquote>
<p>The function returns the difference between 1 and the smallest value greater than 1 that is representable [by a double].</p>
</blockquote>
<p>Does this apply to 0 as well, i.e. <code>epsilon()</code> is the smallest value greater than 0? Or are there numbers between <code>0</code> and <code>0 + epsilon</code> that can be represented by a <code>double</code>?</p>
<p>If not, then isn't the comparison equivalent to <code>someValue == 0.0</code>?</p> | <p>Assuming 64-bit IEEE double, there is a 52-bit mantissa and 11-bit exponent. Let's break it to bits:</p>
<pre><code>1.0000 00000000 00000000 00000000 00000000 00000000 00000000 × 2^0 = 1
</code></pre>
<p>The smallest representable number greater than 1:</p>
<pre><code>1.0000 00000000 00000000 00000000 00000000 00000000 00000001 × 2^0 = 1 + 2^-52
</code></pre>
<p>Therefore:</p>
<pre><code>epsilon = (1 + 2^-52) - 1 = 2^-52
</code></pre>
<p>Are there any numbers between 0 and epsilon? Plenty... E.g. the minimal positive representable (normal) number is:</p>
<pre><code>1.0000 00000000 00000000 00000000 00000000 00000000 00000000 × 2^-1022 = 2^-1022
</code></pre>
<p>In fact there are <code>(1022 - 52 + 1)×2^52 = 4372995238176751616</code> numbers between 0 and epsilon, which is 47% of all the positive representable numbers...</p> | {
"question_id": 13698927,
"question_date": "2012-12-04T08:41:30.473Z",
"question_score": 223,
"tags": "c++|floating-point|double",
"answer_id": 13699489,
"answer_date": "2012-12-04T09:17:49.973Z",
"answer_score": 205
} |
Please answer the following Stack Overflow question:
Title: Protecting executable from reverse engineering?
<p>I've been contemplating how to protect my C/C++ code from disassembly and reverse engineering. Normally I would never condone this behavior myself in my code; however the current protocol I've been working on must not ever be inspected or understandable, for the security of various people.</p>
<p>Now this is a new subject to me, and the internet is not really resourceful for <em>prevention against reverse engineering</em> but rather depicts tons of information on <em>how to reverse engineer</em></p>
<p>Some of the things I've thought of so far are:</p>
<ul>
<li>Code injection (calling dummy functions before and after actual function calls)</li>
<li>Code obfustication (mangles the disassembly of the binary)</li>
<li><p>Write my own startup routines (harder for debuggers to bind to) </p>
<p></p>
<pre><code>void startup();
int _start()
{
startup( );
exit (0)
}
void startup()
{
/* code here */
}
</code></pre></li>
<li><p>Runtime check for debuggers (and force exit if detected)</p></li>
<li><p>Function trampolines</p>
<p></p>
<pre><code> void trampoline(void (*fnptr)(), bool ping = false)
{
if(ping)
fnptr();
else
trampoline(fnptr, true);
}
</code></pre></li>
<li><p>Pointless allocations and deallocations (stack changes a lot)</p></li>
<li>Pointless dummy calls and trampolines (tons of jumping in disassembly output)</li>
<li>Tons of casting (for obfuscated disassembly)</li>
</ul>
<p>I mean these are some of the things I've thought of but they can all be worked around and or figured out by code analysts given the right time frame. Is there anything else alternative I have?</p> | <p>What Amber said is exactly right. You can make reverse engineering harder, but you can never prevent it. You should never trust <a href="http://en.wikipedia.org/wiki/Security_through_obscurity" rel="noreferrer">"security" that relies on the prevention of reverse engineering</a>.</p>
<p>That said, the best anti-reverse-engineering techniques that I've seen focused not on obfuscating the code, but instead on breaking the tools that people usually use to understand how code works. Finding creative ways to break disassemblers, debuggers, etc is both likely to be more effective and also more intellectually satisfying than just generating reams of horrible spaghetti code. This does nothing to block a determined attacker, but it does increase the likelihood that J Random Cracker will wander off and work on something easier instead.</p> | {
"question_id": 6481668,
"question_date": "2011-06-26T01:49:24.543Z",
"question_score": 223,
"tags": "c++|c|obfuscation|assembly",
"answer_id": 6481695,
"answer_date": "2011-06-26T01:57:12.847Z",
"answer_score": 156
} |
Please answer the following Stack Overflow question:
Title: Piping command output to tee but also save exit code of command
<p>I have a shell script in which I wrap a command (mvn clean install), to redirect the output to a logfile. </p>
<pre><code>#!/bin/bash
...
mvn clean install $@ | tee $logfile
echo $? # Does not show the return code of mvn clean install
</code></pre>
<p>Now if <code>mvn clean install</code> fails with an error, I want my wrapper shell script also fail with that error. But since I'm piping all the output to tee, I cannot access the return code of <code>mvn clean install</code>, so when I access <code>$?</code> afterwards, it's always 0 (since tee successes). </p>
<p>I tried letting the command write the error output to a separate file and checking that afterwards, but the error output of mvn is always empty (seems like it only writes to stdout).</p>
<p>How can I preserve the return code of <code>mvn clean install</code> but still piping the output to a logfile?</p> | <p>Since you're running <code>bash</code>, you can use its <a href="http://tldp.org/LDP/abs/html/internalvariables.html#PIPESTATUSREF" rel="noreferrer">$PIPESTATUS</a> variable instead of <code>$?</code>:</p>
<pre><code>mvn clean install $@ | tee $logfile
echo ${PIPESTATUS[0]}
</code></pre> | {
"question_id": 6871859,
"question_date": "2011-07-29T10:36:42.423Z",
"question_score": 223,
"tags": "bash|shell|pipe|sh|tee",
"answer_id": 6871917,
"answer_date": "2011-07-29T10:42:19.487Z",
"answer_score": 204
} |
Please answer the following Stack Overflow question:
Title: How do I hide .class files from the Open Resource dialog in Eclipse?
<p>I won't want to have edit any working sets. I just want a way to, across all workspaces and projects, prevent .class files from ever showing in the Open Resource Dialog. Is there a way to do this?</p> | <p>One option is to filter derived resources. In the upper right corner of the 'Open Resource' dialog there is an arrow you can click to bring up a dropdown menu for filtering. Uncheck the 'Show Derived Resources' option, if it is checked.</p>
<p>If you still see '.class' files, they probably aren't being marked as derived. If they're by themselves in their own folder hierarchy you can fix this by right-clicking the root folder to edit folder properties, and check the 'Derived' checkbox. If they're mixed with your '.java' files...tough luck, you'll need to set the derived property on each '.class' file by hand.</p>
<p>As far as I can tell there's no way to mark class files as derived resources globally for the workspace, but I believe when you create a new Java project the 'bin' folder is marked as derived by default (if you use the default wizard settings)</p>
<hr>
<p>Here are some screenshots from Eclipse Kepler. The first shows how to filter derived resources by unchecking 'Show Derived Resources' in the Open Resource dialog. The second shows how to set the 'Derived' property on a resource.</p>
<p><img src="https://i.stack.imgur.com/Ps18I.png" alt="enter image description here"> </p>
<p><img src="https://i.stack.imgur.com/0I6T3.png" alt="enter image description here"> </p> | {
"question_id": 2632419,
"question_date": "2010-04-13T19:05:35.553Z",
"question_score": 223,
"tags": "java|eclipse",
"answer_id": 2632809,
"answer_date": "2010-04-13T20:04:13.853Z",
"answer_score": 251
} |
Please answer the following Stack Overflow question:
Title: How costly is .NET reflection?
<p>I constantly hear how bad reflection is to use. While I generally avoid reflection and rarely find situations where it is impossible to solve my problem without it, I was wondering... </p>
<p>For those who have used reflection in applications, have you measured performance hits and, is it really so bad?</p> | <p>It is. But that depends on what you're trying to do. </p>
<p>I use reflection to dynamically load assemblies (plugins) and its performance "penalty" is not a problem, since the operation is something I do during startup of the application.</p>
<p>However, if you're reflecting inside a series of nested loops with reflection calls on each, I'd say you should revisit your code :)</p>
<p>For "a couple of time" operations, reflection is perfectly acceptable and you won't notice any delay or problem with it. It's a very powerful mechanism and it is even used by .NET, so I don't see why you shouldn't give it a try. </p> | {
"question_id": 25458,
"question_date": "2008-08-24T23:40:16.647Z",
"question_score": 223,
"tags": "c#|.net|performance|reflection",
"answer_id": 25465,
"answer_date": "2008-08-24T23:48:33.947Z",
"answer_score": 142
} |
Please answer the following Stack Overflow question:
Title: Using Emacs to recursively find and replace in text files not already open
<p>As a follow-up to <a href="https://stackoverflow.com/questions/269812/how-to-quickly-get-started-at-using-and-learning-emacs">this question</a>, it's trying to find out how to do something like this which should be easy, that especially stops me from getting more used to using Emacs and instead starting up the editor I'm already familiar with. I use the example here fairly often in editing multiple files.</p>
<p>In Ultraedit I'd do Alt+s then p to display a dialog box with the options: Find (includes using regular expressions across multiple lines), Replace with, In Files/Types, Directory, Match Case, Match Whole Word Only, List Changed Files and Search Sub Directories. Usually I'll first use the mouse to click-drag select the text that I want to replace.</p>
<p>Using only Emacs itself (on Windows XP), without calling any external utility, how to replace all foo\nbar with bar\nbaz in <code>*.c</code> and <code>*.h</code> files in some folder and all folders beneath it. Maybe Emacs is not the best tool to do this with, but how can it be done easily with a minimal command?</p> | <ol>
<li><code>M-x find-name-dired</code>: you will be prompted for a root directory and a filename pattern.</li>
<li>Press <code>t</code> to "toggle mark" for all files found.</li>
<li>Press <code>Q</code> for "Query-Replace in Files...": you will be prompted for query/substitution regexps.</li>
<li>Proceed as with <code>query-replace-regexp</code>: <code>SPACE</code> to replace and move to next match, <code>n</code> to skip a match, etc.</li>
<li>Press <code>C-x s</code> to save buffers. (You can then press <code>y</code> for yes, <code>n</code> for no, or <code>!</code> for yes for all)</li>
</ol> | {
"question_id": 270930,
"question_date": "2008-11-07T01:02:58.347Z",
"question_score": 223,
"tags": "emacs|editor",
"answer_id": 271136,
"answer_date": "2008-11-07T03:13:35.790Z",
"answer_score": 401
} |
Please answer the following Stack Overflow question:
Title: What is Kestrel (vs IIS / Express)
<p>What is the kestrel web server and how does it relate to IIS / IIS Express?</p>
<p>I come from developing apps on IIS Express and hosting them on an IIS web server. With ASP.NET Core I have a dependency on <code>Microsoft.AspNetCore.Server.Kestrel</code> and my startup has <code>.UseServer("Microsoft.AspNetCore.Server.Kestrel")</code>. But when I run my website, I still get the IIS Express icon in the system tray. Someone asked me if I was using IIS Express or Kestrel and I didn't know what to say!</p>
<p>I don't have any cross-platform requirements as I develop on a PC and host in Azure, so I'm confused if I even <code>need</code> Kestrel, but it doesn't seem like there's an alternative - even the simplest samples use Kestrel.</p> | <blockquote>
<p>What is Kestrel</p>
</blockquote>
<p>It's a full blown web server. You can run your ASP.NET Core application using just Kestrel.</p>
<blockquote>
<p>But when I run my website, I still get the IIS Express icon in the system tray</p>
</blockquote>
<p>In your ASP.NET application, probably in the <code>wwwroot</code> directory, you'll see a web.config that contains this:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<add name="httpPlatformHandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified"/>
</handlers>
<httpPlatform processPath="%DNX_PATH%" arguments="%DNX_ARGS%" stdoutLogEnabled="false" startupTimeLimit="3600"/>
</system.webServer>
</configuration>
</code></pre>
<p>This is the HttpPlatformHandler. Essentially, what this does is forward <em>all</em> requests to Kestrel. IIS Express (and IIS for that matter) will not run ASP.NET themselves anymore. Instead, they will act as proxies that simply pass requests and responses back and forth from Kestrel. There is still advantages of using IIS, specifically it gives you security configuration, kernel-level caching, etc.</p> | {
"question_id": 35639205,
"question_date": "2016-02-25T21:58:03.403Z",
"question_score": 223,
"tags": "asp.net|iis|asp.net-core|kestrel-http-server",
"answer_id": 35639343,
"answer_date": "2016-02-25T22:07:18.003Z",
"answer_score": 153
} |
Please answer the following Stack Overflow question:
Title: Aspect Oriented Programming vs. Object-Oriented Programming
<p>Like most developers here and in the entire world, I have been developing software systems using object-oriented programming (OOP) techniques for many years. So when I read that aspect-oriented programming (AOP) addresses many of the problems that traditional OOP doesn't solve completely or directly, I pause and think, is it real?</p>
<p>I have read a lot of information trying to learn the keys of this AOP paradigm and I´m in the same place, so, I wanted to better understand its benefits in real world application development.</p>
<p>Does somebody have the answer?</p> | <p>Why "vs"? It is not "vs". You can use Aspect Oriented programming in combination with functional programming, but also in combination with Object Oriented one. It is not "vs", it is "Aspect Oriented Programming <strong>with</strong> Object Oriented Programming".</p>
<p>To me AOP is some kind of "meta-programming". Everything that AOP does could also be done without it by just adding more code. AOP just saves you writing this code.</p>
<p>Wikipedia has one of the best examples for this meta-programming. Assume you have a graphical class with many "set...()" methods. After each set method, the data of the graphics changed, thus the graphics changed and thus the graphics need to be updated on screen. Assume to repaint the graphics you must call "Display.update()". The classical approach is to solve this by adding <em>more code</em>. At the end of each set method you write</p>
<pre><code>void set...(...) {
:
:
Display.update();
}
</code></pre>
<p>If you have 3 set-methods, that is not a problem. If you have 200 (hypothetical), it's getting real painful to add this everywhere. Also whenever you add a new set-method, you must be sure to not forget adding this to the end, otherwise you just created a bug.</p>
<p>AOP solves this without adding tons of code, instead you add an aspect:</p>
<pre><code>after() : set() {
Display.update();
}
</code></pre>
<p>And that's it! Instead of writing the update code yourself, you just tell the system that after a set() pointcut has been reached, it must run this code and it will run this code. No need to update 200 methods, no need to make sure you don't forget to add this code on a new set-method. Additionally you just need a pointcut:</p>
<pre><code>pointcut set() : execution(* set*(*) ) && this(MyGraphicsClass) && within(com.company.*);
</code></pre>
<p>What does that mean? That means if a method is named "set*" (* means any name might follow after set), regardless of what the method returns (first asterisk) or what parameters it takes (third asterisk) <em>and</em> it is a method of MyGraphicsClass <em>and</em> this class is part of the package "com.company.*", then this is a set() pointcut. And our first code says "<em>after</em> running any method that is a set pointcut, run the following code".</p>
<p>See how AOP elegantly solves the problem here? Actually everything described here can be done at compile time. A AOP preprocessor can just modify your source (e.g. adding Display.update() to the end of every set-pointcut method) before even compiling the class itself.</p>
<p>However, this example also shows one of the big downsides of AOP. AOP is actually doing something that many programmers consider an "<strong><a href="http://en.wikipedia.org/wiki/Anti-pattern" rel="noreferrer">Anti-Pattern</a></strong>". The exact pattern is called "<a href="http://en.wikipedia.org/wiki/Action_at_a_distance_(computer_science)" rel="noreferrer">Action at a distance</a>".</p>
<blockquote>
<p>Action at a distance is an
anti-pattern (a recognized common
error) in which behavior in one part
of a program varies wildly based on
difficult or impossible to identify
operations in another part of the
program.</p>
</blockquote>
<p>As a newbie to a project, I might just read the code of any set-method and consider it broken, as it seems to not update the display. I don't <strong>see</strong> by just looking at the code of a set-method, that after it is executed, some other code will "magically" be executed to update the display. I consider this a serious downside! By making changes to a method, strange bugs might be introduced. Further understanding the code flow of code where certain things seem to work correctly, but are not obvious (as I said, they just magically work... somehow), is really hard.</p>
<h2>Update</h2>
<p>Just to clarify that: Some people might have the impression I'm saying AOP is something bad and should not be used. That's not what I'm saying! AOP is actually a great feature. I just say "Use it carefully". AOP will only cause problems if you mix up normal code and AOP for the same <em>Aspect</em>. In the example above, we have the Aspect of updating the values of a graphical object and painting the updated object. That is in fact a single aspect. Coding half of it as normal code and the other half of it as aspect is what adds the problem.</p>
<p>If you use AOP for a completely different aspect, e.g. for logging, you will not run into the anti-pattern problem. In that case a newbie to the project might wonder "Where do all these log messages come from? I don't see any log output in the code", but that is not a huge problem. Changes he makes to the program logic will hardly break the log facility and changes made to the log facility will hardly break his program logic - these aspects are totally separated. Using AOP for logging has the advantage that your program code can fully concentrate on doing whatever it should do and you still can have sophisticated logging, without having your code being cluttered up by hundreds of log messages everywhere. Also when new code is introduced, magically log messages will appear at the right time with the right content. The newbie programmer might not understand why they are there or where they came from, but since they will log the "right thing" at the "right time", he can just happily accept the fact that they are there and move on to something else.</p>
<p>So a good usage of AOP in my example would be to always log if any value has been updated via a set method. This will not create an anti-pattern and hardly ever be the cause of any problem.</p>
<p>One might say, if you can easily abuse AOP to create so many problems, it's a bad idea to use it all. However which technology can't be abused? You can abuse data encapsulation, you can abuse inheritance. Pretty much every useful programming technology can be abused. Consider a programming language so limited that it only contains features that can't be abused; a language where features can only be used as they were initially intended to be used. Such a language would be so limited that it's arguable if it can be even used for real world programming.</p> | {
"question_id": 232884,
"question_date": "2008-10-24T09:00:46.373Z",
"question_score": 223,
"tags": "oop|aop|paradigms",
"answer_id": 232918,
"answer_date": "2008-10-24T09:21:17.003Z",
"answer_score": 359
} |
Please answer the following Stack Overflow question:
Title: Akka Kill vs. Stop vs. Poison Pill?
<p>Newbie question of Akka - I'm reading over Akka Essentials, could someone please explain the difference between Akka Stop/Poison Pill vs. Kill ? The book offers just a small explaination "Kill is synchronous vs. Poison pill is asynchronous." But in what way? Does the calling actor thread lock during this time? Are the children actors notified during kill, post-stop envoked, etc? Example uses of one concept vs. the other?</p>
<p>Many thanks!</p> | <p>Both <code>stop</code> and <code>PoisonPill</code> will terminate the actor and stop the message queue. They will cause the actor to cease processing messages, send a stop call to all its children, wait for them to terminate, then call its <code>postStop</code> hook. All further messages are sent to the dead letters mailbox.</p>
<p>The difference is in which messages get processed before this sequence starts. In the case of the <code>stop</code> call, the message currently being processed is completed first, with all others discarded. When sending a <code>PoisonPill</code>, this is simply another message in the queue, so the sequence will start when the <code>PoisonPill</code> is received. All messages that are ahead of it in the queue will be processed first.</p>
<p>By contrast, the <code>Kill</code> message causes the actor to throw an <code>ActorKilledException</code> which gets handled using the normal supervisor mechanism. So the behaviour here depends on what you've defined in your supervisor strategy. The default is to stop the actor. But the mailbox persists, so when the actor restarts it will still have the old messages except for the one that caused the failure.</p>
<p>Also see the 'Stopping an Actor', 'Killing an Actor' section in the docs:</p>
<p><a href="http://doc.akka.io/docs/akka/snapshot/scala/actors.html">http://doc.akka.io/docs/akka/snapshot/scala/actors.html</a></p>
<p>And more on supervision strategies:</p>
<p><a href="http://doc.akka.io/docs/akka/snapshot/scala/fault-tolerance.html">http://doc.akka.io/docs/akka/snapshot/scala/fault-tolerance.html</a></p> | {
"question_id": 13847963,
"question_date": "2012-12-12T20:22:11.240Z",
"question_score": 223,
"tags": "scala|akka",
"answer_id": 13848350,
"answer_date": "2012-12-12T20:49:21.433Z",
"answer_score": 341
} |
Please answer the following Stack Overflow question:
Title: Why Func<T,bool> instead of Predicate<T>?
<p>This is just a curiosity question I was wondering if anyone had a good answer to:</p>
<p>In the .NET Framework Class Library we have for example these two methods:</p>
<pre><code>public static IQueryable<TSource> Where<TSource>(
this IQueryable<TSource> source,
Expression<Func<TSource, bool>> predicate
)
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate
)
</code></pre>
<p>Why do they use <code>Func<TSource, bool></code> instead of <code>Predicate<TSource></code>? Seems like the <code>Predicate<TSource></code> is only used by <code>List<T></code> and <code>Array<T></code>, while <code>Func<TSource, bool></code> is used by pretty much all <code>Queryable</code> and <code>Enumerable</code> methods and extension methods... what's up with that?</p> | <p>While <code>Predicate</code> has been introduced at the same time that <code>List<T></code> and <code>Array<T></code>, in .net 2.0, the different <code>Func</code> and <code>Action</code> variants come from .net 3.5.</p>
<p>So those <code>Func</code> predicates are used mainly for consistency in the LINQ operators. As of .net 3.5, about using <code>Func<T></code> and <code>Action<T></code> the <a href="https://docs.microsoft.com/en-us/archive/blogs/mirceat/linq-framework-design-guidelines#2-extension-methods-func-action-and-expression" rel="noreferrer">guideline states</a>:</p>
<blockquote>
<p>Do use the new LINQ types <code>Func<></code> and
<code>Expression<></code> instead of custom
delegates and predicates</p>
</blockquote> | {
"question_id": 665494,
"question_date": "2009-03-20T09:39:31.037Z",
"question_score": 223,
"tags": "c#|.net|predicate|func",
"answer_id": 665513,
"answer_date": "2009-03-20T09:47:46.803Z",
"answer_score": 179
} |
Please answer the following Stack Overflow question:
Title: Why is it wrong to use std::auto_ptr<> with standard containers?
<p>Why is it wrong to use <code>std::auto_ptr<></code> with standard containers?</p> | <p>The C++ Standard says that an STL element must be "copy-constructible" and "assignable." In other words, an element must be able to be assigned or copied and the two elements are logically independent. <code>std::auto_ptr</code> does not fulfill this requirement.</p>
<p>Take for example this code:</p>
<pre><code>class X
{
};
std::vector<std::auto_ptr<X> > vecX;
vecX.push_back(new X);
std::auto_ptr<X> pX = vecX[0]; // vecX[0] is assigned NULL.
</code></pre>
<p>To overcome this limitation, you should use the <a href="http://msdn.microsoft.com/en-us/library/ee410601.aspx" rel="noreferrer"><code>std::unique_ptr</code></a>, <a href="http://msdn.microsoft.com/en-us/library/bb982026.aspx" rel="noreferrer"><code>std::shared_ptr</code></a> or <a href="http://msdn.microsoft.com/en-us/library/bb982126.aspx" rel="noreferrer"><code>std::weak_ptr</code></a> smart pointers or the boost equivalents if you don't have C++11. <a href="http://www.boost.org/doc/libs/1_54_0/libs/smart_ptr/smart_ptr.htm" rel="noreferrer">Here is the boost library documentation for these smart pointers.</a> </p> | {
"question_id": 111478,
"question_date": "2008-09-21T17:27:28.360Z",
"question_score": 223,
"tags": "c++|stl|raii|auto-ptr|c++-faq",
"answer_id": 111531,
"answer_date": "2008-09-21T17:47:35.863Z",
"answer_score": 125
} |
Please answer the following Stack Overflow question:
Title: Writing a compiler in its own language
<p>Intuitively, it would seems that a compiler for language <code>Foo</code> cannot itself be written in Foo. More specifically, the <em>first</em> compiler for language <code>Foo</code> cannot be written in Foo, but any subsequent compiler could be written for <code>Foo</code>.</p>
<p>But is this actually true? I have some very vague recollection of reading about a language whose first compiler was written in "itself". Is this possible, and if so how?</p> | <p>This is called "bootstrapping". You must first build a compiler (or interpreter) for your language in some other language (usually Java or C). Once that is done, you can write a new version of the compiler in language Foo. You use the first bootstrap compiler to compile the compiler, and then use this compiled compiler to compile everything else (including future versions of itself).</p>
<p>Most languages are indeed created in this fashion, partially because language designers like to use the language they are creating, and also because a non-trivial compiler often serves as a useful benchmark for how "complete" the language may be.</p>
<p>An example of this would be Scala. Its first compiler was created in Pizza, an experimental language by Martin Odersky. As of version 2.0, the compiler was completely re-written in Scala. From that point on, the old Pizza compiler could be completely discarded, due to the fact that the new Scala compiler could be used to compile itself for future iterations.</p> | {
"question_id": 193560,
"question_date": "2008-10-11T01:30:56.600Z",
"question_score": 223,
"tags": "compiler-construction|bootstrapping",
"answer_id": 193562,
"answer_date": "2008-10-11T01:34:48.493Z",
"answer_score": 258
} |
Please answer the following Stack Overflow question:
Title: Comparing strings with == which are declared final in Java
<p>I have a simple question about strings in Java. The following segment of simple code just concatenates two strings and then compares them with <code>==</code>.</p>
<pre><code>String str1="str";
String str2="ing";
String concat=str1+str2;
System.out.println(concat=="string");
</code></pre>
<p>The comparison expression <code>concat=="string"</code> returns <code>false</code> as obvious (I understand the difference between <code>equals()</code> and <code>==</code>).</p>
<hr>
<p>When these two strings are declared <code>final</code> like so,</p>
<pre><code>final String str1="str";
final String str2="ing";
String concat=str1+str2;
System.out.println(concat=="string");
</code></pre>
<p>The comparison expression <code>concat=="string"</code>, in this case returns <code>true</code>. Why does <code>final</code> make a difference? Does it have to do something with the intern pool or I'm just being misled?</p> | <p>When you declare a <code>String</code> (which is <em>immutable</em>) variable as <code>final</code>, and initialize it with a compile-time constant expression, it also becomes a compile-time constant expression, and its value is inlined by the compiler where it is used. So, in your second code example, after inlining the values, the string concatenation is translated by the compiler to:</p>
<pre><code>String concat = "str" + "ing"; // which then becomes `String concat = "string";`
</code></pre>
<p>which when compared to <code>"string"</code> will give you <code>true</code>, because string literals are <em>interned</em>.</p>
<p>From <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.4-300">JLS §4.12.4 - <code>final</code> Variables</a>:</p>
<blockquote>
<p>A variable of primitive type or type <code>String</code>, that is <code>final</code> and initialized with a compile-time constant expression (§15.28), is called a <em>constant variable</em>.</p>
</blockquote>
<p>Also from <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28-200">JLS §15.28 - Constant Expression:</a></p>
<blockquote>
<p>Compile-time constant expressions of type <code>String</code> are always <em>"interned"</em> so as to share unique instances, using the method <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern%28%29"><code>String#intern()</code></a>.</p>
</blockquote>
<hr />
<p>This is not the case in your first code example, where the <code>String</code> variables are not <code>final</code>. So, they are not a compile-time constant expressions. The concatenation operation there will be delayed till runtime, thus leading to the creation of a new <code>String</code> object. You can verify this by comparing byte code of both the codes.</p>
<p>The first code example <strong>(non-<code>final</code> version)</strong> is compiled to the following byte code:</p>
<pre><code> Code:
0: ldc #2; //String str
2: astore_1
3: ldc #3; //String ing
5: astore_2
6: new #4; //class java/lang/StringBuilder
9: dup
10: invokespecial #5; //Method java/lang/StringBuilder."<init>":()V
13: aload_1
14: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
17: aload_2
18: invokevirtual #6; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
21: invokevirtual #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
24: astore_3
25: getstatic #8; //Field java/lang/System.out:Ljava/io/PrintStream;
28: aload_3
29: ldc #9; //String string
31: if_acmpne 38
34: iconst_1
35: goto 39
38: iconst_0
39: invokevirtual #10; //Method java/io/PrintStream.println:(Z)V
42: return
</code></pre>
<p>Clearly it is storing <code>str</code> and <code>ing</code> in two separate variables, and using <code>StringBuilder</code> to perform the concatenation operation.</p>
<p>Whereas, your second code example <strong>(<code>final</code> version)</strong> looks like this:</p>
<pre><code> Code:
0: ldc #2; //String string
2: astore_3
3: getstatic #3; //Field java/lang/System.out:Ljava/io/PrintStream;
6: aload_3
7: ldc #2; //String string
9: if_acmpne 16
12: iconst_1
13: goto 17
16: iconst_0
17: invokevirtual #4; //Method java/io/PrintStream.println:(Z)V
20: return
</code></pre>
<p>So it directly inlines the final variable to create String <code>string</code> at compile time, which is loaded by <code>ldc</code> operation in step <code>0</code>. Then the second string literal is loaded by <code>ldc</code> operation in step <code>7</code>. It doesn't involve creation of any new <code>String</code> object at runtime. The String is already known at compile time, and they are interned.</p> | {
"question_id": 19418427,
"question_date": "2013-10-17T04:41:11.363Z",
"question_score": 223,
"tags": "java|string|final",
"answer_id": 19418517,
"answer_date": "2013-10-17T04:49:10.997Z",
"answer_score": 235
} |
Please answer the following Stack Overflow question:
Title: Convert JSON String to JSON Object c#
<p>I have this String stored in my database:</p>
<pre><code>str = "{ "context_name": { "lower_bound": "value", "upper_bound": "value", "values": [ "value1", "valueN" ] } }"
</code></pre>
<p>This string is already in the JSON format but I want to convert it into a JObject or JSON Object.</p>
<pre><code>JObject json = new JObject();
</code></pre>
<p>I tried the <code>json = (JObject)str;</code> cast but it didn't work so how can I do it?</p> | <p><code>JObject</code> defines method <code>Parse</code> for this:</p>
<pre><code>JObject json = JObject.Parse(str);
</code></pre>
<p>You might want to refer to Json.NET <a href="http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_Linq_JObject.htm">documentation</a>.</p> | {
"question_id": 22870624,
"question_date": "2014-04-04T18:41:18.607Z",
"question_score": 222,
"tags": "c#|asp.net|json|string|parsing",
"answer_id": 22870647,
"answer_date": "2014-04-04T18:42:48.367Z",
"answer_score": 381
} |
Please answer the following Stack Overflow question:
Title: How to center content in a Bootstrap column?
<p>I am trying to center column's content. Does not look like it works for me. Here is my HTML:</p>
<pre><code><div class="row">
<div class="col-xs-1 center-block">
<span>aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
</div>
</div>
</code></pre>
<p><a href="https://jsfiddle.net/usth0kd2/2/" rel="noreferrer">JSFiddle Demo</a></p> | <p>Use:</p>
<pre><code><!-- unsupported by HTML5 -->
<div class="col-xs-1" align="center">
</code></pre>
<p>instead of</p>
<pre><code><div class="col-xs-1 center-block">
</code></pre>
<p>You can also use bootstrap 3 css:</p>
<pre><code><!-- recommended method -->
<div class="col-xs-1 text-center">
</code></pre>
<p>Bootstrap 4 now has flex classes that will center the content:</p>
<pre><code><div class="d-flex justify-content-center">
<div>some content</div>
</div>
</code></pre>
<p>Note that by default it will be <code>x-axis</code> unless <code>flex-direction</code> is <code>column</code></p> | {
"question_id": 35163164,
"question_date": "2016-02-02T20:26:46.487Z",
"question_score": 222,
"tags": "html|css|twitter-bootstrap",
"answer_id": 35163389,
"answer_date": "2016-02-02T20:40:56.997Z",
"answer_score": 325
} |
Please answer the following Stack Overflow question:
Title: How can I convert string to datetime with format specification in JavaScript?
<p>How can I convert a string to a date time object in javascript by specifying a format string?</p>
<p>I am looking for something like:</p>
<pre><code>var dateTime = convertToDateTime("23.11.2009 12:34:56", "dd.MM.yyyy HH:mm:ss");
</code></pre> | <p>I think this can help you: <a href="https://web.archive.org/web/20090114044719/http://www.mattkruse.com/javascript/date/" rel="nofollow noreferrer">http://www.mattkruse.com/javascript/date/</a></p>
<p>There's a <code>getDateFromFormat()</code> function that you can tweak a little to solve your problem.</p>
<p>Update: there's an updated version of the samples available at <a href="https://web.archive.org/web/20090123134657/http://www.javascripttoolbox.com/lib/date/index.php" rel="nofollow noreferrer">javascripttoolbox.com</a></p> | {
"question_id": 476105,
"question_date": "2009-01-24T14:56:46.810Z",
"question_score": 222,
"tags": "javascript|datetime|type-conversion",
"answer_id": 476121,
"answer_date": "2009-01-24T15:10:31.057Z",
"answer_score": 86
} |
Please answer the following Stack Overflow question:
Title: Calling a function on Bootstrap modal open
<p>I used to use jQuery UI's dialog, and it had the <code>open</code> option, where you can specify some Javascript code to execute once the dialog is opened. I would have used that option to select the text within the dialog using a function I have.</p>
<p>Now I want to do that using bootstrap's modal. Below is the HTMl code:</p>
<pre><code><div id="code" class="modal hide fade">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h3>Modal header</h3>
</div>
<div class="modal-body">
<pre>
print 'Hello World'
</code></pre>
<p>And as for the button that opens the modal:</p>
<pre><code> <a href="#code" data-toggle="modal" class="btn code-dialog">Display code</a>
</code></pre>
<p>I tried to use an onclick listener of the button, but the alert message was displayed <em>before</em> the modal appeared:</p>
<pre><code>$( ".code-dialog" ).click(function(){
alert("I want this to appear after the modal has opened!");
});
</code></pre> | <p>You can use the <a href="https://getbootstrap.com/2.3.2/javascript.html#modals" rel="noreferrer">shown event</a>/show event based on what you need:</p>
<pre><code>$( "#code" ).on('shown', function(){
alert("I want this to appear after the modal has opened!");
});
</code></pre>
<p>Demo: <a href="http://plnkr.co/edit/dawC31?p=preview" rel="noreferrer">Plunker</a></p>
<h2>Update for Bootstrap 3.0</h2>
<p>For Bootstrap 3.0 you can still use the shown event but you would use it like this:</p>
<pre><code>$('#code').on('shown.bs.modal', function (e) {
// do something...
})
</code></pre>
<p><a href="https://getbootstrap.com/docs/3.3/javascript/#js-events" rel="noreferrer">See the Bootstrap 3.0 docs here</a> under "Events".</p> | {
"question_id": 17461682,
"question_date": "2013-07-04T04:03:32.197Z",
"question_score": 222,
"tags": "javascript|jquery|jquery-ui|twitter-bootstrap|modal-dialog",
"answer_id": 17461707,
"answer_date": "2013-07-04T04:06:25.787Z",
"answer_score": 412
} |
Please answer the following Stack Overflow question:
Title: Spring JPA selecting specific columns
<p>I am using Spring JPA to perform all database operations. However I don't know how to select specific columns from a table in Spring JPA?</p>
<p>For example:<br/>
<code>SELECT projectId, projectName FROM projects</code></p> | <p>You can set <code>nativeQuery = true</code> in the <code>@Query</code> annotation from a <code>Repository</code> class like this:</p>
<pre><code>public static final String FIND_PROJECTS = "SELECT projectId, projectName FROM projects";
@Query(value = FIND_PROJECTS, nativeQuery = true)
public List<Object[]> findProjects();
</code></pre>
<p>Note that you will have to do the mapping yourself though. It's probably easier to just use the regular mapped lookup like this unless you really only need those two values:</p>
<pre><code>public List<Project> findAll()
</code></pre>
<p>It's probably worth looking at the Spring data <a href="http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query" rel="noreferrer">docs</a> as well.</p> | {
"question_id": 22007341,
"question_date": "2014-02-25T07:25:26.020Z",
"question_score": 222,
"tags": "java|jpa|spring-data-jpa",
"answer_id": 22007664,
"answer_date": "2014-02-25T07:43:34.167Z",
"answer_score": 101
} |
Please answer the following Stack Overflow question:
Title: Array.Add vs +=
<p>I've found some interesting behaviour in PowerShell Arrays, namely, if I declare an array as:</p>
<pre><code>$array = @()
</code></pre>
<p>And then try to add items to it using the <code>$array.Add("item")</code> method, I receive the following error:</p>
<blockquote>
<p>Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."</p>
</blockquote>
<p>However, if I append items using <code>$array += "item"</code>, the item is accepted without a problem and the "fixed size" restriction doesn't seem to apply.</p>
<p>Why is this?</p> | <p>When using the <code>$array.Add()</code>-method, you're trying to add the element into the existing array. An array is a collection of fixed size, so you will receive an error because it can't be extended.</p>
<p><code>$array += $element</code> creates a <strong>new</strong> array with the same elements as old one + the new item, and this new larger array replaces the old one in the <code>$array</code>-variable </p>
<blockquote>
<p>You can use the += operator to add an element to an array. When you
use
it, Windows PowerShell actually creates a new array with the values of the
original array and the added value. For example, to add an element with a
value of 200 to the array in the $a variable, type:</p>
<pre><code> $a += 200
</code></pre>
</blockquote>
<p>Source: <a href="http://technet.microsoft.com/en-us/library/hh847882.aspx" rel="noreferrer">about_Arrays</a></p>
<p><code>+=</code> is an expensive operation, so when you need to add many items you should try to add them in as few operations as possible, ex:</p>
<pre><code>$arr = 1..3 #Array
$arr += (4..5) #Combine with another array in a single write-operation
$arr.Count
5
</code></pre>
<p>If that's not possible, consider using a more efficient collection like <code>List</code> or <code>ArrayList</code> (see the other answer).</p> | {
"question_id": 14620290,
"question_date": "2013-01-31T07:10:36.783Z",
"question_score": 222,
"tags": "arrays|powershell",
"answer_id": 14620446,
"answer_date": "2013-01-31T07:19:11.650Z",
"answer_score": 303
} |
Please answer the following Stack Overflow question:
Title: Testing whether a value is odd or even
<p>I decided to create simple <em>isEven</em> and <em>isOdd</em> function with a very simple algorithm:</p>
<pre><code>function isEven(n) {
n = Number(n);
return n === 0 || !!(n && !(n%2));
}
function isOdd(n) {
return isEven(Number(n) + 1);
}
</code></pre>
<p>That is OK if n is with certain parameters, but fails for many scenarios. So I set out to create robust functions that deliver correct results for as many scenarios as I could, so that only integers within the limits of javascript numbers are tested, everything else returns false (including + and - infinity). Note that zero is even.</p>
<pre><code>// Returns true if:
//
// n is an integer that is evenly divisible by 2
//
// Zero (+/-0) is even
// Returns false if n is not an integer, not even or NaN
// Guard against empty string
(function (global) {
function basicTests(n) {
// Deal with empty string
if (n === '')
return false;
// Convert n to Number (may set to NaN)
n = Number(n);
// Deal with NaN
if (isNaN(n))
return false;
// Deal with infinity -
if (n === Number.NEGATIVE_INFINITY || n === Number.POSITIVE_INFINITY)
return false;
// Return n as a number
return n;
}
function isEven(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Convert to Number and proceed
n = Number(n);
// Return true/false
return n === 0 || !!(n && !(n%2));
}
global.isEven = isEven;
// Returns true if n is an integer and (n+1) is even
// Returns false if n is not an integer or (n+1) is not even
// Empty string evaluates to zero so returns false (zero is even)
function isOdd(n) {
// Do basic tests
if (basicTests(n) === false)
return false;
// Return true/false
return n === 0 || !!(n && (n%2));
}
global.isOdd = isOdd;
}(this));
</code></pre>
<p>Can anyone see any issues with the above? Is there a better (i.e. more accurate, faster or more concise without being obfuscated) version?</p>
<p>There are various posts relating to other languages, but I can't seem to find a definitive version for ECMAScript.</p> | <p>Use modulus:</p>
<pre><code>function isEven(n) {
return n % 2 == 0;
}
function isOdd(n) {
return Math.abs(n % 2) == 1;
}
</code></pre>
<p>You can check that any value in Javascript can be coerced to a number with:</p>
<pre><code>Number.isFinite(parseFloat(n))
</code></pre>
<p>This check should preferably be done outside the <code>isEven</code> and <code>isOdd</code> functions, so you don't have to duplicate error handling in both functions.</p> | {
"question_id": 6211613,
"question_date": "2011-06-02T07:19:01.787Z",
"question_score": 222,
"tags": "javascript|numbers",
"answer_id": 6211660,
"answer_date": "2011-06-02T07:24:34.467Z",
"answer_score": 452
} |
Please answer the following Stack Overflow question:
Title: Generating a random password in php
<p>I am trying to generate a random password in php. </p>
<p>However I am getting all 'a's and the return type is of type array and I would like it to be a string. Any ideas on how to correct the code?</p>
<p>Thanks.</p>
<pre><code>function randomPassword() {
$alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
for ($i = 0; $i < 8; $i++) {
$n = rand(0, count($alphabet)-1);
$pass[$i] = $alphabet[$n];
}
return $pass;
}
</code></pre> | <blockquote>
<p><strong>Security warning</strong>: <code>rand()</code> is not a cryptographically secure pseudorandom number generator. Look elsewhere for <a href="https://stackoverflow.com/a/31284266/2224584">generating a cryptographically secure pseudorandom string in PHP</a>.</p>
</blockquote>
<p>Try this (use <code>strlen</code> instead of <code>count</code>, because <code>count</code> on a string is always <code>1</code>):</p>
<pre><code>function randomPassword() {
$alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$pass = array(); //remember to declare $pass as an array
$alphaLength = strlen($alphabet) - 1; //put the length -1 in cache
for ($i = 0; $i < 8; $i++) {
$n = rand(0, $alphaLength);
$pass[] = $alphabet[$n];
}
return implode($pass); //turn the array into a string
}
</code></pre>
<p><a href="http://codepad.org/UL8k4aYK" rel="noreferrer">Demo</a></p> | {
"question_id": 6101956,
"question_date": "2011-05-23T19:29:28.607Z",
"question_score": 222,
"tags": "php|security|random|passwords",
"answer_id": 6101969,
"answer_date": "2011-05-23T19:30:49.690Z",
"answer_score": 301
} |
Please answer the following Stack Overflow question:
Title: Could not install packages due to an EnvironmentError: [Errno 13]
<p>In my MacOS Mojave terminal I wanted to install a python package with pip. At the end it says:</p>
<pre><code>You are using pip version 10.0.1, however version 18.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
</code></pre>
<p>So I wanted to update pip with the given command but I got an error:</p>
<pre><code>Could not install packages due to an EnvironmentError: [Errno 13] Permission denied:
'/Library/Python/2.7/site-packages/pip-18.0-py2.7.egg/EGG-INFO/PKG-INFO'
Consider using the `--user` option or check the permissions.
</code></pre>
<p>I don't really understand what to do now. <strong>Also I realized it says Python 2.7 in the error message but I have and want to use only python 3.</strong></p> | <p>If you want to use <strong>python3+</strong> to install the packages you need to use <code>pip3 install package_name</code></p>
<p>And to solve the <strong>errno 13</strong> you have to add <code>--user</code> at the end</p>
<pre><code>pip3 install package_name --user
</code></pre>
<hr />
<p><strong>EDIT:</strong></p>
<p>For any project in python it's <strong>highly recommended</strong> to work on a <a href="https://www.geeksforgeeks.org/python-virtual-environment/" rel="noreferrer"><strong>Virtual enviroment</strong></a>, is a tool that helps to keep dependencies required by different projects separate by creating isolated python virtual environments for them.</p>
<p>In order to create one with <strong>python3+</strong> you have to use the following command:</p>
<pre><code>virtualenv enviroment_name -p python3
</code></pre>
<p>And then you work on it just by <strong>activating</strong> it:</p>
<pre><code>source enviroment_name/bin/activate
</code></pre>
<p>Once the virtual environment is activated, the name of your virtual environment will appear on left side of terminal. This will let you know that the virtual environment is currently active.
Now you can install dependencies related to the project in this virtual environment by just using <code>pip</code>.</p>
<pre><code>pip install package_name
</code></pre> | {
"question_id": 52949531,
"question_date": "2018-10-23T12:49:39.417Z",
"question_score": 222,
"tags": "python|macos|pip",
"answer_id": 53916143,
"answer_date": "2018-12-24T17:16:39.423Z",
"answer_score": 325
} |
Please answer the following Stack Overflow question:
Title: Add context path to Spring Boot application
<p>I am trying to set a Spring Boot applications context root programmatically. The reason for the context root is we want the app to be accessed from <code>localhost:port/{app_name}</code> and have all the controller paths append to it. </p>
<p>Here is the application configuration file for the web-app.</p>
<pre><code>@Configuration
public class ApplicationConfiguration {
Logger logger = LoggerFactory.getLogger(ApplicationConfiguration.class);
@Value("${mainstay.web.port:12378}")
private String port;
@Value("${mainstay.web.context:/mainstay}")
private String context;
private Set<ErrorPage> pageHandlers;
@PostConstruct
private void init(){
pageHandlers = new HashSet<ErrorPage>();
pageHandlers.add(new ErrorPage(HttpStatus.NOT_FOUND,"/notfound.html"));
pageHandlers.add(new ErrorPage(HttpStatus.FORBIDDEN,"/forbidden.html"));
}
@Bean
public EmbeddedServletContainerFactory servletContainer(){
TomcatEmbeddedServletContainerFactory factory = new TomcatEmbeddedServletContainerFactory();
logger.info("Setting custom configuration for Mainstay:");
logger.info("Setting port to {}",port);
logger.info("Setting context to {}",context);
factory.setPort(Integer.valueOf(port));
factory.setContextPath(context);
factory.setErrorPages(pageHandlers);
return factory;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
}
</code></pre>
<p>Here is the index controller for the main page. </p>
<pre><code>@Controller
public class IndexController {
Logger logger = LoggerFactory.getLogger(IndexController.class);
@RequestMapping("/")
public String index(Model model){
logger.info("Setting index page title to Mainstay - Web");
model.addAttribute("title","Mainstay - Web");
return "index";
}
}
</code></pre>
<p>The new root of the application should be at <code>localhost:12378/mainstay</code>, but it is still located at <code>localhost:12378</code>. </p>
<p>What am I missing that is causing Spring Boot to not append the context root before the request mapping?</p> | <p>Why are you trying to roll your own solution. Spring-boot already supports that.</p>
<p>If you don't already have one, add an <code>application.properties</code> file to <code>src\main\resources</code>. In that properties file, add 2 properties:</p>
<pre><code>server.contextPath=/mainstay
server.port=12378
</code></pre>
<p><strong>UPDATE (Spring Boot 2.0)</strong></p>
<p>As of Spring Boot 2.0 (due to the support of both Spring MVC and Spring WebFlux) the <code>contextPath</code> has been changed to the following:</p>
<pre><code>server.servlet.context-path=/mainstay
</code></pre>
<p>You can then remove your configuration for the custom servlet container. If you need to do some post processing on the container you can add a <code>EmbeddedServletContainerCustomizer</code> implementation to your configuration (for instance to add the error pages).</p>
<p>Basically the properties inside the <code>application.properties</code> serve as a default you can always override them by using another <code>application.properties</code> next to the artifact you deliver or by adding JVM parameters (<code>-Dserver.port=6666</code>).</p>
<p>See also <a href="http://docs.spring.io/spring-boot/docs/current/reference/html" rel="noreferrer">The Reference Guide</a> especially the <a href="https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties" rel="noreferrer">properties</a> section.</p>
<p>The class <a href="https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java" rel="noreferrer"><code>ServerProperties</code></a> implements the <code>EmbeddedServletContainerCustomizer</code>. The default for <code>contextPath</code> is <code>""</code>. In your code sample you are setting the <code>contextPath</code> directly on the <code>TomcatEmbeddedServletContainerFactory</code>. Next the <code>ServerProperties</code> instance will process this instance and reset it from your path to <code>""</code>. (<a href="https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java#L110" rel="noreferrer">This line</a> does a <code>null</code> check but as the default is <code>""</code> it always fail and set the context to <code>""</code> and thus overriding yours).</p> | {
"question_id": 20405474,
"question_date": "2013-12-05T16:33:59.713Z",
"question_score": 222,
"tags": "java|spring|spring-mvc|spring-boot",
"answer_id": 20418450,
"answer_date": "2013-12-06T07:29:51.593Z",
"answer_score": 451
} |
Please answer the following Stack Overflow question:
Title: How to POST form data with Spring RestTemplate?
<p>I want to convert the following (working) curl snippet to a RestTemplate call:</p>
<pre><code>curl -i -X POST -d "[email protected]" https://app.example.com/hr/email
</code></pre>
<p>How do I pass the email parameter correctly? The following code results in a 404 Not Found response:</p>
<pre><code>String url = "https://app.example.com/hr/email";
Map<String, String> params = new HashMap<String, String>();
params.put("email", "[email protected]");
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.postForEntity( url, params, String.class );
</code></pre>
<p>I've tried to formulate the correct call in PostMan, and I can get it working correctly by specifying the email parameter as a "form-data" parameter in the body. What is the correct way to achieve this functionality in a RestTemplate?</p> | <p>The POST method should be sent along the HTTP request object. And the request may contain either of HTTP header or HTTP body or both. </p>
<p>Hence let's create an HTTP entity and send the headers and parameter in body.</p>
<pre><code>HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "[email protected]");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );
</code></pre>
<p><a href="http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#postForObject-java.lang.String-java.lang.Object-java.lang.Class-java.lang.Object...-" rel="noreferrer">http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#postForObject-java.lang.String-java.lang.Object-java.lang.Class-java.lang.Object...-</a></p> | {
"question_id": 38372422,
"question_date": "2016-07-14T10:59:20.187Z",
"question_score": 222,
"tags": "java|spring|rest|resttemplate",
"answer_id": 38388168,
"answer_date": "2016-07-15T05:01:01.443Z",
"answer_score": 473
} |
Please answer the following Stack Overflow question:
Title: Efficient way to apply multiple filters to pandas DataFrame or Series
<p>I have a scenario where a user wants to <strong>apply several filters to a Pandas DataFrame or Series object</strong>. Essentially, I want to efficiently chain a bunch of filtering (comparison operations) together that are specified at run-time by the user.</p>
<ul>
<li>The filters should be <strong>additive</strong> (aka each one applied should narrow results).</li>
<li>I'm currently using <code>reindex()</code> (as below) but this creates a new object each time and copies the underlying data (if I understand the documentation correctly). I want to avoid this unnecessary copying as it will be really inefficient when filtering a big Series or DataFrame.</li>
<li>I'm thinking that using <code>apply()</code>, <code>map()</code>, or something similar might be better. I'm pretty new to Pandas though so still trying to wrap my head around everything.</li>
<li>Also, I would like to expand this so that <strong>the dictionary passed in can include the columns to operate on</strong> and filter an entire DataFrame based on the input dictionary. However, I'm assuming whatever works for a Series can be easily expanded to a DataFrame.</li>
</ul>
<h2>TL;DR</h2>
<p>I want to take a dictionary of the following form and apply each operation to a given Series object and return a 'filtered' Series object.</p>
<pre><code>relops = {'>=': [1], '<=': [1]}
</code></pre>
<h2>Long Example</h2>
<p>I'll start with an example of what I have currently and just filtering a single Series object. Below is the function I'm currently using:</p>
<pre><code> def apply_relops(series, relops):
"""
Pass dictionary of relational operators to perform on given series object
"""
for op, vals in relops.iteritems():
op_func = ops[op]
for val in vals:
filtered = op_func(series, val)
series = series.reindex(series[filtered])
return series
</code></pre>
<p>The user provides a dictionary with the operations they want to perform:</p>
<pre><code>>>> df = pandas.DataFrame({'col1': [0, 1, 2], 'col2': [10, 11, 12]})
>>> print df
>>> print df
col1 col2
0 0 10
1 1 11
2 2 12
>>> from operator import le, ge
>>> ops ={'>=': ge, '<=': le}
>>> apply_relops(df['col1'], {'>=': [1]})
col1
1 1
2 2
Name: col1
>>> apply_relops(df['col1'], relops = {'>=': [1], '<=': [1]})
col1
1 1
Name: col1
</code></pre>
<p>Again, the 'problem' with my above approach is that I think there is a lot of possibly unnecessary copying of the data for the in-between steps.</p> | <p>Pandas (and numpy) allow for <a href="http://pandas.pydata.org/pandas-docs/dev/indexing.html#boolean-indexing" rel="noreferrer">boolean indexing</a>, which will be much more efficient:</p>
<pre><code>In [11]: df.loc[df['col1'] >= 1, 'col1']
Out[11]:
1 1
2 2
Name: col1
In [12]: df[df['col1'] >= 1]
Out[12]:
col1 col2
1 1 11
2 2 12
In [13]: df[(df['col1'] >= 1) & (df['col1'] <=1 )]
Out[13]:
col1 col2
1 1 11
</code></pre>
<p>If you want to write helper functions for this, consider something along these lines:</p>
<pre><code>In [14]: def b(x, col, op, n):
return op(x[col],n)
In [15]: def f(x, *b):
return x[(np.logical_and(*b))]
In [16]: b1 = b(df, 'col1', ge, 1)
In [17]: b2 = b(df, 'col1', le, 1)
In [18]: f(df, b1, b2)
Out[18]:
col1 col2
1 1 11
</code></pre>
<p>Update: <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="noreferrer">pandas 0.13 has a query method</a> for these kind of use cases, assuming column names are valid identifiers the following works (and can be more efficient for large frames as it uses <a href="https://github.com/pydata/numexpr" rel="noreferrer">numexpr</a> behind the scenes):</p>
<pre><code>In [21]: df.query('col1 <= 1 & 1 <= col1')
Out[21]:
col1 col2
1 1 11
</code></pre> | {
"question_id": 13611065,
"question_date": "2012-11-28T17:34:35.337Z",
"question_score": 222,
"tags": "python|pandas|algorithm|filter",
"answer_id": 13616382,
"answer_date": "2012-11-28T23:38:41.263Z",
"answer_score": 341
} |
Please answer the following Stack Overflow question:
Title: AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?
<p>Using AngularJS if I set a simple input text box value to something like "bob" below. The value does not display if the <code>ng-model</code> attribute is added.</p>
<pre><code> <input type="text"
id="rootFolder"
ng-model="rootFolders"
disabled="disabled"
value="Bob"
size="40"/>
</code></pre>
<p>Anyone know of a simple work around to default this input to something and keep the <code>ng-model</code>? I tried to use a <code>ng-bind</code> with the default value but that seems not to work either.</p> | <p>That's desired behavior, you should define the model in the controller, not in the view.</p>
<pre><code><div ng-controller="Main">
<input type="text" ng-model="rootFolders">
</div>
function Main($scope) {
$scope.rootFolders = 'bob';
}
</code></pre> | {
"question_id": 10610282,
"question_date": "2012-05-15T23:38:39.403Z",
"question_score": 222,
"tags": "javascript|html|angularjs",
"answer_id": 10612424,
"answer_date": "2012-05-16T05:17:25.620Z",
"answer_score": 224
} |
Please answer the following Stack Overflow question:
Title: Retrieve specific commit from a remote Git repository
<p>Is there any way to retrieve only one specific commit from a remote Git repo without cloning it on my PC? The structure of remote repo is absolutely same as that of mine and hence there won't be any conflicts but I have no idea how to do this and I don't want to clone that huge repository.</p>
<p>I am new to git, is there any way?</p> | <p>Starting with Git version 2.5+ (Q2 2015), fetching a single commit (without cloning the full repo) is actually possible.</p>
<p>See <a href="https://github.com/git/git/commit/68ee628932c2196742b77d2961c5e16360734a62" rel="noreferrer">commit 68ee628</a> by <a href="https://github.com/moroten" rel="noreferrer">Fredrik Medley (<code>moroten</code>)</a>, 21 May 2015.<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/a9d34933803198f89ad721ee17f138b046131090" rel="noreferrer">commit a9d3493</a>, 01 Jun 2015)</sup></p>
<p>You now have a new config (on the server side)</p>
<pre><code>uploadpack.allowReachableSHA1InWant
</code></pre>
<blockquote>
<p>Allow <code>upload-pack</code> to accept a fetch request that asks for an object that is reachable from any ref tip. However, note that calculating object reachability is computationally expensive.<br />
Defaults to <code>false</code>.</p>
</blockquote>
<p>If you combine that server-side configuration with a shallow clone (<a href="https://stackoverflow.com/a/19394911/6309"><code>git fetch --depth=1</code></a>), you can ask for a single commit (see <a href="https://github.com/git/git/blob/68ee628932c2196742b77d2961c5e16360734a62/t/t5516-fetch-push.sh#L1123-L1176" rel="noreferrer"><code>t/t5516-fetch-push.sh</code></a>:</p>
<pre><code>git fetch --depth=1 ../testrepo/.git <full-length SHA1>
</code></pre>
<p>You can use the <code>git cat-file</code> command to see that the commit has been fetched:</p>
<pre><code>git cat-file commit <full-length SHA1>
</code></pre>
<blockquote>
<p>"<code>git upload-pack</code>" that serves "<code>git fetch</code>" can be told to serve
commits that are not at the tip of any ref, as long as they are
reachable from a ref, with <code>uploadpack.allowReachableSHA1InWant</code>
configuration variable.</p>
</blockquote>
<p>As noted by <a href="https://stackoverflow.com/users/341994/matt">matt</a> in <a href="https://stackoverflow.com/questions/14872486/retrieve-specific-commit-from-a-remote-git-repository/30701724#comment119562995_30701724">the comments</a>:</p>
<blockquote>
<p>Note that SHA must be the full unabbreviated SHA, otherwise Git will claim it couldn't find the commit</p>
</blockquote>
<hr />
<p>The full documentation is:</p>
<blockquote>
<h2><code>upload-pack</code>: optionally allow fetching reachable sha1</h2>
</blockquote>
<blockquote>
<p>With <code>uploadpack.allowReachableSHA1InWant</code> configuration option set on the server side, "<code>git fetch</code>" can make a request with a "want" line that names an object that has not been advertised (likely to have been obtained out of band or from a submodule pointer).<br />
Only objects reachable from the branch tips, i.e. the union of advertised branches and branches hidden by <code>transfer.hideRefs</code>, will be processed.<br />
Note that there is an associated cost of having to walk back the history to check the reachability.</p>
<p><strong>This feature can be used when obtaining the content of a certain commit,
for which the sha1 is known, without the need of cloning the whole
repository, especially if a shallow fetch is used</strong>.</p>
<p>Useful cases are e.g.</p>
<ul>
<li>repositories containing large files in the history,</li>
<li>fetching only the needed data for a submodule checkout,</li>
<li>when sharing a sha1 without telling which exact branch it belongs to and in Gerrit, if you think in terms of commits instead of change numbers.<br />
(The Gerrit case has already been solved through <code>allowTipSHA1InWant</code> as every Gerrit change has a ref.)</li>
</ul>
</blockquote>
<hr />
<p>Git 2.6 (Q3 2015) will improve that model.<br />
See <a href="https://github.com/git/git/commit/2bc31d1631229d863376d48ef84eb846fea1df02" rel="noreferrer">commit 2bc31d1</a>, <a href="https://github.com/git/git/commit/cc118a65b4590cc2d669679260bad7ca627f2a30" rel="noreferrer">commit cc118a6</a> (28 Jul 2015) 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/824a0be6be8d6c3323003bae65b3df98387e575b" rel="noreferrer">commit 824a0be</a>, 19 Aug 2015)</sup></p>
<blockquote>
<h1><code>refs</code>: support <strong>negative</strong> <code>transfer.hideRefs</code></h1>
</blockquote>
<blockquote>
<p>If you hide a hierarchy of refs using the <code>transfer.hideRefs</code> config, there is no way to later override that config to "unhide" it.<br />
This patch implements a "negative" hide which causes matches to immediately be marked as unhidden, even if another match would hide it.<br />
We take care to apply the matches in reverse-order from how they are fed to us by the config machinery, as that lets our usual "last one wins" config precedence work (and entries in <code>.git/config</code>, for example, will override <code>/etc/gitconfig</code>).</p>
<p>So you can now do:</p>
<pre><code>git config --system transfer.hideRefs refs/secret
git config transfer.hideRefs '!refs/secret/not-so-secret'
</code></pre>
<p>to hide <code>refs/secret</code> in all repos, except for one public bit
in one specific repo.</p>
</blockquote>
<hr />
<p>Git 2.7 (Nov/Dec 2015) will improve again:</p>
<p>See <a href="https://github.com/git/git/commit/948bfa2c0f40a97d670c6a3fc22c05ceb2ec2c3f" rel="noreferrer">commit 948bfa2</a>, <a href="https://github.com/git/git/commit/00b293e519d1aa0c5b57ae9359ec5306d7023b3f" rel="noreferrer">commit 00b293e</a> (05 Nov 2015), <a href="https://github.com/git/git/commit/78a766ab6eaaa91c2638158bd4fda06a93291da0" rel="noreferrer">commit 78a766a</a>, <a href="https://github.com/git/git/commit/92cab492ba988ffd3e3edf040f19ba820306c833" rel="noreferrer">commit 92cab49</a>, <a href="https://github.com/git/git/commit/92cab492ba988ffd3e3edf040f19ba820306c833" rel="noreferrer">commit 92cab49</a>, <a href="https://github.com/git/git/commit/92cab492ba988ffd3e3edf040f19ba820306c833" rel="noreferrer">commit 92cab49</a> (03 Nov 2015), <a href="https://github.com/git/git/commit/00b293e519d1aa0c5b57ae9359ec5306d7023b3f" rel="noreferrer">commit 00b293e</a>, <a href="https://github.com/git/git/commit/00b293e519d1aa0c5b57ae9359ec5306d7023b3f" rel="noreferrer">commit 00b293e</a> (05 Nov 2015), and <a href="https://github.com/git/git/commit/92cab492ba988ffd3e3edf040f19ba820306c833" rel="noreferrer">commit 92cab49</a>, <a href="https://github.com/git/git/commit/92cab492ba988ffd3e3edf040f19ba820306c833" rel="noreferrer">commit 92cab49</a>, <a href="https://github.com/git/git/commit/92cab492ba988ffd3e3edf040f19ba820306c833" rel="noreferrer">commit 92cab49</a>, <a href="https://github.com/git/git/commit/92cab492ba988ffd3e3edf040f19ba820306c833" rel="noreferrer">commit 92cab49</a> (03 Nov 2015) by <a href="https://github.com/lfos" rel="noreferrer">Lukas Fleischer (<code>lfos</code>)</a>.<br />
Helped-by: <a href="https://github.com/sunshineco" rel="noreferrer">Eric Sunshine (<code>sunshineco</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/peff" rel="noreferrer">Jeff King -- <code>peff</code> --</a> in <a href="https://github.com/git/git/commit/dbba85e46b9c7450710a23208ca1868179330e1e" rel="noreferrer">commit dbba85e</a>, 20 Nov 2015)</sup></p>
<blockquote>
<h2><code>config.txt</code>: document the semantics of <code>hideRefs</code> with namespaces</h2>
</blockquote>
<blockquote>
<p>Right now, there is no clear definition of how <code>transfer.hideRefs</code> should
behave when a namespace is set.<br />
Explain that <code>hideRefs</code> prefixes match stripped names in that case. This is how <code>hideRefs</code> patterns are currently
handled in receive-pack.</p>
</blockquote>
<blockquote>
<h2>hideRefs: add support for matching full refs</h2>
</blockquote>
<blockquote>
<p>In addition to matching stripped refs, one can now add <code>hideRefs</code> patterns that the full (unstripped) ref is matched against.<br />
To distinguish between stripped and full matches, those new patterns must be prefixed with a circumflex (<code>^</code>).</p>
</blockquote>
<p>Hence the <a href="https://github.com/git/git/blob/78a766ab6eaaa91c2638158bd4fda06a93291da0/Documentation/config.txt#L2677-L2684" rel="noreferrer">new documentation</a>:</p>
<pre><code>transfer.hideRefs:
</code></pre>
<blockquote>
<p>If a namespace is in use, the namespace prefix is stripped from each reference before it is matched against <code>transfer.hiderefs</code> patterns.<br />
For example, if <code>refs/heads/master</code> is specified in <code>transfer.hideRefs</code> and
the current namespace is <code>foo</code>, then <code>refs/namespaces/foo/refs/heads/master</code>
is omitted from the advertisements but <code>refs/heads/master</code> and
<code>refs/namespaces/bar/refs/heads/master</code> are still advertised as so-called
"have" lines.<br />
In order to match refs before stripping, add a <code>^</code> in front of
the ref name. If you combine <code>!</code> and <code>^</code>, <code>!</code> must be specified first.</p>
</blockquote>
<hr />
<p><a href="https://stackoverflow.com/users/379897/r">R..</a> mentions <a href="https://stackoverflow.com/questions/14872486/retrieve-specific-commit-from-a-remote-git-repository/30701724#comment89086774_30701724">in the comments</a> the config <a href="https://git-scm.com/docs/git-config#git-config-uploadpackallowAnySHA1InWant" rel="noreferrer"><code>uploadpack.allowAnySHA1InWant</code></a>, which allows <code>upload-pack</code> to accept a <code>fetch</code> request that asks for any object at all. (Defaults to <code>false</code>).</p>
<p>See <a href="https://github.com/git/git/commit/f8edeaa05d8623a9f6dad408237496c51101aad8" rel="noreferrer">commit f8edeaa</a> (Nov. 2016, Git v2.11.1) by <a href="https://github.com/novalis" rel="noreferrer">David "novalis" Turner (<code>novalis</code>)</a>:</p>
<blockquote>
<h2><code>upload-pack</code>: optionally allow fetching any sha1</h2>
</blockquote>
<blockquote>
<p>It seems a little silly to do a reachabilty check in the case where we
trust the user to access absolutely everything in the repository.</p>
<p>Also, it's racy in a distributed system -- perhaps one server
advertises a ref, but another has since had a force-push to that ref,
and perhaps the two HTTP requests end up directed to these different
servers.</p>
</blockquote>
<hr />
<p>With Git 2.34 (Q4 2021), "<a href="https://github.com/git/git/blob/1ab13eb973fce31026165391900562be940e0f34/Documentation/git-upload-pack.txt" rel="noreferrer"><code>git upload-pack</code></a>"<sup>(<a href="https://git-scm.com/docs/git-upload-pack" rel="noreferrer">man</a>)</sup> which runs on the other side of <a href="https://github.com/git/git/blob/1ab13eb973fce31026165391900562be940e0f34/Documentation/git-fetch.txt" rel="noreferrer"><code>git fetch</code></a><sup>(<a href="https://git-scm.com/docs/git-fetch" rel="noreferrer">man</a>)</sup> forgot to take the ref namespaces into account when handling want-ref requests.</p>
<p>See <a href="https://github.com/git/git/commit/53a66ec37cfd8fc9f9357f201ae16ae3e8795606" rel="noreferrer">commit 53a66ec</a>, <a href="https://github.com/git/git/commit/39551406539e6ea87f89f619f7f0800e887e9b57" rel="noreferrer">commit 3955140</a>, <a href="https://github.com/git/git/commit/bac01c6469b2489042b867d409894a3152ec98a1" rel="noreferrer">commit bac01c6</a> (13 Aug 2021) by <a href="https://github.com/kim" rel="noreferrer">Kim Altintop (<code>kim</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/1ab13eb973fce31026165391900562be940e0f34" rel="noreferrer">commit 1ab13eb</a>, 10 Sep 2021)</sup></p>
<blockquote>
<h2><a href="https://github.com/git/git/commit/53a66ec37cfd8fc9f9357f201ae16ae3e8795606" rel="noreferrer"><code>docs</code></a>: clarify the interaction of transfer.hideRefs and namespaces</h2>
<p><sup>Signed-off-by: Kim Altintop</sup><br />
<sup>Reviewed-by: Jonathan Tan</sup></p>
</blockquote>
<blockquote>
<p>Expand the section about namespaces in the documentation of <code>transfer.hideRefs</code> to point out the subtle differences between <code>upload-pack</code> and <code>receive-pack</code>.</p>
<p><a href="https://github.com/git/git/commit/39551406539e6ea87f89f619f7f0800e887e9b57" rel="noreferrer">3955140</a> ("<a href="https://github.com/git/git/blob/39551406539e6ea87f89f619f7f0800e887e9b57/upload-pack.c" rel="noreferrer"><code>upload-pack.c</code></a>: treat want-ref relative to namespace", 2021-07-30, Git v2.34.0 -- <a href="https://github.com/git/git/commit/1ab13eb973fce31026165391900562be940e0f34" rel="noreferrer">merge</a> listed in <a href="https://github.com/git/git/commit/8b7c11b8668b4e774f81a9f0b4c30144b818f1d1" rel="noreferrer">batch #5</a>) taught <code>upload-pack</code> to reject <code>want-ref</code>s for hidden refs, which is now mentioned.<br />
It is clarified that at no point the name of a hidden ref is revealed, but the object id it points to may.</p>
</blockquote>
<p><code>git config</code> now includes in its <a href="https://github.com/git/git/blob/53a66ec37cfd8fc9f9357f201ae16ae3e8795606/Documentation/config/transfer.txt#L55-L58" rel="noreferrer">man page</a>:</p>
<blockquote>
<p>reference before it is matched against <code>transfer.hiderefs</code> patterns. In
order to match refs before stripping, add a <code>^</code> in front of the ref name. If
you combine <code>!</code> and <code>^</code>, <code>!</code> must be specified first.</p>
</blockquote>
<p><code>git config</code> now includes in its <a href="https://github.com/git/git/blob/53a66ec37cfd8fc9f9357f201ae16ae3e8795606/Documentation/config/transfer.txt#L61-L65" rel="noreferrer">man page</a>:</p>
<blockquote>
<p>is omitted from the advertisements. If <code>uploadpack.allowRefInWant</code> is set,
<code>upload-pack</code> will treat <code>want-ref refs/heads/master</code> in a protocol v2
<code>fetch</code> command as if <code>refs/namespaces/foo/refs/heads/master</code> did not exist.
<code>receive-pack</code>, on the other hand, will still advertise the object id the
ref is pointing to without mentioning its name (a so-called "<code>.hav</code>e" line).</p>
</blockquote> | {
"question_id": 14872486,
"question_date": "2013-02-14T10:18:07.943Z",
"question_score": 222,
"tags": "git|git-fetch",
"answer_id": 30701724,
"answer_date": "2015-06-08T05:22:17.167Z",
"answer_score": 130
} |
Please answer the following Stack Overflow question:
Title: Truncate a string straight JavaScript
<p>I'd like to truncate a dynamically loaded string using straight JavaScript. It's a url, so there are no spaces, and I obviously don't care about word boundaries, just characters. </p>
<p>Here's what I got:</p>
<pre><code>var pathname = document.referrer; //wont work if accessing file:// paths
document.getElementById("foo").innerHTML = "<a href='" + pathname +"'>" + pathname +"</a>"
</code></pre> | <p>Use the <a href="http://www.w3schools.com/jsref/jsref_substring.asp" rel="noreferrer">substring</a> method:</p>
<pre><code>var length = 3;
var myString = "ABCDEFG";
var myTruncatedString = myString.substring(0,length);
// The value of myTruncatedString is "ABC"
</code></pre>
<p>So in your case:</p>
<pre><code>var length = 3; // set to the number of characters you want to keep
var pathname = document.referrer;
var trimmedPathname = pathname.substring(0, Math.min(length,pathname.length));
document.getElementById("foo").innerHTML =
"<a href='" + pathname +"'>" + trimmedPathname + "</a>"
</code></pre> | {
"question_id": 1301512,
"question_date": "2009-08-19T17:42:44.197Z",
"question_score": 222,
"tags": "javascript|truncate",
"answer_id": 1301525,
"answer_date": "2009-08-19T17:45:54.083Z",
"answer_score": 411
} |
Please answer the following Stack Overflow question:
Title: How to pass arguments to Shell Script through docker run
<p>I am new to the docker world. I have to invoke a shell script that takes command line arguments through a docker container.
Ex: My shell script looks like:</p>
<pre><code>#!bin/bash
echo $1
</code></pre>
<p>Dockerfile looks like this:</p>
<pre><code>FROM ubuntu:14.04
COPY ./file.sh /
CMD /bin/bash file.sh
</code></pre>
<p>I am not sure how to pass the arguments while running the container</p> | <p>Use the same <code>file.sh</code></p>
<pre><code>#!/bin/bash
echo $1
</code></pre>
<p>Build the image using the existing Dockerfile:</p>
<pre><code>docker build -t test .
</code></pre>
<p>Run the image with arguments <code>abc</code> or <code>xyz</code> or something else.</p>
<pre><code>docker run -ti --rm test /file.sh abc
docker run -ti --rm test /file.sh xyz
</code></pre> | {
"question_id": 32727594,
"question_date": "2015-09-22T21:53:55.290Z",
"question_score": 222,
"tags": "bash|shell|docker|command-line-arguments",
"answer_id": 32728266,
"answer_date": "2015-09-22T22:48:49.250Z",
"answer_score": 104
} |
Please answer the following Stack Overflow question:
Title: Laravel - create model, controller and migration in single artisan command
<p>I can create a model and resource controller (binded to model) with the following command</p>
<pre><code>php artisan make:controller TodoController --resource --model=Todo
</code></pre>
<p>I want to also create a migration with the above command, is it possible?</p> | <p>You can do it if you start from the model</p>
<pre><code>php artisan make:model Todo -mcr
</code></pre>
<p>if you run <code>php artisan make:model --help</code> you can see all the available options</p>
<blockquote>
<p>-m, --migration Create a new migration file for the model.<br>
-c, --controller Create a new controller for the model.<br>
-r, --resource Indicates if the generated controller should be a resource controller</p>
</blockquote>
<p><strong>Update</strong></p>
<p>As mentioned in the comments by @arun in newer versions of laravel > 5.6 it is possible to run following command:</p>
<pre><code>php artisan make:model Todo -a
</code></pre>
<blockquote>
<p>-a, --all Generate a migration, factory, and resource
controller for the model</p>
</blockquote> | {
"question_id": 43187735,
"question_date": "2017-04-03T14:48:11.503Z",
"question_score": 222,
"tags": "laravel|laravel-5|laravel-artisan",
"answer_id": 43187825,
"answer_date": "2017-04-03T14:52:29.427Z",
"answer_score": 566
} |
Please answer the following Stack Overflow question:
Title: How to append a char to a std::string?
<p>The following fails with the error <code>prog.cpp:5:13: error: invalid conversion from ‘char’ to ‘const char*’</code></p>
<pre><code>int main()
{
char d = 'd';
std::string y("Hello worl");
y.append(d); // Line 5 - this fails
std::cout << y;
return 0;
}
</code></pre>
<p>I also tried, the following, which compiles but behaves randomly at runtime:</p>
<pre><code>int main()
{
char d[1] = { 'd' };
std::string y("Hello worl");
y.append(d);
std::cout << y;
return 0;
}
</code></pre>
<p>Sorry for this dumb question, but I've searched around google, what I could see are just "char array to char ptr", "char ptr to char array", etc.</p> | <pre><code>y += d;
</code></pre>
<p>I would use <code>+=</code> operator instead of named functions.</p> | {
"question_id": 1472048,
"question_date": "2009-09-24T14:26:09.533Z",
"question_score": 222,
"tags": "c++|string",
"answer_id": 1472075,
"answer_date": "2009-09-24T14:29:28.550Z",
"answer_score": 279
} |
Please answer the following Stack Overflow question:
Title: Controlling Maven final name of jar artifact
<p>I'm trying to define a property in our super pom which will be used by all child projects as the destination of the generated artifact.</p>
<p>For this I was thinking about using <code>project/build/finalName</code> yet this does not seem work, even for simple poms:</p>
<p><strong><em>Command</em></strong></p>
<pre><code> mvn archetype:create \
-DarchetypeGroupId=org.apache.maven.archetypes \
-DgroupId=com.mycompany.app \
-DartifactId=my-app
</code></pre>
<p><strong><em>POM</em></strong></p>
<pre class="lang-xml prettyprint-override"><code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>my-app</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<finalName>${project.name}-testing</finalName>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
</code></pre>
<p>And when I executed : </p>
<pre class="lang-xml prettyprint-override"><code>$ mvn install
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building my-app
[INFO] task-segment: [install]
[INFO] ------------------------------------------------------------------------
[INFO] [resources:resources {execution: default-resources}]
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /tmp/mvn_test/my-app/src/main/resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [resources:testResources {execution: default-testResources}]
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] skip non existing resourceDirectory /tmp/mvn_test/my-app/src/test/resources
[INFO] [compiler:testCompile {execution: default-testCompile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [surefire:test {execution: default-test}]
[INFO] Surefire report directory: /tmp/mvn_test/my-app/target/surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.mycompany.app.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.024 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] [jar:jar {execution: default-jar}]
[INFO] [install:install {execution: default-install}]
[INFO] Installing /tmp/mvn_test/my-app/target/my-app-testing.jar to /home/maxim/.m2/repository/com/mycompany/app/my-app/1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2 seconds
[INFO] Finished at: Sun Nov 21 18:37:02 IST 2010
[INFO] Final Memory: 17M/162M
[INFO] ------------------------------------------------------------------------
</code></pre>
<p>I would expect the string "testing" would appear somewhere in the generated artifact name.</p>
<p>Am I misunderstanding the purpose of "finalName" ?</p> | <p><strong>For Maven >= 3</strong></p>
<pre class="lang-xml prettyprint-override"><code> <packaging>jar</packaging>
<build>
<finalName>WhatEverYouLikey</finalName>
</build>
</code></pre>
<p>See <a href="https://issues.apache.org/jira/browse/MJAR-233" rel="noreferrer">bug report/documentation</a>.</p>
<p>(Credits to <a href="https://stackoverflow.com/users/5209935/matthew">Matthew's</a> and his <a href="https://stackoverflow.com/questions/4238944/controlling-maven-final-name-of-jar-artifact#comment65056498_14490656">comment</a>)</p>
<p><em><strong>For older Maven versions</strong></em></p>
<p>You set the <code>finalName</code> property in the plugin configuration section:</p>
<pre class="lang-xml prettyprint-override"><code><plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<finalName>myJar</finalName>
</configuration>
</plugin>
</code></pre>
<p>As indicated in the <a href="http://maven.apache.org/plugins/maven-jar-plugin/jar-mojo.html#finalName" rel="noreferrer">official documentation</a>.</p> | {
"question_id": 4238944,
"question_date": "2010-11-21T16:40:00.360Z",
"question_score": 222,
"tags": "java|maven-2|jar|build-automation",
"answer_id": 14490656,
"answer_date": "2013-01-23T22:34:13.787Z",
"answer_score": 389
} |
Please answer the following Stack Overflow question:
Title: How can I find the length of a number?
<p>I'm looking to get the length of a number in JavaScript or jQuery?</p>
<p>I've tried <code>value.length</code> without any success, do I need to convert this to a string first?</p> | <pre><code>var x = 1234567;
x.toString().length;
</code></pre>
<p>This process will also work for<code>Float Number</code> and for <code>Exponential number</code> also.</p> | {
"question_id": 10952615,
"question_date": "2012-06-08T16:24:57.687Z",
"question_score": 222,
"tags": "javascript|jquery",
"answer_id": 10952633,
"answer_date": "2012-06-08T16:26:21.813Z",
"answer_score": 410
} |
Please answer the following Stack Overflow question:
Title: How to add a new row to an empty numpy array
<p>Using standard Python arrays, I can do the following:</p>
<pre><code>arr = []
arr.append([1,2,3])
arr.append([4,5,6])
# arr is now [[1,2,3],[4,5,6]]
</code></pre>
<p>However, I cannot do the same thing in numpy. For example:</p>
<pre><code>arr = np.array([])
arr = np.append(arr, np.array([1,2,3]))
arr = np.append(arr, np.array([4,5,6]))
# arr is now [1,2,3,4,5,6]
</code></pre>
<p>I also looked into <code>vstack</code>, but when I use <code>vstack</code> on an empty array, I get:</p>
<pre><code>ValueError: all the input array dimensions except for the concatenation axis must match exactly
</code></pre>
<p>So how do I do append a new row to an empty array in numpy?</p> | <p>The way to "start" the array that you want is:</p>
<pre><code>arr = np.empty((0,3), int)
</code></pre>
<p>Which is an empty array but it has the proper dimensionality.</p>
<pre><code>>>> arr
array([], shape=(0, 3), dtype=int64)
</code></pre>
<p>Then be sure to append along axis 0:</p>
<pre><code>arr = np.append(arr, np.array([[1,2,3]]), axis=0)
arr = np.append(arr, np.array([[4,5,6]]), axis=0)
</code></pre>
<p>But, @jonrsharpe is right. In fact, if you're going to be appending in a loop, it would be much faster to append to a list as in your first example, then convert to a numpy array at the end, since you're really not using numpy as intended during the loop:</p>
<pre><code>In [210]: %%timeit
.....: l = []
.....: for i in xrange(1000):
.....: l.append([3*i+1,3*i+2,3*i+3])
.....: l = np.asarray(l)
.....:
1000 loops, best of 3: 1.18 ms per loop
In [211]: %%timeit
.....: a = np.empty((0,3), int)
.....: for i in xrange(1000):
.....: a = np.append(a, 3*i+np.array([[1,2,3]]), 0)
.....:
100 loops, best of 3: 18.5 ms per loop
In [214]: np.allclose(a, l)
Out[214]: True
</code></pre>
<p>The numpythonic way to do it depends on your application, but it would be more like:</p>
<pre><code>In [220]: timeit n = np.arange(1,3001).reshape(1000,3)
100000 loops, best of 3: 5.93 µs per loop
In [221]: np.allclose(a, n)
Out[221]: True
</code></pre> | {
"question_id": 22392497,
"question_date": "2014-03-13T22:39:26.543Z",
"question_score": 222,
"tags": "python|numpy|scipy",
"answer_id": 22394181,
"answer_date": "2014-03-14T01:03:18.007Z",
"answer_score": 321
} |
Please answer the following Stack Overflow question:
Title: How to select records from last 24 hours using SQL?
<p>I am looking for a <code>where</code> clause that can be used to retrieve records for the last 24 hours?</p> | <pre><code>SELECT *
FROM table_name
WHERE table_name.the_date > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
</code></pre> | {
"question_id": 1888544,
"question_date": "2009-12-11T14:49:02.647Z",
"question_score": 222,
"tags": "sql|datetime",
"answer_id": 1888593,
"answer_date": "2009-12-11T14:54:40.793Z",
"answer_score": 108
} |
Please answer the following Stack Overflow question:
Title: How to change the opacity (alpha, transparency) of an element in a canvas element?
<p>Using the HTML5 <code><canvas></code> element, I would like to load an image file (PNG, JPEG, etc.), draw it to the canvas completely transparently, and then fade it in. I have figured out how to load the image and draw it to the canvas, but I don't know how to change its opacity.</p>
<p>Here's the code I have so far:</p>
<pre><code>var canvas = document.getElementById('myCanvas');
if (canvas.getContext)
{
var c = canvas.getContext('2d');
c.globalAlpha = 0;
var img = new Image();
img.onload = function() {
c.drawImage(img, 0, 0);
}
img.src = 'image.jpg';
}
</code></pre>
<p>Will somebody please point me in the right direction like a property to set or a function to call that will change the opacity?</p> | <p>I am also looking for an answer to this question, (to clarify, I want to be able to draw an image with user defined opacity such as how you can draw shapes with opacity) if you draw with primitive shapes you can set fill and stroke color with alpha to define the transparency. As far as I have concluded right now, this does not seem to affect image drawing. </p>
<pre><code>//works with shapes but not with images
ctx.fillStyle = "rgba(255, 255, 255, 0.5)";
</code></pre>
<p>I have concluded that setting the <code>globalCompositeOperation</code> works with images. </p>
<pre><code>//works with images
ctx.globalCompositeOperation = "lighter";
</code></pre>
<p>I wonder if there is some kind third way of setting color so that we can tint images and make them transparent easily.</p>
<p><strong>EDIT:</strong></p>
<p>After further digging I have concluded that you can set the transparency of an image by setting the <code>globalAlpha</code> parameter BEFORE you draw the image:</p>
<pre><code>//works with images
ctx.globalAlpha = 0.5
</code></pre>
<p>If you want to achieve a fading effect over time you need some kind of loop that changes the alpha value, this is fairly easy, one way to achieve it is the <code>setTimeout</code> function, look that up to create a loop from which you alter the alpha over time.</p> | {
"question_id": 2359537,
"question_date": "2010-03-01T22:22:24.423Z",
"question_score": 222,
"tags": "html|canvas|transparency|opacity|alpha",
"answer_id": 2675425,
"answer_date": "2010-04-20T13:25:27.103Z",
"answer_score": 340
} |
Please answer the following Stack Overflow question:
Title: :after and :before pseudo-element selectors in Sass
<p>How can I use the :before and :after pseudo-element selectors following the syntax of Sass or, alternatively, SCSS? Like this:</p>
<pre><code>p
margin: 2em auto
> a
color: red
:before
content: ""
:after
content: "* * *"
</code></pre>
<p>Of course, the above fails.</p> | <p><a href="http://sass-lang.com/documentation/file.SASS_REFERENCE.html#parent-selector" rel="noreferrer">Use ampersand to specify the parent selector</a>.</p>
<p>SCSS syntax:</p>
<pre><code>p {
margin: 2em auto;
> a {
color: red;
}
&:before {
content: "";
}
&:after {
content: "* * *";
}
}
</code></pre> | {
"question_id": 10750563,
"question_date": "2012-05-25T07:49:31.180Z",
"question_score": 222,
"tags": "css|css-selectors|sass|pseudo-element",
"answer_id": 10750761,
"answer_date": "2012-05-25T08:06:36.523Z",
"answer_score": 499
} |
Please answer the following Stack Overflow question:
Title: Axios get in url works but with second parameter as object it doesn't
<p>I'm trying to send GET request as second parameter but it doesn't work while it does as url.</p>
<p>This works, $_GET['naam'] returns test:</p>
<pre><code>export function saveScore(naam, score) {
return function (dispatch) {
axios.get('http://****.nl/****/gebruikerOpslaan.php?naam=test')
.then((response) => {
dispatch({type: "SAVE_SCORE_SUCCESS", payload: response.data})
})
.catch((err) => {
dispatch({type: "SAVE_SCORE_FAILURE", payload: err})
})
}
};
</code></pre>
<p>But when I try this, there is nothing in <code>$_GET</code> at all:</p>
<pre><code>export function saveScore(naam, score) {
return function (dispatch) {
axios.get('http://****.nl/****/gebruikerOpslaan.php',
{
password: 'pass',
naam: naam,
score: score
})
.then((response) => {
dispatch({type: "SAVE_SCORE_SUCCESS", payload: response.data})
})
.catch((err) => {
dispatch({type: "SAVE_SCORE_FAILURE", payload: err})
})
}
};
</code></pre>
<p>Why can't I do that? In the docs it clearly says it's possible. With <code>$_POST</code> it doesn't work either.</p> | <p><a href="https://github.com/mzabriskie/axios#axiosgeturl-config" rel="noreferrer"><code>axios.get</code></a> accepts a request config as the second parameter (not query string params). </p>
<p>You can use the <code>params</code> config option to set query string params as follows: </p>
<pre><code>axios.get('/api', {
params: {
foo: 'bar'
}
});
</code></pre> | {
"question_id": 40947650,
"question_date": "2016-12-03T12:17:49.123Z",
"question_score": 222,
"tags": "reactjs|react-native|redux|axios",
"answer_id": 40953463,
"answer_date": "2016-12-03T23:02:00.773Z",
"answer_score": 485
} |
Please answer the following Stack Overflow question:
Title: Getting the minimum of two values in SQL
<p>I have two variables, one is called <code>PaidThisMonth</code>, and the other is called <code>OwedPast</code>. They are both results of some subqueries in SQL. How can I select the smaller of the two and return it as a value titled <code>PaidForPast</code>?</p>
<p>The <code>MIN</code> function works on columns, not variables.</p> | <p>Use Case:</p>
<pre><code> Select Case When @PaidThisMonth < @OwedPast
Then @PaidThisMonth Else @OwedPast End PaidForPast
</code></pre>
<p>As Inline table valued UDF</p>
<pre><code>CREATE FUNCTION Minimum
(@Param1 Integer, @Param2 Integer)
Returns Table As
Return(Select Case When @Param1 < @Param2
Then @Param1 Else @Param2 End MinValue)
</code></pre>
<p>Usage:</p>
<pre><code>Select MinValue as PaidforPast
From dbo.Minimum(@PaidThisMonth, @OwedPast)
</code></pre>
<p>ADDENDUM:
This is probably best for when addressing only two possible values, if there are more than two, consider <a href="https://stackoverflow.com/a/32209528">Craig's answer</a> using Values clause.</p> | {
"question_id": 1947753,
"question_date": "2009-12-22T17:07:08.570Z",
"question_score": 222,
"tags": "tsql|sql-server",
"answer_id": 1947794,
"answer_date": "2009-12-22T17:10:38.730Z",
"answer_score": 146
} |
Please answer the following Stack Overflow question:
Title: jQuery returning "parsererror" for ajax request
<p>Been getting a "parsererror" from jquery for an Ajax request, I have tried changing the POST to a GET, returning the data in a few different ways (creating classes, etc.) but I cant seem to figure out what the problem is.</p>
<p>My project is in MVC3 and I'm using jQuery 1.5
I have a Dropdown and on the onchange event I fire off a call to get some data based on what was selected.</p>
<p>Dropdown: (this loads the "Views" from the list in the Viewbag and firing the event works fine)</p>
<pre><code>@{
var viewHtmls = new Dictionary<string, object>();
viewHtmls.Add("data-bind", "value: ViewID");
viewHtmls.Add("onchange", "javascript:PageModel.LoadViewContentNames()");
}
@Html.DropDownList("view", (List<SelectListItem>)ViewBag.Views, viewHtmls)
</code></pre>
<p>Javascript:</p>
<pre><code>this.LoadViewContentNames = function () {
$.ajax({
url: '/Admin/Ajax/GetViewContentNames',
type: 'POST',
dataType: 'json',
data: { viewID: $("#view").val() },
success: function (data) {
alert(data);
},
error: function (data) {
debugger;
alert("Error");
}
});
};
</code></pre>
<p>The above code successfully calls the MVC method and returns:</p>
<pre><code>[{"ViewContentID":1,"Name":"TopContent","Note":"Content on the top"},
{"ViewContentID":2,"Name":"BottomContent","Note":"Content on the bottom"}]
</code></pre>
<p>But jquery fires the error event for the $.ajax() method saying "parsererror".</p> | <p>I recently encountered this problem and stumbled upon this question.</p>
<p>I resolved it with a much easier way.</p>
<p><strong>Method One</strong></p>
<p>You can either remove the <code>dataType: 'json'</code> property from the object literal...</p>
<p><strong>Method Two</strong></p>
<p>Or you can do what @Sagiv was saying by returning your data as <code>Json</code>.</p>
<hr>
<p>The reason why this <code>parsererror</code> message occurs is that when you simply return a string or another value, it is not really <code>Json</code>, so the parser fails when parsing it.</p>
<p>So if you remove the <code>dataType: json</code> property, it will not try to parse it as <code>Json</code>. </p>
<p>With the other method if you make sure to return your data as <code>Json</code>, the parser will know how to handle it properly.</p> | {
"question_id": 5061310,
"question_date": "2011-02-21T00:54:28.060Z",
"question_score": 222,
"tags": "javascript|c#|jquery|asp.net|json",
"answer_id": 11507572,
"answer_date": "2012-07-16T15:33:53.107Z",
"answer_score": 370
} |
Please answer the following Stack Overflow question:
Title: Switch statement for string matching in JavaScript
<p>How do I write a switch for the following conditional?</p>
<p>If the url <strong>contains</strong> "foo", then <code>settings.base_url</code> is "bar".</p>
<p>The following is achieving the effect required but I've a feeling this would be more manageable in a switch:</p>
<pre><code>var doc_location = document.location.href;
var url_strip = new RegExp("http:\/\/.*\/");
var base_url = url_strip.exec(doc_location)
var base_url_string = base_url[0];
//BASE URL CASES
// LOCAL
if (base_url_string.indexOf('xxx.local') > -1) {
settings = {
"base_url" : "http://xxx.local/"
};
}
// DEV
if (base_url_string.indexOf('xxx.dev.yyy.com') > -1) {
settings = {
"base_url" : "http://xxx.dev.yyy.com/xxx/"
};
}
</code></pre> | <p><s>You can't do it in a <code>switch</code> unless you're doing <strong>full</strong> string matching; that's doing <strong>substring</strong> matching.</s> <em>(This isn't</em> quite <em>true, as Sean points out in the comments. See note at the end.)</em></p>
<p>If you're happy that your regex at the top is stripping away everything that you don't want to compare in your match, you don't need a substring match, and could do:</p>
<pre><code>switch (base_url_string) {
case "xxx.local":
// Blah
break;
case "xxx.dev.yyy.com":
// Blah
break;
}
</code></pre>
<p>...but again, that only works if that's the <em>complete</em> string you're matching. It would fail if <code>base_url_string</code> were, say, "yyy.xxx.local" whereas your current code would match that in the "xxx.local" branch.</p>
<hr>
<p><strong>Update</strong>: Okay, so technically you <em>can</em> use a <code>switch</code> for substring matching, but I wouldn't recommend it in most situations. Here's how (<a href="http://jsbin.com/ehabar" rel="noreferrer">live example</a>):</p>
<pre><code>function test(str) {
switch (true) {
case /xyz/.test(str):
display("• Matched 'xyz' test");
break;
case /test/.test(str):
display("• Matched 'test' test");
break;
case /ing/.test(str):
display("• Matched 'ing' test");
break;
default:
display("• Didn't match any test");
break;
}
}
</code></pre>
<p>That works because of the way JavaScript <a href="http://es5.github.com/#x12.11" rel="noreferrer"><code>switch</code> statements work</a>, in particular two key aspects: First, that the cases are considered in <em>source text</em> order, and second that the selector expressions (the bits after the keyword <code>case</code>) are <em>expressions</em> that are evaluated as that case is evaluated (not constants as in some other languages). So since our test expression is <code>true</code>, the first <code>case</code> expression that results in <code>true</code> will be the one that gets used.</p> | {
"question_id": 2896626,
"question_date": "2010-05-24T11:33:19.377Z",
"question_score": 222,
"tags": "javascript|regex|switch-statement",
"answer_id": 2896642,
"answer_date": "2010-05-24T11:35:23.037Z",
"answer_score": 387
} |
Please answer the following Stack Overflow question:
Title: How to get first element in a list of tuples?
<p>I have a list like below where the first element is the id and the other is a string:</p>
<pre><code>[(1, u'abc'), (2, u'def')]
</code></pre>
<p>I want to create a list of ids only from this list of tuples as below:</p>
<pre><code>[1,2]
</code></pre>
<p>I'll use this list in <code>__in</code> so it needs to be a list of integer values.</p> | <pre><code>>>> a = [(1, u'abc'), (2, u'def')]
>>> [i[0] for i in a]
[1, 2]
</code></pre> | {
"question_id": 12142133,
"question_date": "2012-08-27T12:38:37.183Z",
"question_score": 222,
"tags": "python|list",
"answer_id": 12142903,
"answer_date": "2012-08-27T13:25:51.693Z",
"answer_score": 327
} |
Please answer the following Stack Overflow question:
Title: How to export all data from table to an insertable sql format?
<p>I have a Table (call it <code>A_table</code>) in a database (call it <code>A_db</code>) in Microsoft SQL Server Management Studio, and there are 10 rows.</p>
<p>I have another database (call it <code>B_db</code>), and it has a Table (call it <code>B_table</code>), which has the same column settings as <code>A_table</code> has. But the <code>B_table</code> is empty.</p>
<p>What I want:</p>
<ul>
<li><strong>Copy</strong> every rows from <code>A_table</code> to <code>B_table</code>.</li>
</ul>
<p>Is there any option in <strong>Microsoft SQL Server Management Studio 2012</strong>, to create an insert SQL from a table? Or is there any other option to do that?</p> | <p>Quick and Easy way:</p>
<ol>
<li>Right click database</li>
<li>Point to <code>tasks</code> <code>In SSMS 2017 you need to ignore step 2 - the generate scripts options is at the top level of the context menu</code> Thanks to <a href="https://stackoverflow.com/users/5740181/daniel-elkington">Daniel</a> for the comment to update.</li>
<li>Select <code>generate scripts</code></li>
<li>Click next</li>
<li>Choose tables</li>
<li>Click next</li>
<li>Click advanced</li>
<li>Scroll to <code>Types of data to script</code> - Called <code>types of data to script</code> in SMSS 2014 Thanks to <a href="https://stackoverflow.com/users/1861513/ellesedil">Ellesedil</a> for commenting</li>
<li>Select <code>data only</code></li>
<li>Click on 'Ok' to close the advanced script options window</li>
<li>Click next and generate your script</li>
</ol>
<p>I usually in cases like this generate to a new query editor window and then just do any modifications where needed.</p> | {
"question_id": 20542819,
"question_date": "2013-12-12T11:53:46.593Z",
"question_score": 222,
"tags": "sql|sql-server|copy|export|ssms",
"answer_id": 20543132,
"answer_date": "2013-12-12T12:08:34.380Z",
"answer_score": 523
} |
Please answer the following Stack Overflow question:
Title: rebase in progress. Cannot commit. How to proceed or stop (abort)?
<p>When I run: </p>
<pre><code>git status
</code></pre>
<p>I see this:</p>
<pre><code>rebase in progress; onto 9c168a5
You are currently rebasing branch 'master' on '9c168a5'.
(all conflicts fixed: run "git rebase --continue")
nothing to commit, working directory clean
</code></pre>
<p>When I do: </p>
<pre><code>ls `git rev-parse --git-dir` | grep rebase || echo no rebase
</code></pre>
<p>I see: rebase-apply</p>
<p>I can't commit to origin. </p>
<pre><code>git branch
</code></pre>
<p>Shows:</p>
<pre><code>* (no branch, rebasing master)
develop
master
</code></pre>
<p>I'm stuck. I don't know what to do? Does it really take this long to rebase? <code>git rebase --continue</code> doesn't do anything. I don't have anything in git status.. I'm just waiting for the rebase. What can I do?</p>
<p>UDATE:
This is the output of: git rebase --continue</p>
<pre><code>Applying: no message
No changes - did you forget to use 'git add'?
If there is nothing left to stage, chances are that something else
already introduced the same changes; you might want to skip this patch.
When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".
</code></pre>
<p>git add . has nothing. </p> | <p>Rebase doesn't happen in the background. "rebase in progress" means that you started a rebase, and the rebase got interrupted because of conflict. You have to resume the rebase
(<code>git rebase --continue</code>) or abort it (<code>git rebase --abort</code>).</p>
<p>As the error message from <code>git rebase --continue</code> suggests, you asked git to apply a patch that results in an empty patch. Most likely, this means the patch was already applied and you want to drop it using <code>git rebase --skip</code>.</p> | {
"question_id": 29902967,
"question_date": "2015-04-27T18:08:27.357Z",
"question_score": 222,
"tags": "git|git-rebase",
"answer_id": 29903238,
"answer_date": "2015-04-27T18:24:03.837Z",
"answer_score": 386
} |
Please answer the following Stack Overflow question:
Title: Fragment onResume() & onPause() is not called on backstack
<p>I have multiple fragment inside an activity. On a button click I am starting a new fragment, adding it to backstack. I naturally expected the <code>onPause()</code> method of current Fragment and <code>onResume()</code> of new Fragment to be called. Well it is not happening.</p>
<h2>LoginFragment.java</h2>
<pre><code>public class LoginFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.login_fragment, container, false);
final FragmentManager mFragmentmanager = getFragmentManager();
Button btnHome = (Button)view.findViewById(R.id.home_btn);
btnHome.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
HomeFragment fragment = new HomeFragment();
FragmentTransaction ft2 = mFragmentmanager.beginTransaction();
ft2.setCustomAnimations(R.anim.slide_right, R.anim.slide_out_left
, R.anim.slide_left, R.anim.slide_out_right);
ft2.replace(R.id.middle_fragment, fragment);
ft2.addToBackStack("");
ft2.commit();
}
});
}
@Override
public void onResume() {
Log.e("DEBUG", "onResume of LoginFragment");
super.onResume();
}
@Override
public void onPause() {
Log.e("DEBUG", "OnPause of loginFragment");
super.onPause();
}
}
</code></pre>
<h2>HomeFragment.java</h2>
<pre><code>public class HomeFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.login_fragment, container, false);
}
@Override
public void onResume() {
Log.e("DEBUG", "onResume of HomeFragment");
super.onResume();
}
@Override
public void onPause() {
Log.e("DEBUG", "OnPause of HomeFragment");
super.onPause();
}
}
</code></pre>
<p>What I expected, was,</p>
<ol>
<li>When button is clicked, <strong>LoginFragment</strong> gets replaced with
<strong>HomeFragment</strong>, <code>onPause()</code> of <strong>LoginFragment</strong>, and <code>onResume()</code> of
<strong>HomeFragment</strong> gets called</li>
<li>When back is pressed, <strong>HomeFragment</strong> is poped out and <strong>LoginFragment</strong> is
seen, and <code>onPause()</code> of <strong>HomeFragment</strong> and <code>onResume()</code> of <strong>LoginFragment</strong>
gets called.</li>
</ol>
<p>What I am getting is,</p>
<ol>
<li>When button is clicked, <strong>HomeFragment</strong> is correctly replacing
<strong>LoginFragment</strong>, onResume() of <strong>HomeFragment</strong> is called, but onPause()
of <strong>LoginFragment</strong> is never called.</li>
<li>When back pressed, <strong>HomeFragment</strong> is correctly popping to reveal
<strong>LoginFragment</strong>, onPause() of <strong>HomeFragment</strong> gets called, but onResume()
of <strong>LoginFragment</strong> never gets called.</li>
</ol>
<p>Is this the normal behaviour? Why is <code>onResume()</code> of <strong>LoginFragment</strong> not getting called when I press the back button.</p> | <p>The fragments <code>onResume()</code> or <code>onPause()</code> will be called only when the Activities <code>onResume()</code> or <code>onPause()</code> is called.
They are tightly coupled to the <code>Activity</code>.</p>
<p>Read the <a href="http://developer.android.com/guide/components/fragments.html#Lifecycle" rel="noreferrer">Handling the Fragment Lifecycle section of this article</a>.</p> | {
"question_id": 11326155,
"question_date": "2012-07-04T09:23:31.520Z",
"question_score": 222,
"tags": "android|android-fragments|onresume|back-stack",
"answer_id": 16252923,
"answer_date": "2013-04-27T13:55:01.720Z",
"answer_score": 201
} |
Please answer the following Stack Overflow question:
Title: matplotlib error - no module named tkinter
<p>I tried to use the matplotlib package via Pycharm IDE on windows 10.
when I run this code:</p>
<pre><code>from matplotlib import pyplot
</code></pre>
<p>I get the following error:</p>
<pre><code>ImportError: No module named 'tkinter'
</code></pre>
<p>I know that in python 2.x it was called Tkinter, but that is not the problem - I just installed a brand new python 3.5.1.</p>
<p>EDIT: in addition, I also tried to import 'tkinter' and 'Tkinter' - neither of these worked (both returned the error message I mentioned).</p> | <h3>For Linux</h3>
<p>Debian based distros:</p>
<pre><code>sudo apt-get install python3-tk
</code></pre>
<p>RPM based distros:</p>
<pre><code>sudo yum install python3-tkinter
</code></pre>
<h3>For windows:</h3>
<p>For Windows, I think the problem is you didn't install complete Python package. Since Tkinter should be shipped with Python out of box. See: <a href="http://www.tkdocs.com/tutorial/install.html" rel="noreferrer">http://www.tkdocs.com/tutorial/install.html</a> . Good python distributions for Windows can be found by the companies Anaconda or ActiveState.</p>
<h3>Test the python module</h3>
<pre><code>python -c "import tkinter"
</code></pre>
<p>p.s. I suggest installing <a href="https://ipython.org/" rel="noreferrer">ipython</a>, which provides powerful shell and necessary packages as well.</p> | {
"question_id": 36327134,
"question_date": "2016-03-31T07:42:34.903Z",
"question_score": 222,
"tags": "python|matplotlib|tkinter",
"answer_id": 36327323,
"answer_date": "2016-03-31T07:53:42.203Z",
"answer_score": 251
} |
Please answer the following Stack Overflow question:
Title: PHP Get Site URL Protocol - http vs https
<p>I've written a little function to establish the current site url protocol but I don't have SSL and don't know how to test if it works under https. <strong>Can you tell me if this is correct?</strong></p>
<pre><code>function siteURL()
{
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
$domainName = $_SERVER['HTTP_HOST'].'/';
return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );
</code></pre>
<p><strong>Is it necessary to do it like above or can I just do it like?:</strong></p>
<pre><code>function siteURL()
{
$protocol = 'http://';
$domainName = $_SERVER['HTTP_HOST'].'/'
return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );
</code></pre>
<p>Under SSL, doesn't the server automatically convert the url to https even if the anchor tag url is using http? Is it necessary to check for the protocol?</p>
<p>Thank you!</p> | <p>It is not automatic. Your top function looks ok.</p> | {
"question_id": 4503135,
"question_date": "2010-12-21T19:30:18.197Z",
"question_score": 222,
"tags": "php|url|ssl",
"answer_id": 4503213,
"answer_date": "2010-12-21T19:38:31.400Z",
"answer_score": 75
} |
Please answer the following Stack Overflow question:
Title: Changing the Status Bar Color for specific ViewControllers using Swift in iOS8
<pre><code>override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent;
}
</code></pre>
<p>Using the above code in any ViewController to set the statusBar color to White for a specific viewcontroller <strong><em>doesnt work in iOS8 for me</em></strong>. Any suggestions? Using the UIApplication.sharedApplication method, the color changes after required changes in the Info.plist for the whole app.</p>
<pre><code>// Change the colour of status bar from black to white
UIApplication.sharedApplication().statusBarStyle = .LightContent
</code></pre>
<p>How can I just make changes to the status bar color for some required and <strong><em>specific ViewControllers</em></strong>?</p> | <p>After reading all the suggestions, and trying out a few things, I could get this to work for specific viewcontrollers using the following steps :</p>
<p><strong>First Step:</strong></p>
<p>Open your info.plist and insert a new key named "<em>View controller-based status bar appearance</em>" to <strong><em>NO</em></strong></p>
<p><strong>Second Step (Just an explanation, no need to implement this):</strong></p>
<p>Normally we put the following code in the application(_:didFinishLaunchingWithOptions:)
method of the AppDelegate, </p>
<p><strong><em>Swift 2</em></strong></p>
<pre><code>UIApplication.sharedApplication().statusBarStyle = .LightContent
</code></pre>
<p><strong><em>Swift 3</em></strong></p>
<pre><code>UIApplication.shared.statusBarStyle = .lightContent
</code></pre>
<p>but that <em>affects the <code>statusBarStyle</code> of all the ViewControllers.</em></p>
<p><strong>So, how to get this working for specific ViewControllers - Final Step:</strong></p>
<p>Open the viewcontroller file where you want to change the <code>statusBarStyle</code> and put the following code in <code>viewWillAppear()</code>, </p>
<p><strong><em>Swift 2</em></strong></p>
<pre><code>UIApplication.sharedApplication().statusBarStyle = .LightContent
</code></pre>
<p><strong><em>Swift 3</em></strong></p>
<pre><code>UIApplication.shared.statusBarStyle = .lightContent
</code></pre>
<p>Also, implement the <code>viewWillDisappear()</code> method for that specific viewController and put the following lines of code, </p>
<p><strong><em>Swift 2</em></strong></p>
<pre><code>override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default
}
</code></pre>
<p><strong><em>Swift 3</em></strong></p>
<pre><code>override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.shared.statusBarStyle = UIStatusBarStyle.default
}
</code></pre>
<p>This step will first change the <code>statusBarStyle</code> for the specific viewcontroller and then change it back to <code>default</code> when the specific viewcontroller disappears. Not implementing the <code>viewWillDisappear()</code> will change the <code>statusBarStyle</code> permanently to the new defined value of <code>UIStatusBarStyle.LightContent</code></p> | {
"question_id": 26956728,
"question_date": "2014-11-16T12:05:37.397Z",
"question_score": 222,
"tags": "swift|uiviewcontroller|ios8|xcode6|statusbar",
"answer_id": 28513320,
"answer_date": "2015-02-14T06:59:44.867Z",
"answer_score": 360
} |
Please answer the following Stack Overflow question:
Title: How do I install imagemagick with homebrew?
<p>I'm trying to install Imagemagick on OSX Lion but something is not working as expected.</p>
<pre><code>-> brew install imagemagick
/usr/local/git/bin/git
==> Cloning https://github.com/adamv/ImageMagick.git
Cloning into /Users/klebershimabuku/Library/Caches/Homebrew/imagemagick--git...
fatal: https://github.com/adamv/ImageMagick.git/info/refs not found: did you run git update-server-info on the server?
Error: Failure while executing: git clone --depth 1 https://github.com/adamv/ImageMagick.git /Users/kleber/Library/Caches/Homebrew/imagemagick--git
</code></pre>
<p>brew doctor says:</p>
<pre><code>-> brew doctor
We couldn't detect gcc 4.0.x. Some formulae require this compiler.
Some "config" scripts were found in your path, but not in system or Homebrew folders.
`./configure` scripts often look for *-config scripts to determine if software packagesare installed, and what additional flags to use when compiling and linking.
Having additional scripts in your path can confuse software installed via Homebrew if the config script overrides a system or Homebrew provided script of the same name.
/Users/kleber/.rvm/gems/ruby-1.9.2-p180@global/bin
passenger-config
Setting DYLD_LIBARY_PATH can break dynamic linking.
You should probably unset it.
</code></pre>
<p>And yes, I have XCode 4.1 installed and running.</p>
<pre><code>-> brew update
From http://github.com/mxcl/homebrew
* branch master -> FETCH_HEAD
Already up-to-date.
</code></pre> | <p>The quickest fix for me was doing the following:</p>
<pre><code>cd /usr/local
git reset --hard FETCH_HEAD
</code></pre>
<p>Then I retried <code>brew install imagemagick</code> and it correctly pulled the package from the new mirror, instead of adamv.</p>
<p>If that does not work, ensure that <code>/Library/Caches/Homebrew</code> does not contain any imagemagick files or folders. Delete them if it does.</p> | {
"question_id": 7053996,
"question_date": "2011-08-13T23:41:48.400Z",
"question_score": 222,
"tags": "git|gcc|homebrew|osx-lion|gcc4",
"answer_id": 7407154,
"answer_date": "2011-09-13T19:11:33.500Z",
"answer_score": 97
} |
Please answer the following Stack Overflow question:
Title: SVG: text inside rect
<p>I want to display some text <em>inside</em> SVG <code>rect</code>. Is it possible?</p>
<p>I tried </p>
<pre><code><svg xmlns="http://www.w3.org/2000/svg">
<g>
<rect x="0" y="0" width="100" height="100" fill="red">
<text x="0" y="10" font-family="Verdana" font-size="55" fill="blue"> Hello </text>
</rect>
</g>
</svg>
</code></pre>
<p>But it does not work.</p> | <p>This is not possible. If you want to display text inside a rect element you should put them both in a group with the text element coming after the rect element ( so it appears on top ).</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-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg">
<g>
<rect x="0" y="0" width="100" height="100" fill="red"></rect>
<text x="0" y="50" font-family="Verdana" font-size="35" fill="blue">Hello</text>
</g>
</svg></code></pre>
</div>
</div>
</p> | {
"question_id": 6725288,
"question_date": "2011-07-17T16:43:19.823Z",
"question_score": 222,
"tags": "text|svg|rect",
"answer_id": 6732550,
"answer_date": "2011-07-18T11:59:07.810Z",
"answer_score": 307
} |
Please answer the following Stack Overflow question:
Title: Referring to a Column Alias in a WHERE Clause
<pre><code>SELECT logcount, logUserID, maxlogtm
, DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
WHERE daysdiff > 120
</code></pre>
<p>I get</p>
<blockquote>
<p>"invalid column name daysdiff". </p>
</blockquote>
<p>Maxlogtm is a datetime field. It's the little stuff that drives me crazy.</p> | <pre><code>SELECT
logcount, logUserID, maxlogtm,
DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
WHERE ( DATEDIFF(day, maxlogtm, GETDATE() > 120)
</code></pre>
<p>Normally you can't refer to field aliases in the <code>WHERE</code> clause. (Think of it as the entire <code>SELECT</code> including aliases, is applied after the <code>WHERE</code> clause.)</p>
<p>But, as mentioned in other answers, you can force SQL to treat <code>SELECT</code> to be handled before the <code>WHERE</code> clause. This is usually done with parenthesis to force logical order of operation or with a Common Table Expression (CTE):</p>
<p>Parenthesis/Subselect:</p>
<pre><code>SELECT
*
FROM
(
SELECT
logcount, logUserID, maxlogtm,
DATEDIFF(day, maxlogtm, GETDATE()) AS daysdiff
FROM statslogsummary
) as innerTable
WHERE daysdiff > 120
</code></pre>
<p>Or see Adam's answer for a CTE version of the same.</p> | {
"question_id": 8370114,
"question_date": "2011-12-03T18:57:00.920Z",
"question_score": 222,
"tags": "sql|sql-server|tsql|sql-server-2005",
"answer_id": 8370146,
"answer_date": "2011-12-03T19:00:10.913Z",
"answer_score": 266
} |
Please answer the following Stack Overflow question:
Title: Style input element to fill remaining width of its container
<p>Let's say I have an html snippet like this:</p>
<pre><code><div style="width:300px;">
<label for="MyInput">label text</label>
<input type="text" id="MyInput" />
</div>
</code></pre>
<p>This isn't my exact code, but the important thing is there's a label and a text input on the same line in a fixed-width container. How can I style the input to fill the remaining width of the container without wrapping and without knowing the size of the label?</p> | <p>as much as everyone hates tables for layout, they do help with stuff like this, either using explicit table tags or using display:table-cell</p>
<pre><code><div style="width:300px; display:table">
<label for="MyInput" style="display:table-cell; width:1px">label&nbsp;text</label>
<input type="text" id="MyInput" style="display:table-cell; width:100%" />
</div>
</code></pre> | {
"question_id": 773517,
"question_date": "2009-04-21T16:37:03.587Z",
"question_score": 222,
"tags": "html|css",
"answer_id": 773556,
"answer_date": "2009-04-21T16:47:12.767Z",
"answer_score": 153
} |
Please answer the following Stack Overflow question:
Title: How to retrieve absolute path given relative
<p>Is there a command to retrieve the absolute path given a relative path?</p>
<p>For example I want $line to contain the absolute path of each file in dir <code>./etc/</code></p>
<pre><code>find ./ -type f | while read line; do
echo $line
done
</code></pre> | <p>use:</p>
<pre><code>find "$(pwd)"/ -type f
</code></pre>
<p>to get all files or</p>
<pre><code>echo "$(pwd)/$line"
</code></pre>
<p>to display full path (if relative path matters to)</p> | {
"question_id": 4175264,
"question_date": "2010-11-13T23:24:41.623Z",
"question_score": 222,
"tags": "bash|shell|path|absolute",
"answer_id": 4175309,
"answer_date": "2010-11-13T23:34:39.050Z",
"answer_score": 81
} |
Please answer the following Stack Overflow question:
Title: RegEx for matching UK Postcodes
<p>I'm after a regex that will validate a full complex UK postcode only within an input string. All of the uncommon postcode forms must be covered as well as the usual. For instance:</p>
<p><strong>Matches</strong></p>
<ul>
<li>CW3 9SS</li>
<li>SE5 0EG</li>
<li>SE50EG</li>
<li>se5 0eg</li>
<li>WC2H 7LT</li>
</ul>
<p><strong>No Match</strong></p>
<ul>
<li>aWC2H 7LT</li>
<li>WC2H 7LTa</li>
<li>WC2H</li>
</ul>
<p>How do I solve this problem?</p> | <p>I'd recommend taking a look at the UK Government Data Standard for postcodes [link now dead; <a href="http://webarchive.nationalarchives.gov.uk/+/http://www.cabinetoffice.gov.uk/media/291370/bs7666-v2-0-xsd-PostCodeType.htm" rel="noreferrer">archive of XML</a>, see <a href="http://en.wikipedia.org/wiki/Postcodes_in_the_United_Kingdom#Validation" rel="noreferrer">Wikipedia</a> for discussion]. There is a brief description about the data and the attached xml schema provides a regular expression. It may not be exactly what you want but would be a good starting point. The RegEx differs from the XML slightly, as a P character in third position in format A9A 9AA is allowed by the definition given.</p>
<p>The RegEx supplied by the UK Government was:</p>
<pre><code>([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9][A-Za-z]?))))\s?[0-9][A-Za-z]{2})
</code></pre>
<p>As pointed out on the Wikipedia discussion, this will allow some non-real postcodes (e.g. those starting AA, ZY) and they do provide a more rigorous test that you could try.</p> | {
"question_id": 164979,
"question_date": "2008-10-02T23:05:03.907Z",
"question_score": 222,
"tags": "regex|validation|regex-group|postal-code",
"answer_id": 164994,
"answer_date": "2008-10-02T23:13:26.197Z",
"answer_score": 246
} |
Please answer the following Stack Overflow question:
Title: How can I remove or replace SVG content?
<p>I have a piece of JavaScript code which creates (using D3.js) an <code>svg</code> element which contains a chart. I want to update the chart based on new data coming from a web service using AJAX, the problem is that each time I click on the update button, it generates a new <code>svg</code>, so I want to remove the old one or update its content.</p>
<p>Here is a snippet from the JavaScript function where I create the <code>svg</code>:</p>
<pre><code>var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
</code></pre>
<p>How can I remove the old <code>svg</code> element or at least replace its content?</p> | <p>Here is the solution:</p>
<pre><code>d3.select("svg").remove();
</code></pre>
<p>This is a <code>remove</code> function provided by D3.js.</p> | {
"question_id": 10784018,
"question_date": "2012-05-28T11:34:45.093Z",
"question_score": 222,
"tags": "javascript|ajax|svg|d3.js",
"answer_id": 10911546,
"answer_date": "2012-06-06T09:30:10.150Z",
"answer_score": 310
} |
Please answer the following Stack Overflow question:
Title: Python glob multiple filetypes
<p>Is there a better way to use glob.glob in python to get a list of multiple file types such as .txt, .mdown, and .markdown? Right now I have something like this:</p>
<pre><code>projectFiles1 = glob.glob( os.path.join(projectDir, '*.txt') )
projectFiles2 = glob.glob( os.path.join(projectDir, '*.mdown') )
projectFiles3 = glob.glob( os.path.join(projectDir, '*.markdown') )
</code></pre> | <p>Maybe there is a better way, but how about:</p>
<pre><code>import glob
types = ('*.pdf', '*.cpp') # the tuple of file types
files_grabbed = []
for files in types:
files_grabbed.extend(glob.glob(files))
# files_grabbed is the list of pdf and cpp files
</code></pre>
<p>Perhaps there is another way, so wait in case someone else comes up with a better answer.</p> | {
"question_id": 4568580,
"question_date": "2010-12-31T06:39:15.140Z",
"question_score": 222,
"tags": "python|glob",
"answer_id": 4568638,
"answer_date": "2010-12-31T06:53:41.133Z",
"answer_score": 213
} |
Please answer the following Stack Overflow question:
Title: Set types on useState React Hook with TypeScript
<p>I'm migrating a React with TypeScript project to use hooks features (React v16.7.0-alpha), but I cannot figure out how to set typings of the destructured elements.</p>
<p>Here is an example:</p>
<pre><code>interface IUser {
name: string;
}
...
const [user, setUser] = useState({name: 'Jon'});
</code></pre>
<p>I want to force <code>user</code> variable to be of type <code>IUser</code>. My only successful trial, is doing it in two phases: Typing, then initializing:</p>
<pre><code>let user: IUser;
let setUser: any;
[user, setUser] = useState({name: 'Jon'});
</code></pre>
<p>But I'm sure there is a better way. Also, <code>setUser</code> should be initialized as a function that takes a <code>IUser</code> as input, and returns nothing.</p>
<p>Also, worth noting that using <code>const [user, setUser] = useState({name: 'Jon'});</code> without any initialization works fine, but I would like to take advantage of TypeScript to force type checking on init, especially if it depends on some props.</p>
<p>Thanks for your help.</p> | <p>Use this</p>
<pre><code>const [user, setUser] = useState<IUser>({name: 'Jon'});
</code></pre>
<p>See the <a href="https://github.com/DefinitelyTyped/DefinitelyTyped/blob/ba2bb0f/types/react/index.d.ts#L916" rel="noreferrer">Corresponding Type in DefinitelyTyped</a></p> | {
"question_id": 53650468,
"question_date": "2018-12-06T11:31:12.593Z",
"question_score": 222,
"tags": "reactjs|typescript|react-hooks",
"answer_id": 53650561,
"answer_date": "2018-12-06T11:35:42.087Z",
"answer_score": 470
} |
Please answer the following Stack Overflow question:
Title: Sublime Text from Command Line
<p>I installed Sublime Text and wanted to know how to open <code>rb</code> files in it from the terminal. I saw <a href="https://stackoverflow.com/questions/7594091/what-is-the-command-to-make-sublime-text-my-core-editor">What is the command to make Sublime Text my core editor?</a> and I see that I can make Sublime my core editor, but I want to be able to type</p>
<pre><code>sublime file.rb
</code></pre>
<p>How do I do this in Windows?</p> | <p>From build <a href="http://www.sublimetext.com/3" rel="noreferrer">3065</a> (Release Date: 29 August 2014) onwards <code>Sublime text</code> includes a command line helper, nameley <code>subl.exe</code>. It is at sublime's installation folder: copy it in to a folder included in the system path.
For example, in my case I copied it</p>
<p>from <code>C:\Program Files\Sublime Text 3</code> </p>
<p>to <code>C:\Windows\System32</code></p>
<p>You may then use in your terminal/console <code>subl</code> as a command to open whatever file, such as in your example:</p>
<p><code>subl file.rb</code></p>
<p>Or you may as well modify your system <code>PATH</code> variable to include sublime's instalation folder, but I believe that is much more involved.</p> | {
"question_id": 9440639,
"question_date": "2012-02-25T02:27:50.990Z",
"question_score": 222,
"tags": "windows|terminal|sublimetext",
"answer_id": 25577833,
"answer_date": "2014-08-30T00:21:30.857Z",
"answer_score": 175
} |
Please answer the following Stack Overflow question:
Title: Find which commit is currently checked out in Git
<p>I'm in the middle of a <code>git bisect</code> session. </p>
<p>What's the command to find out which commit (SHA1 hash) I am currently on? <code>git status</code> does not provide this. </p>
<p>Edit: I guess calling <code>git log</code> and looking at first entry works? </p> | <p>You have at least 5 different ways to view the commit you currently have checked out into your working copy during a <code>git bisect</code> session (<strong>note that options 1-4 will also work when you're not doing a bisect</strong>):</p>
<ol>
<li><code>git show</code>.</li>
<li><code>git log -1</code>.</li>
<li>Bash prompt.</li>
<li><code>git status</code>.</li>
<li><code>git bisect visualize</code>.</li>
</ol>
<p>I'll explain each option in detail below. </p>
<h3>Option 1: git show</h3>
<p>As explained in <a href="https://stackoverflow.com/questions/11168141/git-which-commit-am-i-on-have-checked-out/11168148#11168148">this answer</a> to the general question of how to determine which commit you currently have checked-out (not just during <code>git bisect</code>), you can use <code>git show</code> with the <code>-s</code> option to suppress patch output:</p>
<pre><code>$ git show --oneline -s
a9874fd Merge branch 'epic-feature'
</code></pre>
<h3>Option 2: git log -1</h3>
<p>You can also simply do <code>git log -1</code> to find out which commit you're currently on.</p>
<pre><code>$ git log -1 --oneline
c1abcde Add feature-003
</code></pre>
<h3>Option 3: Bash prompt</h3>
<p>In Git version 1.8.3+ (or was it an earlier version?), if you have your Bash prompt configured to show the current branch you have checked out into your working copy, then it will also show you the current commit you have checked out during a bisect session or when you're in a "detached HEAD" state. In the example below, I currently have <code>c1abcde</code> checked out:</p>
<pre><code># Prompt during a bisect
user ~ (c1abcde...)|BISECTING $
# Prompt at detached HEAD state
user ~ (c1abcde...) $
</code></pre>
<h3>Option 4: git status</h3>
<p>Also as of Git version 1.8.3+ (and possibly earlier, again not sure), running <code>git status</code> will also show you what commit you have checked out during a bisect and when you're in detached HEAD state:</p>
<pre><code>$ git status
# HEAD detached at c1abcde <== RIGHT HERE
</code></pre>
<h3>Option 5: git bisect visualize</h3>
<p>Finally, while you're doing a <code>git bisect</code>, you can also simply use <a href="https://www.kernel.org/pub/software/scm/git/docs/git-bisect.html#_bisect_visualize" rel="noreferrer"><code>git bisect visualize</code></a> or its built-in alias <code>git bisect view</code> to launch <code>gitk</code>, so that you can graphically view which commit you are on, as well as which commits you have marked as bad and good so far. I'm pretty sure this existed well before version 1.8.3, I'm just not sure in which version it was introduced:</p>
<pre class="lang-bash prettyprint-override"><code>git bisect visualize
git bisect view # shorter, means same thing
</code></pre>
<p><img src="https://i.stack.imgur.com/qaCQU.png" alt="enter image description here"></p> | {
"question_id": 11168141,
"question_date": "2012-06-23T08:51:38.843Z",
"question_score": 222,
"tags": "git",
"answer_id": 18160212,
"answer_date": "2013-08-10T08:46:01.067Z",
"answer_score": 260
} |
Please answer the following Stack Overflow question:
Title: How to 'bulk update' with Django?
<p>I'd like to update a table with Django - something like this in raw SQL:</p>
<pre><code>update tbl_name set name = 'foo' where name = 'bar'
</code></pre>
<p>My first result is something like this - but that's nasty, isn't it?</p>
<pre><code>list = ModelClass.objects.filter(name = 'bar')
for obj in list:
obj.name = 'foo'
obj.save()
</code></pre>
<p>Is there a more elegant way?</p> | <h2>Update:</h2>
<p>Django 2.2 version now has a <a href="https://docs.djangoproject.com/en/stable/ref/models/querysets/#bulk-update" rel="noreferrer">bulk_update</a>.</p>
<h2>Old answer:</h2>
<p>Refer to the following django documentation section</p>
<blockquote>
<p><a href="https://docs.djangoproject.com/en/stable/topics/db/queries/#updating-multiple-objects-at-once" rel="noreferrer">Updating multiple objects at once</a></p>
</blockquote>
<p>In short you should be able to use: </p>
<pre><code>ModelClass.objects.filter(name='bar').update(name="foo")
</code></pre>
<p>You can also use <code>F</code> objects to do things like incrementing rows:</p>
<pre><code>from django.db.models import F
Entry.objects.all().update(n_pingbacks=F('n_pingbacks') + 1)
</code></pre>
<p>See the <a href="https://docs.djangoproject.com/en/stable/topics/db/queries/" rel="noreferrer">documentation</a>.</p>
<p>However, note that: </p>
<ul>
<li>This won't use <code>ModelClass.save</code> method (so if you have some logic inside it won't be triggered). </li>
<li>No django signals will be emitted.</li>
<li>You can't perform an <code>.update()</code> on a sliced QuerySet, it must be on an original QuerySet so you'll need to lean on the <code>.filter()</code> and <code>.exclude()</code> methods.</li>
</ul> | {
"question_id": 12661253,
"question_date": "2012-09-30T12:30:07.353Z",
"question_score": 222,
"tags": "django|django-models",
"answer_id": 12661327,
"answer_date": "2012-09-30T12:43:55.860Z",
"answer_score": 337
} |
Please answer the following Stack Overflow question:
Title: How do I merge a git tag onto a branch
<p>I'm trying to find the syntax for merging a tagged commit onto another branch. I'm guessing that it's straight forward but my feeble search attempts aren't finding it.</p> | <p>You mean this?</p>
<pre><code>git checkout destination_branch
git merge tag_name
</code></pre> | {
"question_id": 17051504,
"question_date": "2013-06-11T18:47:02.903Z",
"question_score": 222,
"tags": "git-merge|git-tag",
"answer_id": 17052417,
"answer_date": "2013-06-11T19:44:29.253Z",
"answer_score": 357
} |
Please answer the following Stack Overflow question:
Title: Best approach to real time http streaming to HTML5 video client
<p>I'm really stuck trying to understand the best way to stream real time output of ffmpeg to a HTML5 client using node.js, as there are a number of variables at play and I don't have a lot of experience in this space, having spent many hours trying different combinations.</p>
<p>My use case is:</p>
<p>1) IP video camera RTSP H.264 stream is picked up by FFMPEG and remuxed into a mp4 container using the following FFMPEG settings in node, output to STDOUT. This is only run on the initial client connection, so that partial content requests don't try to spawn FFMPEG again.</p>
<pre><code>liveFFMPEG = child_process.spawn("ffmpeg", [
"-i", "rtsp://admin:[email protected]:554" , "-vcodec", "copy", "-f",
"mp4", "-reset_timestamps", "1", "-movflags", "frag_keyframe+empty_moov",
"-" // output to stdout
], {detached: false});
</code></pre>
<p>2) I use the node http server to capture the STDOUT and stream that back to the client upon a client request. When the client first connects I spawn the above FFMPEG command line then pipe the STDOUT stream to the HTTP response.</p>
<pre><code>liveFFMPEG.stdout.pipe(resp);
</code></pre>
<p>I have also used the stream event to write the FFMPEG data to the HTTP response but makes no difference</p>
<pre><code>xliveFFMPEG.stdout.on("data",function(data) {
resp.write(data);
}
</code></pre>
<p>I use the following HTTP header (which is also used and working when streaming pre-recorded files)</p>
<pre><code>var total = 999999999 // fake a large file
var partialstart = 0
var partialend = total - 1
if (range !== undefined) {
var parts = range.replace(/bytes=/, "").split("-");
var partialstart = parts[0];
var partialend = parts[1];
}
var start = parseInt(partialstart, 10);
var end = partialend ? parseInt(partialend, 10) : total; // fake a large file if no range reques
var chunksize = (end-start)+1;
resp.writeHead(206, {
'Transfer-Encoding': 'chunked'
, 'Content-Type': 'video/mp4'
, 'Content-Length': chunksize // large size to fake a file
, 'Accept-Ranges': 'bytes ' + start + "-" + end + "/" + total
});
</code></pre>
<p>3) The client has to use HTML5 video tags.</p>
<p>I have no problems with streaming playback (using fs.createReadStream with 206 HTTP partial content) to the HTML5 client a video file previously recorded with the above FFMPEG command line (but saved to a file instead of STDOUT), so I know the FFMPEG stream is correct, and I can even correctly see the video live streaming in VLC when connecting to the HTTP node server.</p>
<p>However trying to stream live from FFMPEG via node HTTP seems to be a lot harder as the client will display one frame then stop. I suspect the problem is that I am not setting up the HTTP connection to be compatible with the HTML5 video client. I have tried a variety of things like using HTTP 206 (partial content) and 200 responses, putting the data into a buffer then streaming with no luck, so I need to go back to first principles to ensure I'm setting this up the right way.</p>
<p>Here is my understanding of how this should work, please correct me if I'm wrong:</p>
<p>1) FFMPEG should be setup to fragment the output and use an empty moov (FFMPEG frag_keyframe and empty_moov mov flags). This means the client does not use the moov atom which is typically at the end of the file which isn't relevant when streaming (no end of file), but means no seeking possible which is fine for my use case.</p>
<p>2) Even though I use MP4 fragments and empty MOOV, I still have to use HTTP partial content, as the HTML5 player will wait until the entire stream is downloaded before playing, which with a live stream never ends so is unworkable.</p>
<p>3) I don't understand why piping the STDOUT stream to the HTTP response doesn't work when streaming live yet if I save to a file I can stream this file easily to HTML5 clients using similar code. Maybe it's a timing issue as it takes a second for the FFMPEG spawn to start, connect to the IP camera and send chunks to node, and the node data events are irregular as well. However the bytestream should be exactly the same as saving to a file, and HTTP should be able to cater for delays.</p>
<p>4) When checking the network log from the HTTP client when streaming a MP4 file created by FFMPEG from the camera, I see there are 3 client requests: A general GET request for the video, which the HTTP server returns about 40Kb, then a partial content request with a byte range for the last 10K of the file, then a final request for the bits in the middle not loaded. Maybe the HTML5 client once it receives the first response is asking for the last part of the file to load the MP4 MOOV atom? If this is the case it won't work for streaming as there is no MOOV file and no end of the file.</p>
<p>5) When checking the network log when trying to stream live, I get an aborted initial request with only about 200 bytes received, then a re-request again aborted with 200 bytes and a third request which is only 2K long. I don't understand why the HTML5 client would abort the request as the bytestream is exactly the same as I can successfully use when streaming from a recorded file. It also seems node isn't sending the rest of the FFMPEG stream to the client, yet I can see the FFMPEG data in the .on event routine so it is getting to the FFMPEG node HTTP server.</p>
<p>6) Although I think piping the STDOUT stream to the HTTP response buffer should work, do I have to build an intermediate buffer and stream that will allow the HTTP partial content client requests to properly work like it does when it (successfully) reads a file? I think this is the main reason for my problems however I'm not exactly sure in Node how to best set that up. And I don't know how to handle a client request for the data at the end of the file as there is no end of file.</p>
<p>7) Am I on the wrong track with trying to handle 206 partial content requests, and should this work with normal 200 HTTP responses? HTTP 200 responses works fine for VLC so I suspect the HTML5 video client will only work with partial content requests?</p>
<p>As I'm still learning this stuff its difficult to work through the various layers of this problem (FFMPEG, node, streaming, HTTP, HTML5 video) so any pointers will be greatly appreciated. I have spent hours researching on this site and the net, and I have not come across anyone who has been able to do real time streaming in node but I can't be the first, and I think this should be able to work (somehow!).</p> | <blockquote>
<p>EDIT 3: As of IOS 10, HLS will support fragmented mp4 files. The answer
now, is to create fragmented mp4 assets, with a DASH and HLS manifest. > Pretend flash, iOS9 and below and IE 10 and below don't exist.</p>
</blockquote>
<h2>Everything below this line is out of date. Keeping it here for posterity.</h2>
<hr>
<blockquote>
<p>EDIT 2: As people in the comments are pointing out, things change.
Almost all browsers will support AVC/AAC codecs.
iOS still requires HLS. But via adaptors like hls.js you can play
HLS in MSE. The new answer is HLS+hls.js if you need iOS. or just
Fragmented MP4 (i.e. DASH) if you don't</p>
</blockquote>
<p>There are many reasons why video and, specifically, live video is very difficult. (Please note that the original question specified that HTML5 video is a requirement, but the asker stated Flash is possible in the comments. So immediately, this question is misleading)</p>
<p>First I will restate: <strong>THERE IS NO OFFICIAL SUPPORT FOR LIVE STREAMING OVER HTML5</strong>. There are hacks, but your mileage may vary.</p>
<blockquote>
<p>EDIT: since I wrote this answer Media Source Extensions have matured,
and are now very close to becoming a viable option. They are supported
on most major browsers. IOS continues to be a hold out.</p>
</blockquote>
<p>Next, you need to understand that Video on demand (VOD) and live video are very different. Yes, they are both video, but the problems are different, hence the formats are different. For example, if the clock in your computer runs 1% faster than it should, you will not notice on a VOD. With live video, you will be trying to play video before it happens. If you want to join a a live video stream in progress, you need the data necessary to initialize the decoder, so it must be repeated in the stream, or sent out of band. With VOD, you can read the beginning of the file them seek to whatever point you wish.</p>
<p>Now let's dig in a bit.</p>
<p>Platforms:</p>
<ul>
<li>iOS</li>
<li>PC</li>
<li>Mac</li>
<li>Android</li>
</ul>
<p>Codecs:</p>
<ul>
<li>vp8/9</li>
<li>h.264</li>
<li>thora (vp3)</li>
</ul>
<p>Common Delivery methods for live video in browsers:</p>
<ul>
<li>DASH (HTTP)</li>
<li>HLS (HTTP)</li>
<li>flash (RTMP)</li>
<li>flash (HDS)</li>
</ul>
<p>Common Delivery methods for VOD in browsers:</p>
<ul>
<li>DASH (HTTP Streaming)</li>
<li>HLS (HTTP Streaming)</li>
<li>flash (RTMP)</li>
<li>flash (HTTP Streaming)</li>
<li>MP4 (HTTP pseudo streaming)</li>
<li>I'm not going to talk about MKV and OOG because I do not know them very well.</li>
</ul>
<p>html5 video tag:</p>
<ul>
<li>MP4</li>
<li>webm</li>
<li>ogg</li>
</ul>
<hr>
<p>Lets look at which browsers support what formats</p>
<p>Safari:</p>
<ul>
<li>HLS (iOS and mac only)</li>
<li>h.264</li>
<li>MP4</li>
</ul>
<p>Firefox</p>
<ul>
<li>DASH (via MSE but no h.264)</li>
<li>h.264 via Flash only!</li>
<li>VP9</li>
<li>MP4</li>
<li>OGG</li>
<li>Webm</li>
</ul>
<p>IE</p>
<ul>
<li>Flash</li>
<li>DASH (via MSE IE 11+ only)</li>
<li>h.264</li>
<li>MP4</li>
</ul>
<p>Chrome</p>
<ul>
<li>Flash</li>
<li>DASH (via MSE)</li>
<li>h.264</li>
<li>VP9</li>
<li>MP4</li>
<li>webm</li>
<li>ogg</li>
</ul>
<p>MP4 cannot be used for live video (NOTE: DASH is a superset of MP4, so don't get confused with that). MP4 is broken into two pieces: moov and mdat. mdat contains the raw audio video data. But it is not indexed, so without the moov, it is useless. The moov contains an index of all data in the mdat. But due to its format, it can not be 'flattened' until the timestamps and size of EVERY frame is known. It may be possible to construct an moov that 'fibs' the frame sizes, but is is very wasteful bandwidth wise. </p>
<p>So if you want to deliver everywhere, we need to find the least common denominator. You will see there is no LCD here without resorting to flash
example:</p>
<ul>
<li>iOS only supports h.264 video. and it only supports HLS for live.</li>
<li>Firefox does not support h.264 at all, unless you use flash</li>
<li>Flash does not work in iOS</li>
</ul>
<p>The closest thing to an LCD is using HLS to get your iOS users, and flash for everyone else.
My personal favorite is to encode HLS, then use flash to play HLS for everyone else. You can play HLS in flash via JW player 6, (or write your own HLS to FLV in AS3 like I did)</p>
<p>Soon, the most common way to do this will be HLS on iOS/Mac and DASH via MSE everywhere else (This is what Netflix will be doing soon). But we are still waiting for everyone to upgrade their browsers. You will also likely need a separate DASH/VP9 for Firefox (I know about open264; it sucks. It can't do video in main or high profile. So it is currently useless).</p> | {
"question_id": 21921790,
"question_date": "2014-02-20T23:13:51.723Z",
"question_score": 222,
"tags": "html|node.js|ffmpeg|streaming",
"answer_id": 22001830,
"answer_date": "2014-02-25T00:01:36.693Z",
"answer_score": 215
} |
Please answer the following Stack Overflow question:
Title: Python memory leaks
<p>I have a long-running script which, if let to run long enough, will consume all the memory on my system.</p>
<p>Without going into details about the script, I have two questions:</p>
<ol>
<li>Are there any "Best Practices" to follow, which will help prevent leaks from occurring?</li>
<li>What techniques are there to debug memory leaks in Python?</li>
</ol> | <p>Have a look at this article: <a href="https://web.archive.org/web/20160316152429/http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks/" rel="noreferrer">Tracing python memory leaks</a></p>
<p>Also, note that the <a href="http://docs.python.org/library/gc.html" rel="noreferrer">garbage collection module</a> actually can have debug flags set. Look at the <code>set_debug</code> function. Additionally, look at <a href="https://stackoverflow.com/questions/1641231/python-working-around-memory-leaks/1641280#1641280">this code by Gnibbler</a> for determining the types of objects that have been created after a call.</p> | {
"question_id": 1435415,
"question_date": "2009-09-16T20:56:04.007Z",
"question_score": 222,
"tags": "python|debugging|memory-management|memory-leaks",
"answer_id": 1435426,
"answer_date": "2009-09-16T20:58:17.077Z",
"answer_score": 113
} |
Please answer the following Stack Overflow question:
Title: Omitting the first line from any Linux command output
<p>I have a requirement where i'd like to omit the 1st line from the output of <code>ls -latr "some path"</code> Since I need to remove <code>total 136</code> from the below output</p>
<p><img src="https://i.stack.imgur.com/OtM9M.png" alt="enter image description here"></p>
<p>So I wrote <code>ls -latr /home/kjatin1/DT_901_linux//autoInclude/system | tail -q</code> which excluded the 1st line, but when the folder is empty it does not omit it. Please tell me how to omit 1st line in any linux command output</p> | <p>Pipe it to <code>awk</code>:</p>
<pre><code>awk '{if(NR>1)print}'
</code></pre>
<p>or <code>sed</code></p>
<pre><code>sed -n '1!p'
</code></pre> | {
"question_id": 7318497,
"question_date": "2011-09-06T10:34:56.100Z",
"question_score": 222,
"tags": "linux",
"answer_id": 7318521,
"answer_date": "2011-09-06T10:37:35.400Z",
"answer_score": 223
} |
Please answer the following Stack Overflow question:
Title: How to add a "open git-bash here..." context menu to the windows explorer?
<p>How to add a context (aka right click) menu to the windows explorer that, when clicked, opens the git-bash console in the current explorer folder?</p> | <p>I had a similar issue and I did this.</p>
<p><strong>Step 1 :</strong> Type "regedit" in start menu</p>
<p><strong>Step 2 :</strong> Run the registry editor</p>
<p><strong>Step 3 :</strong> Navigate to <code>HKEY_CURRENT_USER\SOFTWARE\Classes\Directory\Background\shell</code>. If you don't have the <code>shell</code> key, create one.</p>
<p><strong>Step 4 :</strong> Right-click on "shell" and choose New > Key. name the Key "Bash"</p>
<p><a href="https://i.stack.imgur.com/7dRPE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/7dRPE.png" alt="Right click on "shell" and choose New > Key. name the Key "Bash"" /></a></p>
<p><strong>Step 5 :</strong> Modify the value and set it to "open in Bash" This is the text that appears in the right click.</p>
<p><a href="https://i.stack.imgur.com/4TdTS.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4TdTS.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/MSS45.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MSS45.png" alt="enter image description here" /></a></p>
<p><strong>Step 6 :</strong> Create a new key under Bash and name it "command". Set the value of this key to your git-bash.exe path.</p>
<p><a href="https://i.stack.imgur.com/GR6jY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GR6jY.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/hBorr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/hBorr.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/NAZr6.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NAZr6.png" alt="enter image description here" /></a></p>
<p>Close the registry editor.</p>
<p>You should now be able to see the option in right click menu in explorer</p>
<p><strong>PS</strong> Git Bash by default picks up the current directory.</p>
<p><em><strong>EDIT</strong></em> : If you want a one click approach, check Ozesh's <a href="https://stackoverflow.com/a/44019893/466314">solution below</a></p> | {
"question_id": 24386657,
"question_date": "2014-06-24T12:28:25.167Z",
"question_score": 222,
"tags": "git|contextmenu|windows-explorer|windows-shell-extension-menu",
"answer_id": 39194769,
"answer_date": "2016-08-28T18:59:44.860Z",
"answer_score": 266
} |
Please answer the following Stack Overflow question:
Title: Is there a way to comment out markup in an .ASPX page?
<p>Is there a way to comment out markup in an <code>.ASPX</code> page so that it isn't delivered to the client? I have tried the standard comments <code><!-- --></code> but this just gets delivered as a comment and doesn't prevent the control from rendering. </p> | <pre><code><%--
Commented out HTML/CODE/Markup. Anything with
this block will not be parsed/handled by ASP.NET.
<asp:Calendar runat="server"></asp:Calendar>
<%# Eval(“SomeProperty”) %>
--%>
</code></pre>
<p><a href="http://weblogs.asp.net/scottgu/archive/2006/07/09/Tip_2F00_Trick_3A00_-Using-Server-Side-Comments-with-ASP.NET-2.0-.aspx" rel="noreferrer">Source</a></p> | {
"question_id": 121382,
"question_date": "2008-09-23T14:34:01.367Z",
"question_score": 222,
"tags": "asp.net|markup|comments",
"answer_id": 121400,
"answer_date": "2008-09-23T14:35:34.263Z",
"answer_score": 346
} |
Please answer the following Stack Overflow question:
Title: The number of method references in a .dex file cannot exceed 64k API 17
<p>I am building an app with SugarORM Library but when I try to build the project for API 17 (didn't check for others) it shows build error.</p>
<pre><code> Information:Gradle tasks [:app:assembleDebug]
:app:preBuild UP-TO-DATE
:app:preDebugBuild UP-TO-DATE
:app:checkDebugManifest
:app:preReleaseBuild UP-TO-DATE
:app:prepareComAndroidSupportAnimatedVectorDrawable2330Library UP-TO-DATE
:app:prepareComAndroidSupportAppcompatV72330Library UP-TO-DATE
:app:prepareComAndroidSupportCardviewV72330Library UP-TO-DATE
:app:prepareComAndroidSupportDesign2330Library UP-TO-DATE
:app:prepareComAndroidSupportMediarouterV72300Library UP-TO-DATE
:app:prepareComAndroidSupportRecyclerviewV72330Library UP-TO-DATE
:app:prepareComAndroidSupportSupportV42330Library UP-TO-DATE
:app:prepareComAndroidSupportSupportVectorDrawable2330Library UP-TO-DATE
:app:prepareComAndroidVolleyVolley100Library UP-TO-DATE
:app:prepareComGithubSatyanSugar14Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServices840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesAds840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesAnalytics840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesAppindexing840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesAppinvite840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesAppstate840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesAuth840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesBase840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesBasement840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesCast840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesDrive840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesFitness840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesGames840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesGcm840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesIdentity840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesLocation840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesMaps840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesMeasurement840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesNearby840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesPanorama840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesPlus840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesSafetynet840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesVision840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesWallet840Library UP-TO-DATE
:app:prepareComGoogleAndroidGmsPlayServicesWearable840Library UP-TO-DATE
:app:prepareMeDrakeetMaterialdialogLibrary131Library UP-TO-DATE
:app:prepareDebugDependencies
:app:compileDebugAidl UP-TO-DATE
:app:compileDebugRenderscript UP-TO-DATE
:app:generateDebugBuildConfig UP-TO-DATE
:app:generateDebugAssets UP-TO-DATE
:app:mergeDebugAssets UP-TO-DATE
:app:generateDebugResValues UP-TO-DATE
:app:generateDebugResources UP-TO-DATE
:app:mergeDebugResources UP-TO-DATE
:app:processDebugManifest UP-TO-DATE
:app:processDebugResources UP-TO-DATE
:app:generateDebugSources UP-TO-DATE
:app:compileDebugJavaWithJavac
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
:app:compileDebugNdk UP-TO-DATE
:app:compileDebugSources
:app:prePackageMarkerForDebug
:app:transformClassesWithDexForDebug
Error:The number of method references in a .dex file cannot exceed 64K.
Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html
Error:Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.8.0_51.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2
Information:BUILD FAILED
Information:Total time: 21.663 secs
Information:2 errors
Information:0 warnings
Information:See complete output in console
</code></pre>
<p>But when I build this project for android v5.0 or above, it works fine. If I remove SugarORM gradle dependency it works fine for both devices v4.2.2 and v5.0.</p> | <p>You have too many methods. There can only be <strong>65536 methods for dex</strong>.</p>
<p>As suggested you can use the <a href="https://developer.android.com/tools/building/multidex.html" rel="noreferrer"><strong>multidex support</strong></a>.</p>
<p>Just add these lines in the <code>module/build.gradle</code>:</p>
<pre><code>android {
defaultConfig {
...
// Enabling multidex support.
multiDexEnabled true
}
...
}
dependencies {
implementation 'androidx.multidex:multidex:2.0.1' //with androidx libraries
//implementation 'com.android.support:multidex:1.0.3' //with support libraries
}
</code></pre>
<p>Also in your <code>Manifest</code> add the <code>MultiDexApplication</code> class from the multidex support library to the application element</p>
<pre><code> <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.multidex.myapplication">
<application
...
android:name="androidx.multidex.MultiDexApplication">
<!-- If you are using support libraries use android:name="android.support.multidex.MultiDexApplication" -->
<!--If you are using your own custom Application class then extend -->
<!--MultiDexApplication and change above line as-->
<!--android:name=".YourCustomApplicationClass"> -->
...
</application>
</manifest>
</code></pre>
<p>If you are using your own <code>Application</code> class, change the parent class from <code>Application</code> to <code>MultiDexApplication</code>.<br />
If you can't do it, in your Application class override the <code>attachBaseContext</code> method with:</p>
<pre><code>@Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(newBase);
MultiDex.install(this);
}
</code></pre>
<p>Another solution is to try to remove unused code with <strong>ProGuard</strong> - Configure the <a href="https://developer.android.com/tools/help/proguard.html" rel="noreferrer">ProGuard</a> settings for your app to run ProGuard and ensure you have shrinking enabled for release builds.</p> | {
"question_id": 36785014,
"question_date": "2016-04-22T04:46:34.863Z",
"question_score": 222,
"tags": "android|gradle|android-gradle-plugin|android-multidex|sugarorm",
"answer_id": 36786721,
"answer_date": "2016-04-22T06:43:01.837Z",
"answer_score": 490
} |
Please answer the following Stack Overflow question:
Title: Service located in another namespace
<p>I have been trying to find a way to define a service in one namespace that links to a Pod running in another namespace. I know that containers in a Pod running in <code>namespaceA</code> can access <code>serviceX</code> defined in <code>namespaceB</code> by referencing it in the cluster DNS as <code>serviceX.namespaceB.svc.cluster.local</code>, but I would rather not have the code inside the container need to know about the location of <code>serviceX</code>. That is, I want the code to just lookup <code>serviceX</code> and then be able to access it.</p>
<p>The <a href="http://kubernetes.io/docs/user-guide/services/" rel="noreferrer">Kubernetes documentation</a> suggests that this is possible. It says that one of the reasons that you would define a service without a selector is that <strong>You want to point your service to a service in another Namespace or on another cluster</strong>.</p>
<p>That suggests to me that I should:</p>
<ol>
<li>Define a <code>serviceX</code> service in <code>namespaceA</code>, without a selector (since the POD I want to select isn't in <code>namespaceA</code>).</li>
<li>Define a service (which I also called <code>serviceX</code>) in <code>namespaceB</code>, and then</li>
<li>Define an Endpoints object in <code>namespaceA</code> to point to <code>serviceX</code> in <code>namespaceB</code>.</li>
</ol>
<p>It is this third step that I have not been able to accomplish.</p>
<p>First, I tried defining the Endpoints object this way:</p>
<pre class="lang-yaml prettyprint-override"><code>kind: Endpoints
apiVersion: v1
metadata:
name: serviceX
namespace: namespaceA
subsets:
- addresses:
- targetRef:
kind: Service
namespace: namespaceB
name: serviceX
apiVersion: v1
ports:
- name: http
port: 3000
</code></pre>
<p>That seemed the logical approach, and <em>obviously</em> what the <code>targetRef</code> was for. But, this led to an error saying that the <code>ip</code> field in the <code>addresses</code> array was mandatory. So, my next try was to assign a fixed ClusterIP address to <code>serviceX</code> in <code>namespaceB</code>, and put that in the IP field (note that the <code>service_cluster_ip_range</code> is configured as <code>192.168.0.0/16</code>, and <code>192.168.1.1</code> was assigned as the ClusterIP for <code>serviceX</code> in <code>namespaceB</code>; <code>serviceX</code> in <code>namespaceA</code> was auto assigned a different ClusterIP on the <code>192.168.0.0/16</code> subnet):</p>
<pre class="lang-yaml prettyprint-override"><code>kind: Endpoints
apiVersion: v1
metadata:
name: serviceX
namespace: namespaceA
subsets:
- addresses:
- ip: 192.168.1.1
targetRef:
kind: Service
namespace: namespaceB
name: serviceX
apiVersion: v1
ports:
- name: http
port: 3000
</code></pre>
<p>That was accepted, but accesses to <code>serviceX</code> in <code>namespaceA</code> did not get forwarded to the Pod in <code>namespaceB</code> - they timed out. Looking at the iptables setup, it looks like it would have had to do NAT pre-routing twice to accomplish that.</p>
<p>The only thing I did find that worked - but is not a satisfactory solution - is to lookup the actual IP address of the Pod providing <code>serviceX</code> in <code>namespaceB</code> and put that address in the Endpoints object in <code>namespaceA</code>. That isn't satisfactory, of course, because the Pod IP address may change over time. That's the problem service IPs are there to solve.</p>
<p>So, is there a way to meet what seems to be the promise of the documentation that I can point a service in one namespace to a <em>service</em> running in a different namespace?</p>
<p>A commenter questioned why you would want to do this - here is a use case that makes sense to me, at least:</p>
<p>Say you have a multi-tenant system, which also includes a common data-access function that can be shared between tenants. Now imagine that there are different flavors of this data-access function with common APIs, but different performance characteristics. Some tenants get access to one of them, other tenants have access to another one.</p>
<p>Each tenant's pods run in their own namespaces, but each one needs to access one of these common data-access services, which will necessarily be in another namespace (since it is accessed by multiple tenants). But, you wouldn't want the tenant to have to change their code if their subscription changes to access the higher-performing service.</p>
<p>A potential solution (the cleanest one I can think of, if only it worked) is to include a service definition in each tenant's namespace for the data-access service, with each one configured for the appropriate endpoint. This service definition would be configured to point to the proper data-access service each tenant is entitled to use.</p> | <p>I stumbled over the same issue and found a nice solution which does not need any static ip configuration:</p>
<p>You can access a service via it's <a href="https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/" rel="noreferrer">DNS name</a> (as mentioned by you): <em>servicename.namespace.svc.cluster.local</em></p>
<p>You can use that DNS name to reference it in <a href="https://kubernetes.io/docs/concepts/services-networking/service/#services-without-selectors" rel="noreferrer">another namespace via a local service</a>:</p>
<pre class="lang-yaml prettyprint-override"><code>kind: Service
apiVersion: v1
metadata:
name: service-y
namespace: namespace-a
spec:
type: ExternalName
externalName: service-y.namespace-b.svc.cluster.local
ports:
- port: 80
</code></pre> | {
"question_id": 37221483,
"question_date": "2016-05-14T01:22:28.160Z",
"question_score": 222,
"tags": "kubernetes",
"answer_id": 44329470,
"answer_date": "2017-06-02T12:53:02.050Z",
"answer_score": 424
} |
Please answer the following Stack Overflow question:
Title: Best data type for storing currency values in a MySQL database
<p>What is the best SQL data type for currency values? I'm using MySQL but would prefer a database independent type.</p> | <p>Something like <code>Decimal(19,4)</code> usually works pretty well in most cases. You can adjust the scale and precision to fit the needs of the numbers you need to store. Even in SQL Server, I tend not to use "<code>money</code>" as it's non-standard.</p> | {
"question_id": 628637,
"question_date": "2009-03-10T01:36:22.530Z",
"question_score": 222,
"tags": "mysql|sql|sqldatatypes",
"answer_id": 628639,
"answer_date": "2009-03-10T01:38:56.953Z",
"answer_score": 239
} |
Please answer the following Stack Overflow question:
Title: How do I get the "id" after INSERT into MySQL database with Python?
<p>I execute an INSERT INTO statement</p>
<pre><code>cursor.execute("INSERT INTO mytable(height) VALUES(%s)",(height))
</code></pre>
<p>and I want to get the primary key.</p>
<p>My table has 2 columns: </p>
<pre><code>id primary, auto increment
height this is the other column.
</code></pre>
<p>How do I get the "id", after I just inserted this? </p> | <p>Use <code>cursor.lastrowid</code> to get the last row ID inserted on the cursor object, or <code>connection.insert_id()</code> to get the ID from the last insert on that connection.</p> | {
"question_id": 2548493,
"question_date": "2010-03-30T20:33:32.200Z",
"question_score": 222,
"tags": "python|mysql|database",
"answer_id": 2548531,
"answer_date": "2010-03-30T20:37:02.940Z",
"answer_score": 309
} |
Please answer the following Stack Overflow question:
Title: How to get the python.exe location programmatically?
<p>Basically I want to get a handle of the python interpreter so I can pass a script file to execute (from an external application).</p> | <p>This works in Linux & Windows:</p>
<p><strong>Python 3.x</strong></p>
<pre><code>>>> import sys
>>> print(sys.executable)
C:\path\to\python.exe
</code></pre>
<p><strong>Python 2.x</strong></p>
<pre><code>>>> import sys
>>> print sys.executable
/usr/bin/python
</code></pre> | {
"question_id": 749711,
"question_date": "2009-04-14T23:29:02.067Z",
"question_score": 222,
"tags": "python",
"answer_id": 749769,
"answer_date": "2009-04-14T23:46:57.093Z",
"answer_score": 366
} |
Please answer the following Stack Overflow question:
Title: Why would an Enum implement an Interface?
<p>I just found out that Java allows enums to implement an interface. What would be a good use case for that?</p> | <p>Enums don't just have to represent passive sets (e.g. colours). They can represent more complex objects with functionality, and so you're then likely to want to add further functionality to these - e.g. you may have interfaces such as <code>Printable</code>, <code>Reportable</code> etc. and components that support these.</p> | {
"question_id": 2709593,
"question_date": "2010-04-25T19:31:59.533Z",
"question_score": 222,
"tags": "java|enums",
"answer_id": 2709604,
"answer_date": "2010-04-25T19:34:38.160Z",
"answer_score": 151
} |
Please answer the following Stack Overflow question:
Title: How can I exclude $(this) from a jQuery selector?
<p>I have something like this:</p>
<pre><code><div class="content">
<a href="#">A</a>
</div>
<div class="content">
<a href="#">B</a>
</div>
<div class="content">
<a href="#">C</a>
</div>
</code></pre>
<p>When one of these links is clicked, I want to perform the .hide() function on the links that are not clicked. I understand jQuery has the :not selector, but I can't figure out how to use it in this case because <strong>it is necessary that I select the links using <code>$(".content a")</code></strong></p>
<p>I want to do something like</p>
<pre><code>$(".content a").click(function()
{
$(".content a:not(this)").hide("slow");
});
</code></pre>
<p>but I can't figure out how to use the :not selector properly in this case.</p> | <p>Try using the <a href="http://docs.jquery.com/Traversing/not" rel="noreferrer"><code>not()</code> <strong>method</strong></a> instead of the <a href="http://docs.jquery.com/Selectors/not" rel="noreferrer"><code>:not()</code> selector</a>.</p>
<pre><code>$(".content a").click(function() {
$(".content a").not(this).hide("slow");
});
</code></pre> | {
"question_id": 437958,
"question_date": "2009-01-13T04:30:16.263Z",
"question_score": 222,
"tags": "jquery|jquery-selectors|this",
"answer_id": 437979,
"answer_date": "2009-01-13T04:39:46.153Z",
"answer_score": 424
} |
Please answer the following Stack Overflow question:
Title: git clone from another directory
<p>I am trying to clone repo from another directory.</p>
<p>Lets say I have one repo in <code>C:/folder1</code> and <code>C:/folder2</code></p>
<p>I want to clone the work in <code>folder1</code> into <code>folder2</code>.</p>
<p>What would I type into the command prompt to do this? </p>
<p>It seems that often when cloning a URL is provided rather then a file path, however, at this moment I am just practicing and trying to get use to Git.</p> | <pre><code>cd /d c:\
git clone C:\folder1 folder2
</code></pre>
<p>From the <a href="https://www.kernel.org/pub/software/scm/git/docs/git-clone.html#URLS">documentation for <code>git clone</code></a>:</p>
<blockquote>
<p>For local repositories, also supported by git natively, the following syntaxes may be used:</p>
<pre><code>/path/to/repo.git/
file:///path/to/repo.git/
</code></pre>
<p>These two syntaxes are mostly equivalent, except the former implies --local option.</p>
</blockquote> | {
"question_id": 21045061,
"question_date": "2014-01-10T13:01:39.470Z",
"question_score": 222,
"tags": "git|git-clone",
"answer_id": 21045596,
"answer_date": "2014-01-10T13:29:03.293Z",
"answer_score": 238
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.