input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: Convert columns into rows with Pandas
<p>So my dataset has some information by location for n dates. The problem is each date is actually a different column header. For example the CSV looks like</p>
<pre><code>location name Jan-2010 Feb-2010 March-2010
A "test" 12 20 30
B "foo" 18 20 25
</code></pre>
<p>What I would like is for it to look like</p>
<pre><code>location name Date Value
A "test" Jan-2010 12
A "test" Feb-2010 20
A "test" March-2010 30
B "foo" Jan-2010 18
B "foo" Feb-2010 20
B "foo" March-2010 25
</code></pre>
<p>My problem is I don't know how many dates are in the column (though I know they will always start after name)</p> | <p><strong>UPDATE</strong><br>
From v0.20, <code>melt</code> is a first order function, you can now use</p>
<pre><code>df.melt(id_vars=["location", "name"],
var_name="Date",
value_name="Value")
location name Date Value
0 A "test" Jan-2010 12
1 B "foo" Jan-2010 18
2 A "test" Feb-2010 20
3 B "foo" Feb-2010 20
4 A "test" March-2010 30
5 B "foo" March-2010 25
</code></pre>
<hr>
<p><strong>OLD(ER) VERSIONS: <0.20</strong></p>
<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.melt.html" rel="noreferrer"><code>pd.melt</code></a> to get most of the way there, and then sort:</p>
<pre><code>>>> df
location name Jan-2010 Feb-2010 March-2010
0 A test 12 20 30
1 B foo 18 20 25
>>> df2 = pd.melt(df, id_vars=["location", "name"],
var_name="Date", value_name="Value")
>>> df2
location name Date Value
0 A test Jan-2010 12
1 B foo Jan-2010 18
2 A test Feb-2010 20
3 B foo Feb-2010 20
4 A test March-2010 30
5 B foo March-2010 25
>>> df2 = df2.sort(["location", "name"])
>>> df2
location name Date Value
0 A test Jan-2010 12
2 A test Feb-2010 20
4 A test March-2010 30
1 B foo Jan-2010 18
3 B foo Feb-2010 20
5 B foo March-2010 25
</code></pre>
<p>(Might want to throw in a <code>.reset_index(drop=True)</code>, just to keep the output clean.)</p>
<p><strong>Note</strong>: <code>pd.DataFrame.sort</code> <a href="https://stackoverflow.com/questions/44123874/dataframe-object-has-no-attribute-sort">has been deprecated</a> in favour of <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html" rel="noreferrer"><code>pd.DataFrame.sort_values</code></a>.</p> | {
"question_id": 28654047,
"question_date": "2015-02-22T03:08:28.463Z",
"question_score": 227,
"tags": "python|pandas",
"answer_id": 28654127,
"answer_date": "2015-02-22T03:21:24.837Z",
"answer_score": 356
} |
Please answer the following Stack Overflow question:
Title: How do I change the title of the "back" button on a Navigation Bar
<p>Currently the left bar button default value is the title of the view that loaded the current one, in other words the view to be shown when the button is pressed (back button).</p>
<p>I want to change the text shown on the button to something else.</p>
<p>I tried putting the following line of code in the view controller's viewDidLoad method but it doesn't seem to work.</p>
<pre><code>self.navigationItem.leftBarButtonItem.title = @"Log Out";
</code></pre>
<p>What should I do?</p>
<p>Thanks.</p> | <p>This should be placed in the method that calls the ViewController titled "NewTitle".
Right before the push or popViewController statement.</p>
<pre><code>UIBarButtonItem *newBackButton =
[[UIBarButtonItem alloc] initWithTitle:@"NewTitle"
style:UIBarButtonItemStyleBordered
target:nil
action:nil];
[[self navigationItem] setBackBarButtonItem:newBackButton];
[newBackButton release];
</code></pre> | {
"question_id": 1449339,
"question_date": "2009-09-19T19:41:40.903Z",
"question_score": 227,
"tags": "ios|objective-c|cocoa-touch|uinavigationbar|uinavigationitem",
"answer_id": 1449381,
"answer_date": "2009-09-19T19:58:37.203Z",
"answer_score": 343
} |
Please answer the following Stack Overflow question:
Title: Are "while(true)" loops so bad?
<p>I've been programming in Java for several years now, but I just recently returned to school to get a formal degree. I was quite surprised to learn that, on my last assignment, I lost points for using a loop like the one below.</p>
<pre><code>do{
//get some input.
//if the input meets my conditions, break;
//Otherwise ask again.
} while(true)
</code></pre>
<p>Now for my test I'm just scanning for some console input, but I was told that this kind of loop is discouraged because using <code>break</code> is akin to <code>goto</code>, we just don't do it.</p>
<p>I understand fully the pitfalls of <code>goto</code> and its Java cousin <code>break:label</code>, and I have the good sense not to use them. I also realize that a more complete program would provide some other means of escape, say for instance to just end the program, but that wasn't a reason my professor cited, so...</p>
<p>What's wrong with <code>do-while(true)</code>?</p> | <p>I wouldn't say it's <em>bad</em> - but equally I would normally at least look for an alternative.</p>
<p>In situations where it's the first thing I write, I almost always at least <em>try</em> to refactor it into something clearer. Sometimes it can't be helped (or the alternative is to have a <code>bool</code> variable which does nothing meaningful except indicate the end of the loop, less clearly than a <code>break</code> statement) but it's worth at least trying.</p>
<p>As an example of where it's clearer to use <code>break</code> than a flag, consider:</p>
<pre><code>while (true)
{
doStuffNeededAtStartOfLoop();
int input = getSomeInput();
if (testCondition(input))
{
break;
}
actOnInput(input);
}
</code></pre>
<p>Now let's force it to use a flag:</p>
<pre><code>boolean running = true;
while (running)
{
doStuffNeededAtStartOfLoop();
int input = getSomeInput();
if (testCondition(input))
{
running = false;
}
else
{
actOnInput(input);
}
}
</code></pre>
<p>I view the latter as more complicated to read: it's got an extra <code>else</code> block, the <code>actOnInput</code> is more indented, and if you're trying to work out what happens when <code>testCondition</code> returns <code>true</code>, you need to look carefully through the rest of the block to check that there isn't something <em>after</em> the <code>else</code> block which would occur whether <code>running</code> has been set to <code>false</code> or not.</p>
<p>The <code>break</code> statement communicates the intent more clearly, and lets the rest of the block get on with what it needs to do without worrying about earlier conditions.</p>
<p>Note that this is exactly the same sort of argument that people have about multiple return statements in a method. For example, if I can work out the result of a method within the first few lines (e.g. because some input is null, or empty, or zero) I find it clearer to return that answer directly than to have a variable to store the result, then a whole block of other code, and <em>finally</em> a <code>return</code> statement.</p> | {
"question_id": 6850380,
"question_date": "2011-07-27T19:52:27.793Z",
"question_score": 227,
"tags": "java|while-loop|do-while",
"answer_id": 6850411,
"answer_date": "2011-07-27T19:55:11.807Z",
"answer_score": 226
} |
Please answer the following Stack Overflow question:
Title: How do you print in a Go test using the "testing" package?
<p>I'm running a test in Go with a statement to print something (i.e. for debugging of tests) but it's not printing anything.</p>
<pre><code>func TestPrintSomething(t *testing.T) {
fmt.Println("Say hi")
}
</code></pre>
<p>When I run go test on this file, this is the output:</p>
<pre><code>ok command-line-arguments 0.004s
</code></pre>
<p>The only way to really get it to print, as far as I know, is to print it via t.Error(), like so: </p>
<pre><code>func TestPrintSomethingAgain(t *testing.T) {
t.Error("Say hi")
}
</code></pre>
<p>Which outputs this:</p>
<pre><code>Say hi
--- FAIL: TestPrintSomethingAgain (0.00 seconds)
foo_test.go:35: Say hi
FAIL
FAIL command-line-arguments 0.003s
gom: exit status 1
</code></pre>
<p>I've Googled and looked through the manual but didn't find anything.</p> | <p>The structs <a href="http://golang.org/pkg/testing/#T" rel="noreferrer"><code>testing.T</code></a> and <a href="http://golang.org/pkg/testing/#B" rel="noreferrer"><code>testing.B</code></a> both have a <a href="http://golang.org/pkg/testing/#B.Log" rel="noreferrer"><code>.Log</code></a> and <a href="http://golang.org/pkg/testing/#B.Logf" rel="noreferrer"><code>.Logf</code></a> method that sound to be what you are looking for. <a href="http://golang.org/pkg/testing/#B.Log" rel="noreferrer"><code>.Log</code></a> and <a href="http://golang.org/pkg/testing/#B.Logf" rel="noreferrer"><code>.Logf</code></a> are similar to <a href="http://golang.org/pkg/fmt/#Print" rel="noreferrer"><code>fmt.Print</code></a> and <a href="http://golang.org/pkg/fmt/#Printf" rel="noreferrer"><code>fmt.Printf</code></a> respectively.</p>
<p>See more details here: <a href="http://golang.org/pkg/testing/#pkg-index" rel="noreferrer">http://golang.org/pkg/testing/#pkg-index</a></p>
<p><code>fmt.X</code> print statements <strong>do</strong> work inside tests, but you will find their output is probably not on screen where you expect to find it and, hence, why you should use the logging methods in <code>testing</code>.</p>
<p>If, as in your case, you want to see the logs for tests that are not failing, you have to provide <code>go test</code> the <code>-v</code> flag (v for verbosity). More details on testing flags can be found here: <a href="https://golang.org/cmd/go/#hdr-Testing_flags" rel="noreferrer">https://golang.org/cmd/go/#hdr-Testing_flags</a></p> | {
"question_id": 23205419,
"question_date": "2014-04-21T20:27:09.057Z",
"question_score": 227,
"tags": "testing|go",
"answer_id": 23205771,
"answer_date": "2014-04-21T20:50:23.450Z",
"answer_score": 239
} |
Please answer the following Stack Overflow question:
Title: @property retain, assign, copy, nonatomic in Objective-C
<p>As someone that's new to Objective-C can someone give me an overview of the retain, assign, copy and any others I'm missing, that follow the @property directive? What are they doing and why would I want to use one over another?</p> | <p>The article linked to by MrMage is no longer working. So, here is what I've learned in my (very) short time coding in Objective-C:</p>
<p>nonatomic vs. atomic
- "atomic" is the default. Always use "nonatomic". I don't know why, but the book I read said there is "rarely a reason" to use "atomic". (BTW: The book I read is the BNR "iOS Programming" book.)</p>
<p>readwrite vs. readonly
- "readwrite" is the default. When you @synthesize, both a getter and a setter will be created for you. If you use "readonly", no setter will be created. Use it for a value you don't want to ever change after the instantiation of the object.</p>
<p>retain vs. copy vs. assign</p>
<ul>
<li>"assign" is the default. In the setter that is created by @synthesize, the value will simply be assigned to the attribute. My understanding is that "assign" should be used for non-pointer attributes.</li>
<li>"retain" is needed when the attribute is a pointer to an object. The setter generated by @synthesize will retain (aka add a retain count) the object. You will need to release the object when you are finished with it.</li>
<li>"copy" is needed when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.</li>
</ul> | {
"question_id": 2255861,
"question_date": "2010-02-12T23:51:26.393Z",
"question_score": 227,
"tags": "ios|objective-c|iphone|memory-management",
"answer_id": 7855536,
"answer_date": "2011-10-21T21:34:17.677Z",
"answer_score": 284
} |
Please answer the following Stack Overflow question:
Title: How can I check the version before installing a package using 'apt-get'?
<p>I'm thinking to install <em>hylafax+</em> version 5.5.4 which was released last month on my <a href="http://en.wikipedia.org/wiki/Debian" rel="nofollow noreferrer">Debian</a> PC.</p>
<p>I checked <code>dpkg -l | grep "hylafax"</code> and found out that the current version is 5.5.3. Then I checked <code>apt-cache search hylafax</code> and saw the packages are available, but I can't see any version number.</p>
<p>How can I find the version of packages available in the <code>apt-get</code>?</p> | <p>OK, I found it.</p>
<p><code>apt-cache policy <package name></code> will show the version details.</p>
<p>It also shows which version is currently installed and which versions are available to install.</p>
<p>For example, <code>apt-cache policy hylafax+</code></p> | {
"question_id": 18885820,
"question_date": "2013-09-19T03:40:29.037Z",
"question_score": 227,
"tags": "debian|version|apt|apt-get|dpkg",
"answer_id": 18888235,
"answer_date": "2013-09-19T07:05:26.410Z",
"answer_score": 383
} |
Please answer the following Stack Overflow question:
Title: Composer: how can I install another dependency without updating old ones?
<p>I have a project with a few dependencies and I'd like to install another one, but I'd like to keep the others the way they are. So I've edited the <code>composer.json</code>, but if I run <code>composer install</code>, I get the following output:</p>
<pre><code>Installing dependencies from lock file
Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. Run update to update them.
Your requirements could not be resolved to an installable set of packages.
Problem 1
- laravel/framework dev-master requires ext-mcrypt * -> the requested PHP extension mcrypt is missing from your system.
- laravel/framework dev-master requires ext-mcrypt * -> the requested PHP extension mcrypt is missing from your system.
- Installation request for laravel/framework dev-master -> satisfiable by laravel/framework dev-master.
</code></pre>
<p>First of all, I do have mcrypt installed, so I don't know why it's complaining about that there.</p>
<p>So, how can I install this new dependency?</p>
<p><strong>My composer.json:</strong></p>
<pre><code>{
"require": {
"opauth/opauth": "*",
"opauth/facebook": "*",
"opauth/google": "*",
"opauth/twitter": "*",
"imagine/Imagine": "dev-develop",
"laravel/framework": "4.*",
"loic-sharma/profiler": "dev-master"
},
"autoload": {
"classmap": [
"app/libraries",
"app/commands",
"app/controllers",
"app/models",
"app/database/migrations",
"app/tests/TestCase.php"
]
},
"minimum-stability": "dev"
}
</code></pre> | <p>To install a new package and only that, you have two options:</p>
<ol>
<li><p>Using the <a href="https://getcomposer.org/doc/03-cli.md#require" rel="noreferrer"><code>require</code></a> command, just run:</p>
<pre><code>composer require new/package
</code></pre>
<p>Composer will guess the best version constraint to use, install the package, and add it to <code>composer.lock</code>.</p>
<p>You can also specify an explicit version constraint by running:</p>
<pre><code>composer require new/package ~2.5
</code></pre></li>
</ol>
<p><em>–OR–</em></p>
<ol start="2">
<li><p>Using the <a href="https://getcomposer.org/doc/03-cli.md#update" rel="noreferrer"><code>update</code></a> command, add the new package manually to <code>composer.json</code>, then run:</p>
<pre><code>composer update new/package
</code></pre></li>
</ol>
<p>If Composer complains, stating "Your requirements could not be resolved to an installable set of packages.", you can resolve this by passing the flag <code>--with-dependencies</code>. This will whitelist all dependencies of the package you are trying to install/update (but none of your other dependencies).</p>
<p>Regarding the question asker's issues with Laravel and mcrypt: check that it's properly enabled in your CLI php.ini. If <code>php -m</code> doesn't list mcrypt then it's missing.</p>
<p><strong><em>Important:</strong> Don't forget to specify <code>new/package</code> when using <code>composer update</code>! Omitting that argument will cause all dependencies, as well as <code>composer.lock</code>, to be updated.</em></p> | {
"question_id": 15212381,
"question_date": "2013-03-04T22:29:22.817Z",
"question_score": 227,
"tags": "composer-php",
"answer_id": 15219640,
"answer_date": "2013-03-05T09:03:34.950Z",
"answer_score": 336
} |
Please answer the following Stack Overflow question:
Title: Showing the same file in both columns of a Sublime Text window
<p>When I have 2 columns set in a Sublime Text window, can I display the same file in both columns?</p> | <p><strong>EDIT</strong></p>
<p>With the release of Sublime Text 4, there is now a feature called Split View that you can access a couple different ways. Via the menu system, you can simply use <strong><code>File -> Split View</code></strong>. You can also right-click on a tab and select <strong><code>Split View</code></strong> from the context menu. It automatically opens a new pane with a new view of the file currently selected.</p>
<p>You should be aware that unlike the new pane described below, the new Split View pane is temporary. This means that if you click on another tab or open a new file, the split view disappears. However, the new view into the file remains open as a separate tab, so to reopen the pane (or compare any open file(s)), select the tab you want on the left, then <kbd>Ctrl</kbd>-click (<kbd>Command ⌘</kbd>-click on macOS) on the other tab(s) you want to compare, and each one will be displayed in its own pane.</p>
<p>If want to have two (or more) "permanent" panes that will stay open regardless of which tab you click on, just follow the directions below.</p>
<hr />
<p><strong>Original Answer</strong></p>
<p><sup>(For Sublime Text 3)</sup></p>
<p>Yes, you can. When a file is open, click on <strong><code>File -> New View Into File</code></strong>. You can then drag the new tab to the other pane and view the file twice.</p>
<p>There are several ways to create a new pane. As described in other answers, on Linux and Windows, you can use <kbd>Alt</kbd><kbd>Shift</kbd><kbd>2</kbd> (<kbd>Option ⌥</kbd><kbd>Command ⌘</kbd><kbd>2</kbd> on OS X), which corresponds to <strong><code>View → Layout → Columns: 2</code></strong> in the menu. If you have the excellent <a href="https://packagecontrol.io/packages/Origami" rel="noreferrer"><code>Origami</code></a> plugin installed, you can use <strong><code>View → Origami → Pane → Create → Right</code></strong>, or the <kbd>Ctrl</kbd><kbd>K</kbd>, <kbd>Ctrl</kbd><kbd>→</kbd> chord on Windows/Linux (replace <kbd>Ctrl</kbd> with <kbd>⌘</kbd> on OS X).</p> | {
"question_id": 23957730,
"question_date": "2014-05-30T15:05:24.933Z",
"question_score": 227,
"tags": "sublimetext3|sublimetext2|sublimetext|sublimetext4",
"answer_id": 23964831,
"answer_date": "2014-05-30T23:33:48.300Z",
"answer_score": 342
} |
Please answer the following Stack Overflow question:
Title: How to choose an AWS profile when using boto3 to connect to CloudFront
<p>I am using the Boto 3 python library, and want to connect to AWS CloudFront.
I need to specify the correct AWS Profile (AWS Credentials), but looking at the official documentation, I see no way to specify it.</p>
<p>I am initializing the client using the code:
<code>client = boto3.client('cloudfront')</code></p>
<p>However, this results in it using the default profile to connect.
I couldn't find a method where I can specify which profile to use.</p> | <p>I think the docs aren't wonderful at exposing how to do this. It has been a supported feature for some time, however, and there are some details in this <a href="https://github.com/boto/boto3/pull/69" rel="noreferrer">pull request</a>.</p>
<p>So there are three different ways to do this:</p>
<p>Option A) Create a new session with the profile</p>
<pre><code> dev = boto3.session.Session(profile_name='dev')
</code></pre>
<p>Option B) Change the profile of the default session in code</p>
<pre><code> boto3.setup_default_session(profile_name='dev')
</code></pre>
<p>Option C) Change the profile of the default session with an environment variable</p>
<pre><code> $ AWS_PROFILE=dev ipython
>>> import boto3
>>> s3dev = boto3.resource('s3')
</code></pre> | {
"question_id": 33378422,
"question_date": "2015-10-27T21:02:50.390Z",
"question_score": 227,
"tags": "python|amazon-web-services|boto3|amazon-iam|amazon-cloudfront",
"answer_id": 33395432,
"answer_date": "2015-10-28T15:41:31.690Z",
"answer_score": 390
} |
Please answer the following Stack Overflow question:
Title: Is there any way to do HTTP PUT in python
<p>I need to upload some data to a server using HTTP <code>PUT</code> in python. From my brief reading of the urllib2 docs, it only does HTTP <code>POST</code>. Is there any way to do an HTTP <code>PUT</code> in python?</p> | <p>I've used a variety of python HTTP libs in the past, and I've settled on <a href="https://requests.readthedocs.io/" rel="nofollow noreferrer">requests</a> as my favourite. Existing libs had pretty useable interfaces, but code can end up being a few lines too long for simple operations. A basic PUT in requests looks like:</p>
<pre><code>payload = {'username': 'bob', 'email': '[email protected]'}
>>> r = requests.put("http://somedomain.org/endpoint", data=payload)
</code></pre>
<p>You can then check the response status code with:</p>
<pre><code>r.status_code
</code></pre>
<p>or the response with:</p>
<pre><code>r.content
</code></pre>
<p>Requests has a lot synactic sugar and shortcuts that'll make your life easier.</p> | {
"question_id": 111945,
"question_date": "2008-09-21T20:11:05.753Z",
"question_score": 227,
"tags": "python|http|put",
"answer_id": 8259648,
"answer_date": "2011-11-24T15:54:13.543Z",
"answer_score": 321
} |
Please answer the following Stack Overflow question:
Title: Rails.env vs RAILS_ENV
<p>I see both in examples when checking what env one is running in. What's preferred? Are they, for all intents and purposes equal?</p> | <p><a href="http://api.rubyonrails.org/classes/Rails.html#method-c-env" rel="noreferrer">According to the docs</a>, <code>#Rails.env</code> wraps <code>RAILS_ENV</code>:</p>
<pre><code> # File vendor/rails/railties/lib/initializer.rb, line 55
def env
@_env ||= ActiveSupport::StringInquirer.new(RAILS_ENV)
end
</code></pre>
<p>But, look at specifically <em>how</em> it's wrapped, using <code>ActiveSupport::StringInquirer</code>:</p>
<blockquote>
<p>Wrapping a string in this class gives
you a prettier way to test for
equality. The value returned by
Rails.env is wrapped in a
StringInquirer object so instead of
calling this:</p>
<pre><code>Rails.env == "production"
</code></pre>
<p>you can call this:</p>
<pre><code>Rails.env.production?
</code></pre>
</blockquote>
<p>So they aren't <em>exactly</em> equivalent, but they're fairly close. I haven't used Rails much yet, but I'd say <code>#Rails.env</code> is certainly the more visually attractive option due to using <code>StringInquirer</code>.</p> | {
"question_id": 2715035,
"question_date": "2010-04-26T16:18:49.293Z",
"question_score": 227,
"tags": "ruby-on-rails",
"answer_id": 2715076,
"answer_date": "2010-04-26T16:26:37.510Z",
"answer_score": 383
} |
Please answer the following Stack Overflow question:
Title: Is there a decorator to simply cache function return values?
<p>Consider the following:</p>
<pre><code>@property
def name(self):
if not hasattr(self, '_name'):
# expensive calculation
self._name = 1 + 1
return self._name
</code></pre>
<p>I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;)</p>
<p>PS the real calculation doesn't depend on mutable values</p> | <p><strong>Python 3.8 <code>functools.cached_property</code> decorator</strong></p>
<p><a href="https://docs.python.org/dev/library/functools.html#functools.cached_property" rel="noreferrer">https://docs.python.org/dev/library/functools.html#functools.cached_property</a></p>
<p><code>cached_property</code> from Werkzeug was mentioned at: <a href="https://stackoverflow.com/a/5295190/895245">https://stackoverflow.com/a/5295190/895245</a> but a supposedly derived version will be merged into 3.8, which is awesome.</p>
<p>This decorator can be seen as caching <code>@property</code>, or as a cleaner <code>@functools.lru_cache</code> for when you don't have any arguments.</p>
<p>The docs say:</p>
<blockquote>
<pre><code>@functools.cached_property(func)
</code></pre>
<p>Transform a method of a class into a property whose value is computed once and then cached as a normal attribute for the life of the instance. Similar to property(), with the addition of caching. Useful for expensive computed properties of instances that are otherwise effectively immutable.</p>
<p>Example:</p>
<pre><code>class DataSet:
def __init__(self, sequence_of_numbers):
self._data = sequence_of_numbers
@cached_property
def stdev(self):
return statistics.stdev(self._data)
@cached_property
def variance(self):
return statistics.variance(self._data)
</code></pre>
<p>New in version 3.8.</p>
<p>Note This decorator requires that the <strong>dict</strong> attribute on each instance be a mutable mapping. This means it will not work with some types, such as metaclasses (since the <strong>dict</strong> attributes on type instances are read-only proxies for the class namespace), and those that specify <strong>slots</strong> without including <strong>dict</strong> as one of the defined slots (as such classes don’t provide a <strong>dict</strong> attribute at all).</p>
</blockquote> | {
"question_id": 815110,
"question_date": "2009-05-02T16:15:40.493Z",
"question_score": 227,
"tags": "python|caching|decorator|memoization",
"answer_id": 56097764,
"answer_date": "2019-05-12T09:15:51.190Z",
"answer_score": 45
} |
Please answer the following Stack Overflow question:
Title: fatal: git-write-tree: error building trees
<p>I did a <code>git pull</code> from a shared git repository, but something went really wrong, after I tried a <code>git revert</code>. Here is the situation now:</p>
<pre><code>$ git stash
Source/MediaStorageAndFileFormat/gdcmImageCodec.cxx: needs merge
Source/MediaStorageAndFileFormat/gdcmJPEGLSCodec.cxx: needs merge
Source/MediaStorageAndFileFormat/gdcmPNMCodec.cxx: needs merge
Testing/Source/DataStructureAndEncodingDefinition/Cxx/TestDS.cxx: needs merge
Utilities/socketxx/socket++/sockstream.cpp: needs merge
Source/MediaStorageAndFileFormat/gdcmImageCodec.cxx: needs merge
Source/MediaStorageAndFileFormat/gdcmJPEGLSCodec.cxx: needs merge
Source/MediaStorageAndFileFormat/gdcmPNMCodec.cxx: needs merge
Testing/Source/DataStructureAndEncodingDefinition/Cxx/TestDS.cxx: needs merge
Utilities/socketxx/socket++/sockstream.cpp: needs merge
Source/MediaStorageAndFileFormat/gdcmImageCodec.cxx: unmerged (2aafac967c35fa4e77c3086b83a3c102939ad168)
Source/MediaStorageAndFileFormat/gdcmImageCodec.cxx: unmerged (78cc95e8bae85bf8345a7793676e878e83df167b)
Source/MediaStorageAndFileFormat/gdcmImageCodec.cxx: unmerged (2524db713fbde0d7ebd86bfe2afc4b4d7d48db33)
Source/MediaStorageAndFileFormat/gdcmJPEGLSCodec.cxx: unmerged (4bb4ba78973091eaa854b03c6ce24e8f4af9e7cc)
Source/MediaStorageAndFileFormat/gdcmJPEGLSCodec.cxx: unmerged (ad0982b8b8b4c4fef23e69bbb639ca6d0cd98dd8)
Source/MediaStorageAndFileFormat/gdcmJPEGLSCodec.cxx: unmerged (4868371b7218c6e007fb6c582ad4ab226167a80a)
Source/MediaStorageAndFileFormat/gdcmPNMCodec.cxx: unmerged (f7a1b386b5b13b8fa8b6a31ce1258d2d5e5b13c5)
Source/MediaStorageAndFileFormat/gdcmPNMCodec.cxx: unmerged (6ce299c416fbb3bb60e11ef1e54962ffd3449a4c)
Source/MediaStorageAndFileFormat/gdcmPNMCodec.cxx: unmerged (75c8043a60a56a1130a34cdbd91d130bc9343c1c)
Testing/Source/DataStructureAndEncodingDefinition/Cxx/TestDS.cxx: unmerged (79c2843f2649ea9c87fa57662dafd899a5fa39ee)
...
fatal: git-write-tree: error building trees
Cannot save the current index state
</code></pre>
<p>Is there a way to reset all that ?</p>
<p>Thanks</p> | <p>Use</p>
<pre class="lang-bash prettyprint-override"><code>git reset --mixed
</code></pre>
<p>instead of <code> git reset --hard</code>. You will not lose any changes.</p> | {
"question_id": 5483213,
"question_date": "2011-03-30T07:25:48.277Z",
"question_score": 227,
"tags": "git",
"answer_id": 16056225,
"answer_date": "2013-04-17T09:19:52.917Z",
"answer_score": 603
} |
Please answer the following Stack Overflow question:
Title: What are React controlled components and uncontrolled components?
<p>What are controlled components and uncontrolled components in ReactJS? How do they differ from each other?</p> | <p>This relates to stateful DOM components (form elements) and the React docs explain the difference:</p>
<ul>
<li>A <a href="https://facebook.github.io/react/docs/forms.html#controlled-components" rel="noreferrer">Controlled Component</a> is one that takes its current value through <code>props</code> and notifies changes through callbacks like <code>onChange</code>. A parent component "controls" it by handling the callback and managing its own state and passing the new values as props to the controlled component. You could also call this a "dumb component". </li>
<li>A <a href="https://facebook.github.io/react/docs/uncontrolled-components.html" rel="noreferrer">Uncontrolled Component</a> is one that stores its own state internally, and you query the DOM using a <code>ref</code> to find its current value when you need it. This is a bit more like traditional HTML.</li>
</ul>
<p>Most native React form components support both controlled and uncontrolled usage:</p>
<pre><code>// Controlled:
<input type="text" value={value} onChange={handleChange} />
// Uncontrolled:
<input type="text" defaultValue="foo" ref={inputRef} />
// Use `inputRef.current.value` to read the current value of <input>
</code></pre>
<p>In most (or all) cases <a href="https://goshakkk.name/controlled-vs-uncontrolled-inputs-react/#conclusion" rel="noreferrer">you should use controlled components</a>.</p> | {
"question_id": 42522515,
"question_date": "2017-03-01T03:15:04.520Z",
"question_score": 227,
"tags": "reactjs|react-component",
"answer_id": 42522792,
"answer_date": "2017-03-01T03:44:53.290Z",
"answer_score": 314
} |
Please answer the following Stack Overflow question:
Title: Is there a built-in way to loop through the properties of an object?
<p>Is there a Mustache / Handlebars way of looping through an <strong>object</strong> properties?</p>
<p>So with</p>
<pre><code>var o = {
bob : 'For sure',
roger: 'Unknown',
donkey: 'What an ass'
}
</code></pre>
<p>Can I then do something <em>in the template engine</em> that would be equivalent to</p>
<pre><code>for(var prop in o)
{
// with say, prop a variable in the template and value the property value
}
</code></pre>
<p>?</p> | <h2>Built-in support since Handlebars 1.0rc1</h2>
<p>Support for this functionality <a href="https://github.com/wycats/handlebars.js/blob/9589ab89492c23e1d201f61617ae2a3bf54a0afc/lib/handlebars/base.js#L80-L86" rel="noreferrer">has been added</a> to Handlebars.js, so there is no more need for external helpers.</p>
<h2>How to use it</h2>
<p>For arrays:</p>
<pre><code>{{#each myArray}}
Index: {{@index}} Value = {{this}}
{{/each}}
</code></pre>
<p>For objects:</p>
<pre><code>{{#each myObject}}
Key: {{@key}} Value = {{this}}
{{/each}}
</code></pre>
<p>Note that only properties passing the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty" rel="noreferrer"><code>hasOwnProperty</code></a> test will be enumerated.</p> | {
"question_id": 9058774,
"question_date": "2012-01-30T02:42:53.677Z",
"question_score": 227,
"tags": "javascript|iteration|handlebars.js|mustache",
"answer_id": 17516837,
"answer_date": "2013-07-07T22:02:39.257Z",
"answer_score": 477
} |
Please answer the following Stack Overflow question:
Title: Can I get the name of the current controller in the view?
<p>Is there a way to figure out what the current controller is from within the view?</p>
<p>For an example of why I would want to know this: if several controllers share the same layout, I may have a part in the layout ERB file where I want to highlight the current page's menu item based on the controller.</p>
<p>Maybe that is a bad approach. If so, what is the more preferred way to do this?</p>
<p>I'm interested to know about getting the name of the current controller either way, though.</p>
<p>(Obviously I could put something like <code>@controller_name = 'users'</code> in each controller; but that seems like the sort of thing Rails would've already done behind the scenes. So I'm just wondering if there's a built-in way.)</p> | <p><code>controller_name</code> holds the name of the controller used to serve the current view.</p> | {
"question_id": 3757491,
"question_date": "2010-09-21T05:19:48.157Z",
"question_score": 227,
"tags": "ruby-on-rails|model-view-controller|view|controller",
"answer_id": 3757524,
"answer_date": "2010-09-21T05:27:34.313Z",
"answer_score": 282
} |
Please answer the following Stack Overflow question:
Title: Linq-to-Entities Join vs GroupJoin
<p>Can someone please explain what a <code>GroupJoin()</code> is?</p>
<p>How is it different from a regular <code>Join()</code>?</p>
<p>Is it commonly used?</p>
<p>Is it only for method syntax? What about query syntax? (A c# code example would be nice)</p> | <h2>Behaviour</h2>
<p>Suppose you have two lists:</p>
<pre><code>Id Value
1 A
2 B
3 C
Id ChildValue
1 a1
1 a2
1 a3
2 b1
2 b2
</code></pre>
<p>When you <strong><code>Join</code></strong> the two lists on the <code>Id</code> field the result will be:</p>
<pre><code>Value ChildValue
A a1
A a2
A a3
B b1
B b2
</code></pre>
<p>When you <strong><code>GroupJoin</code></strong> the two lists on the <code>Id</code> field the result will be:</p>
<pre><code>Value ChildValues
A [a1, a2, a3]
B [b1, b2]
C []
</code></pre>
<p>So <code>Join</code> produces a flat (tabular) result of parent and child values.<br />
<code>GroupJoin</code> produces a list of entries in the first list, each with a group of joined entries in the second list.</p>
<p>That's why <code>Join</code> is the equivalent of <code>INNER JOIN</code> in SQL: there are no entries for <code>C</code>. While <code>GroupJoin</code> is the equivalent of <code>OUTER JOIN</code>: <code>C</code> is in the result set, but with an empty list of related entries (in an SQL result set there would be a row <code>C - null</code>).</p>
<h2>Syntax</h2>
<p>So let the two lists be <code>IEnumerable<Parent></code> and <code>IEnumerable<Child></code> respectively. (In case of Linq to Entities: <code>IQueryable<T></code>).</p>
<p><strong><code>Join</code></strong> syntax would be</p>
<pre class="lang-cs prettyprint-override"><code>from p in Parent
join c in Child on p.Id equals c.Id
select new { p.Value, c.ChildValue }
</code></pre>
<p>returning an <code>IEnumerable<X></code> where X is an anonymous type with two properties, <code>Value</code> and <code>ChildValue</code>. This query syntax uses the <a href="http://msdn.microsoft.com/en-us/library/bb534675.aspx" rel="noreferrer"><code>Join</code></a> method under the hood.</p>
<p><strong><code>GroupJoin</code></strong> syntax would be</p>
<pre class="lang-cs prettyprint-override"><code>from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }
</code></pre>
<p>returning an <code>IEnumerable<Y></code> where Y is an anonymous type consisting of one property of type <code>Parent</code> and a property of type <code>IEnumerable<Child></code>. This query syntax uses the <a href="http://msdn.microsoft.com/en-us/library/bb534297.aspx" rel="noreferrer"><code>GroupJoin</code></a> method under the hood.</p>
<p>We could just do <code>select g</code> in the latter query, which would select an <code>IEnumerable<IEnumerable<Child>></code>, say a list of lists. In many cases the select with the parent included is more useful.</p>
<h2>Some use cases</h2>
<h3>1. Producing a flat outer join.</h3>
<p>As said, the statement ...</p>
<pre class="lang-cs prettyprint-override"><code>from p in Parent
join c in Child on p.Id equals c.Id into g
select new { Parent = p, Children = g }
</code></pre>
<p>... produces a list of parents with child groups. This can be turned into a flat list of parent-child pairs by two small additions:</p>
<pre class="lang-cs prettyprint-override"><code>from p in parents
join c in children on p.Id equals c.Id into g // <= into
from c in g.DefaultIfEmpty() // <= flattens the groups
select new { Parent = p.Value, Child = c?.ChildValue }
</code></pre>
<p>The result is similar to</p>
<pre class="lang-cs prettyprint-override"><code>Value Child
A a1
A a2
A a3
B b1
B b2
C (null)
</code></pre>
<p>Note that the <em>range variable</em> <code>c</code> is reused in the above statement. Doing this, any <code>join</code> statement can simply be converted to an <code>outer join</code> by adding the equivalent of <code>into g from c in g.DefaultIfEmpty()</code> to an existing <code>join</code> statement.</p>
<p>This is where query (or comprehensive) syntax shines. Method (or fluent) syntax shows what really happens, but it's hard to write:</p>
<pre class="lang-cs prettyprint-override"><code>parents.GroupJoin(children, p => p.Id, c => c.Id, (p, c) => new { p, c })
.SelectMany(x => x.c.DefaultIfEmpty(), (x,c) => new { x.p.Value, c?.ChildValue } )
</code></pre>
<p>So a flat <code>outer join</code> in LINQ is a <code>GroupJoin</code>, flattened by <code>SelectMany</code>.</p>
<h3>2. Preserving order</h3>
<p>Suppose the list of parents is a bit longer. Some UI produces a list of selected parents as <code>Id</code> values in a fixed order. Let's use:</p>
<pre class="lang-cs prettyprint-override"><code>var ids = new[] { 3,7,2,4 };
</code></pre>
<p>Now the selected parents must be filtered from the parents list in this exact order.</p>
<p>If we do ...</p>
<pre class="lang-cs prettyprint-override"><code>var result = parents.Where(p => ids.Contains(p.Id));
</code></pre>
<p>... the order of <code>parents</code> will determine the result. If the parents are ordered by <code>Id</code>, the result will be parents 2, 3, 4, 7. Not good. However, we can also use <code>join</code> to filter the list. And by using <code>ids</code> as first list, the order will be preserved:</p>
<pre class="lang-cs prettyprint-override"><code>from id in ids
join p in parents on id equals p.Id
select p
</code></pre>
<p>The result is parents 3, 7, 2, 4.</p> | {
"question_id": 15595289,
"question_date": "2013-03-24T04:49:24.443Z",
"question_score": 227,
"tags": "c#|linq|linq-to-entities",
"answer_id": 15599143,
"answer_date": "2013-03-24T13:40:25.783Z",
"answer_score": 447
} |
Please answer the following Stack Overflow question:
Title: What is the ellipsis (...) for in this method signature?
<p>In the <a href="http://code.google.com/appengine/docs/java/javadoc/com/google/appengine/api/xmpp/MessageBuilder.html" rel="noreferrer">App Engine docs</a>, what is the ellipsis (<code>JID...</code>) for in this method signature?</p>
<pre><code>public MessageBuilder withRecipientJids(JID... recipientJids)
</code></pre>
<p>What's the function of those three dots?</p> | <p>Those are Java varargs. They let you pass any number of objects of a specific type (in this case they are of type JID).</p>
<p>In your example, the following function calls would be valid:</p>
<pre><code>MessageBuilder msgBuilder; //There should probably be a call to a constructor here ;)
MessageBuilder msgBuilder2;
msgBuilder.withRecipientJids(jid1, jid2);
msgBuilder2.withRecipientJids(jid1, jid2, jid78_a, someOtherJid);
</code></pre>
<p>See more here:
<a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html" rel="noreferrer">http://java.sun.com/j2se/1.5.0/docs/guide/language/varargs.html</a></p> | {
"question_id": 2367398,
"question_date": "2010-03-02T22:35:56.400Z",
"question_score": 227,
"tags": "java|ellipsis",
"answer_id": 2367412,
"answer_date": "2010-03-02T22:38:13.043Z",
"answer_score": 226
} |
Please answer the following Stack Overflow question:
Title: Is there a way to remove the separator line from a UITableView?
<p>I'm looking for a way to completely remove the separator line in a UITableView when in the plain mode. This is done automatically in grouped, but this also changes the dimensions of the table in a way that is hard to measure. I have set the seperator line color to colorClear. But this does not completely solve the problem.</p>
<p>As I am trying to draw a custom background view in the cells, and I want the cells to be seamless, the one pixel line that remains in-between is causing me problems. Is there a more elegant workaround then using a grouped view and then stretching it?</p> | <p>You can do this with the <code>UITableView</code> property <code>separatorStyle</code>. Make sure the property is set to <code>UITableViewCellSeparatorStyleNone</code> and you're set.</p>
<p>Objective-C</p>
<pre><code>self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
</code></pre>
<p>In Swift (prior to 3)</p>
<pre><code>tableView.separatorStyle = .None
</code></pre>
<p>In Swift 3/4/5</p>
<pre><code>tableView.separatorStyle = .none
</code></pre> | {
"question_id": 925115,
"question_date": "2009-05-29T09:15:07.547Z",
"question_score": 227,
"tags": "objective-c|cocoa-touch|uikit",
"answer_id": 925202,
"answer_date": "2009-05-29T09:42:40.847Z",
"answer_score": 455
} |
Please answer the following Stack Overflow question:
Title: Difference between @Mock, @MockBean and Mockito.mock()
<p>When creating tests and mocking dependencies, what is the difference between these three approaches?</p>
<ol>
<li><p>@MockBean:</p>
<pre><code>@MockBean
MyService myservice;
</code></pre></li>
<li><p>@Mock:</p>
<pre><code>@Mock
MyService myservice;
</code></pre></li>
<li><p>Mockito.mock()</p>
<pre><code>MyService myservice = Mockito.mock(MyService.class);
</code></pre></li>
</ol> | <p><strong>Plain Mockito library</strong> </p>
<pre><code>import org.mockito.Mock;
...
@Mock
MyService myservice;
</code></pre>
<p>and </p>
<pre><code>import org.mockito.Mockito;
...
MyService myservice = Mockito.mock(MyService.class);
</code></pre>
<p>come from the Mockito library and are functionally equivalent. <br>
They allow to mock a class or an interface and to record and verify behaviors on it.<br></p>
<p>The way using annotation is shorter, so preferable and often preferred.<br></p>
<hr>
<p>Note that to enable Mockito annotations during test executions, the
<code>MockitoAnnotations.initMocks(this)</code> static method has to be called.<br>
To avoid side effect between tests, it is advised to do it before each test execution :</p>
<pre><code>@Before
public void initMocks() {
MockitoAnnotations.initMocks(this);
}
</code></pre>
<p>Another way to enable Mockito annotations is annotating the test class with <code>@RunWith</code> by specifying the <code>MockitoJUnitRunner</code> that does this task and also other useful things :</p>
<pre><code>@RunWith(org.mockito.runners.MockitoJUnitRunner.class)
public MyClassTest{...}
</code></pre>
<hr>
<p><strong>Spring Boot library wrapping Mockito library</strong> </p>
<p>This is indeed a <a href="https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/MockBean.html" rel="noreferrer">Spring Boot class</a>:</p>
<pre><code>import org.springframework.boot.test.mock.mockito.MockBean;
...
@MockBean
MyService myservice;
</code></pre>
<p>The class is included in the <code>spring-boot-test</code> library.<br></p>
<p>It allows to add Mockito mocks in a Spring <code>ApplicationContext</code>.<br>
If a bean, compatible with the declared class exists in the context, it <strong>replaces</strong> it by the mock.<br>
If it is not the case, it <strong>adds</strong> the mock in the context as a bean.</p>
<p>Javadoc reference :</p>
<blockquote>
<p>Annotation that can be used to add mocks to a Spring
ApplicationContext.</p>
<p>...</p>
<p>If any existing single bean of the same type defined in the context
will be replaced by the mock, if no existing bean is defined a new one
will be added.</p>
</blockquote>
<hr>
<p><strong>When use classic/plain Mockito and when use <code>@MockBean</code> from Spring Boot ?<br></strong></p>
<p>Unit tests are designed to test a component in isolation from other components and unit tests have also a requirement : being as fast as possible in terms of execution time as these tests may be executed each day dozen times on the developer machines.<br></p>
<p>Consequently, here is a simple guideline :<br></p>
<p>As you write a test that doesn't need any dependencies from the Spring Boot container, the classic/plain Mockito is the way to follow : it is fast and favors the isolation of the tested component.<br>
If your test needs to rely on the Spring Boot container <strong>and</strong> you want also to add or mock one of the container beans : <code>@MockBean</code> from Spring Boot is the way.</p>
<hr>
<p><strong>Typical usage of Spring Boot <code>@MockBean</code></strong> </p>
<p>As we write a test class annotated with <code>@WebMvcTest</code> (web test slice). </p>
<p><a href="https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-testing-autoconfigured-mvc-tests" rel="noreferrer">The Spring Boot documentation</a> summarizes that very well :</p>
<blockquote>
<p>Often <code>@WebMvcTest</code> will be limited to a single controller and used in
combination with <code>@MockBean</code> to provide mock implementations for
required collaborators.</p>
</blockquote>
<p>Here is an example :</p>
<pre><code>import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringRunner.class)
@WebMvcTest(FooController.class)
public class FooControllerTest {
@Autowired
private MockMvc mvc;
@MockBean
private FooService fooServiceMock;
@Test
public void testExample() throws Exception {
Foo mockedFoo = new Foo("one", "two");
Mockito.when(fooServiceMock.get(1))
.thenReturn(mockedFoo);
mvc.perform(get("foos/1")
.accept(MediaType.TEXT_PLAIN))
.andExpect(status().isOk())
.andExpect(content().string("one two"));
}
}
</code></pre> | {
"question_id": 44200720,
"question_date": "2017-05-26T11:41:12.840Z",
"question_score": 227,
"tags": "java|spring|spring-boot|junit|mockito",
"answer_id": 44200907,
"answer_date": "2017-05-26T11:50:19.777Z",
"answer_score": 290
} |
Please answer the following Stack Overflow question:
Title: Use cases for the 'setdefault' dict method
<p>The addition of <code>collections.defaultdict</code> in Python 2.5 greatly reduced the need for <code>dict</code>'s <code>setdefault</code> method. This question is for our collective education:</p>
<ol>
<li>What is <code>setdefault</code> still useful for, today in Python 2.6/2.7?</li>
<li>What popular use cases of <code>setdefault</code> were superseded with <code>collections.defaultdict</code>?</li>
</ol> | <p>You could say <code>defaultdict</code> is useful for settings defaults <em>before filling the dict</em> and <code>setdefault</code> is useful for setting defaults <em>while or after filling the dict</em>. </p>
<p>Probably the most common use case: Grouping items (in unsorted data, else use <code>itertools.groupby</code>)</p>
<pre><code># really verbose
new = {}
for (key, value) in data:
if key in new:
new[key].append( value )
else:
new[key] = [value]
# easy with setdefault
new = {}
for (key, value) in data:
group = new.setdefault(key, []) # key might exist already
group.append( value )
# even simpler with defaultdict
from collections import defaultdict
new = defaultdict(list)
for (key, value) in data:
new[key].append( value ) # all keys have a default already
</code></pre>
<p>Sometimes you want to make sure that specific keys exist after creating a dict. <code>defaultdict</code> doesn't work in this case, because it only creates keys on explicit access. Think you use something HTTP-ish with many headers -- some are optional, but you want defaults for them:</p>
<pre><code>headers = parse_headers( msg ) # parse the message, get a dict
# now add all the optional headers
for headername, defaultvalue in optional_headers:
headers.setdefault( headername, defaultvalue )
</code></pre> | {
"question_id": 3483520,
"question_date": "2010-08-14T13:32:58.453Z",
"question_score": 227,
"tags": "python|dictionary|setdefault",
"answer_id": 3483652,
"answer_date": "2010-08-14T14:05:51.163Z",
"answer_score": 245
} |
Please answer the following Stack Overflow question:
Title: Is it better in C++ to pass by value or pass by reference-to-const?
<p>Is it better in C++ to pass by value or pass by reference-to-const?</p>
<p>I am wondering which is better practice. I realize that pass by reference-to-const should provide for better performance in the program because you are not making a copy of the variable.</p> | <p>It used to be generally recommended best practice<sup>1</sup> to <strong>use pass by const ref for <em>all types</em>, except for builtin types (<code>char</code>, <code>int</code>, <code>double</code>, etc.), for iterators and for function objects</strong> (lambdas, classes deriving from <code>std::*_function</code>).</p>
<p>This was especially true before the existence of <em>move semantics</em>. The reason is simple: if you passed by value, a copy of the object had to be made and, except for very small objects, this is always more expensive than passing a reference.</p>
<p>With C++11, we have gained <a href="https://stackoverflow.com/q/3106110/1968"><em>move semantics</em></a>. In a nutshell, move semantics permit that, in some cases, an object can be passed “by value” without copying it. In particular, this is the case when the object that you are passing is an <a href="https://stackoverflow.com/q/3601602/1968"><em>rvalue</em></a>.</p>
<p>In itself, moving an object is still at least as expensive as passing by reference. However, in many cases a function will internally copy an object anyway — i.e. it will take <em>ownership</em> of the argument.<sup>2</sup></p>
<p>In these situations we have the following (simplified) trade-off:</p>
<ol>
<li>We can pass the object by reference, then copy internally.</li>
<li>We can pass the object by value.</li>
</ol>
<p>“Pass by value” still causes the object to be copied, unless the object is an rvalue. In the case of an rvalue, the object can be moved instead, so that the second case is suddenly no longer “copy, then move” but “move, then (potentially) move again”.</p>
<p>For large objects that implement proper move constructors (such as vectors, strings …), the second case is then <em>vastly</em> more efficient than the first. Therefore, it is recommended to <strong>use pass by value if the function takes ownership of the argument, and if the object type supports efficient moving</strong>.</p>
<hr>
<p>A historical note:</p>
<p>In fact, any modern compiler should be able to figure out when passing by value is expensive, and implicitly convert the call to use a const ref if possible.</p>
<p><em>In theory.</em> In practice, compilers can’t always change this without breaking the function’s binary interface. In some special cases (when the function is inlined) the copy will actually be elided if the compiler can figure out that the original object won’t be changed through the actions in the function.</p>
<p>But in general the compiler can’t determine this, and the advent of move semantics in C++ has made this optimisation much less relevant.</p>
<hr>
<p><sup>1</sup> E.g. in Scott Meyers, <em>Effective C++</em>.</p>
<p><sup>2</sup> This is especially often true for object constructors, which may take arguments and store them internally to be part of the constructed object’s state.</p> | {
"question_id": 270408,
"question_date": "2008-11-06T21:43:00.810Z",
"question_score": 227,
"tags": "c++|variables|pass-by-reference|constants|pass-by-value",
"answer_id": 270435,
"answer_date": "2008-11-06T21:49:23.980Z",
"answer_score": 222
} |
Please answer the following Stack Overflow question:
Title: Java: How to test methods that call System.exit()?
<p>I've got a few methods that should call <code>System.exit()</code> on certain inputs. Unfortunately, testing these cases causes JUnit to terminate! Putting the method calls in a new Thread doesn't seem to help, since <code>System.exit()</code> terminates the JVM, not just the current thread. Are there any common patterns for dealing with this? For example, can I subsitute a stub for <code>System.exit()</code>? </p>
<p>[EDIT] The class in question is actually a command-line tool which I'm attempting to test inside JUnit. Maybe JUnit is simply not the right tool for the job? Suggestions for complementary regression testing tools are welcome (preferably something that integrates well with JUnit and EclEmma).</p> | <p>Indeed, <a href="http://coding.derkeiler.com/Archive/Java/comp.lang.java.programmer/2008-04/msg02603.html" rel="noreferrer">Derkeiler.com</a> suggests:</p>
<ul>
<li>Why <code>System.exit()</code> ?</li>
</ul>
<blockquote>
<p>Instead of terminating with System.exit(whateverValue), why not throw an unchecked exception? In normal use it will drift all the way out to the JVM's last-ditch catcher and shut your script down (unless you decide to catch it somewhere along the way, which might be useful someday). </p>
<p>In the JUnit scenario it will be caught by the JUnit framework, which will report that
such-and-such test failed and move smoothly along to the next.</p>
</blockquote>
<ul>
<li>Prevent <code>System.exit()</code> to actually exit the JVM:</li>
</ul>
<blockquote>
<p>Try modifying the TestCase to run with a security manager that prevents calling System.exit, then catch the SecurityException.</p>
</blockquote>
<pre><code>public class NoExitTestCase extends TestCase
{
protected static class ExitException extends SecurityException
{
public final int status;
public ExitException(int status)
{
super("There is no escape!");
this.status = status;
}
}
private static class NoExitSecurityManager extends SecurityManager
{
@Override
public void checkPermission(Permission perm)
{
// allow anything.
}
@Override
public void checkPermission(Permission perm, Object context)
{
// allow anything.
}
@Override
public void checkExit(int status)
{
super.checkExit(status);
throw new ExitException(status);
}
}
@Override
protected void setUp() throws Exception
{
super.setUp();
System.setSecurityManager(new NoExitSecurityManager());
}
@Override
protected void tearDown() throws Exception
{
System.setSecurityManager(null); // or save and restore original
super.tearDown();
}
public void testNoExit() throws Exception
{
System.out.println("Printing works");
}
public void testExit() throws Exception
{
try
{
System.exit(42);
} catch (ExitException e)
{
assertEquals("Exit status", 42, e.status);
}
}
}
</code></pre>
<hr>
<p>Update December 2012:</p>
<p><a href="https://stackoverflow.com/users/557117/will">Will</a> proposes <a href="https://stackoverflow.com/questions/309396/java-how-to-test-methods-that-call-system-exit/309427#comment19186122_309427">in the comments</a> using <a href="http://stefanbirkner.github.com/system-rules/" rel="noreferrer"><strong>System Rules</strong></a>, a collection of JUnit(4.9+) rules for testing code which uses <code>java.lang.System</code>.<br>
This was initially mentioned by <strong><a href="https://stackoverflow.com/users/557091/stefan-birkner">Stefan Birkner</a></strong> in <a href="https://stackoverflow.com/a/8658497/6309">his answer</a> in December 2011.</p>
<pre><code>System.exit(…)
</code></pre>
<blockquote>
<p>Use the <a href="http://stefanbirkner.github.com/system-rules/#ExpectedSystemExit" rel="noreferrer"><code>ExpectedSystemExit</code></a> rule to verify that <code>System.exit(…)</code> is called.<br>
You could verify the exit status, too.</p>
</blockquote>
<p>For instance:</p>
<pre><code>public void MyTest {
@Rule
public final ExpectedSystemExit exit = ExpectedSystemExit.none();
@Test
public void noSystemExit() {
//passes
}
@Test
public void systemExitWithArbitraryStatusCode() {
exit.expectSystemExit();
System.exit(0);
}
@Test
public void systemExitWithSelectedStatusCode0() {
exit.expectSystemExitWithStatus(0);
System.exit(0);
}
}
</code></pre> | {
"question_id": 309396,
"question_date": "2008-11-21T16:38:58.930Z",
"question_score": 227,
"tags": "java|multithreading|unit-testing|junit|testability",
"answer_id": 309427,
"answer_date": "2008-11-21T16:48:22.920Z",
"answer_score": 236
} |
Please answer the following Stack Overflow question:
Title: Get PostGIS version
<p>How can I find out which version of PostGIS I have?</p> | <p>Since some of the functions depend on other libraries like GEOS and proj4 you might want to get their versions too. Then use:</p>
<pre><code>SELECT PostGIS_full_version();
</code></pre> | {
"question_id": 4833282,
"question_date": "2011-01-28T21:36:50.550Z",
"question_score": 227,
"tags": "postgresql|postgis",
"answer_id": 4833716,
"answer_date": "2011-01-28T22:34:38.300Z",
"answer_score": 347
} |
Please answer the following Stack Overflow question:
Title: What is Autoloading; How do you use spl_autoload, __autoload and spl_autoload_register?
<p>I am learning advanced PHP standards and trying to implement new and useful methods. Earlier I was using <code>__autoload</code> just to escape including multiple files on each page, but recently I have seen a tip on <a href="http://in2.php.net/__autoload" rel="noreferrer"><code>__autoload manual</code></a> </p>
<blockquote>
<p><strong>spl_autoload_register()</strong> provides a more flexible alternative for
autoloading classes. For this reason, using <strong>__autoload()</strong> is
discouraged and may be deprecated or removed in the future.</p>
</blockquote>
<p>but I really can't figure out how to implement <a href="http://www.php.net/manual/en/function.spl-autoload.php" rel="noreferrer"><code>spl_autoload</code></a> and <a href="http://www.php.net/manual/en/function.spl-autoload-register.php" rel="noreferrer"><code>spl_autoload_register</code></a></p> | <p><code>spl_autoload_register()</code> allows you to register multiple functions (or static methods from your own Autoload class) that PHP will put into a stack/queue and call sequentially when a "new Class" is declared. </p>
<p>So for example:</p>
<pre><code>spl_autoload_register('myAutoloader');
function myAutoloader($className)
{
$path = '/path/to/class/';
include $path.$className.'.php';
}
//-------------------------------------
$myClass = new MyClass();
</code></pre>
<p>In the example above, "MyClass" is the name of the class that you are trying to instantiate, PHP passes this name as a string to <code>spl_autoload_register()</code>, which allows you to pick up the variable and use it to "include" the appropriate class/file. As a result you don't specifically need to include that class via an include/require statement... </p>
<p>Just simply call the class you want to instantiate like in the example above, and since you registered a function (via <code>spl_autoload_register()</code>) of your own that will figure out where all your class are located, PHP will use that function.</p>
<p>The benefit of using <code>spl_autoload_register()</code> is that unlike <code>__autoload()</code> you don't need to implement an autoload function in every file that you create. <code>spl_autoload_register()</code> also allows you to register multiple autoload functions to speed up autoloading and make it even easier. </p>
<p>Example:</p>
<pre><code>spl_autoload_register('MyAutoloader::ClassLoader');
spl_autoload_register('MyAutoloader::LibraryLoader');
spl_autoload_register('MyAutoloader::HelperLoader');
spl_autoload_register('MyAutoloader::DatabaseLoader');
class MyAutoloader
{
public static function ClassLoader($className)
{
//your loading logic here
}
public static function LibraryLoader($className)
{
//your loading logic here
}
</code></pre>
<hr>
<p>With regards to <a href="http://ca3.php.net/manual/en/function.spl-autoload.php" rel="noreferrer">spl_autoload</a>, the manual states:</p>
<blockquote>
<p>This function is intended to be used as a default implementation for <code>__autoload()</code>. If nothing else is specified and <code>spl_autoload_register()</code> is called without any parameters then this functions will be used for any later call to <code>__autoload()</code>. </p>
</blockquote>
<p>In more practical terms, if all your files are located in a single directory and your application uses not only .php files, but custom configuration files with .inc extensions for example, then one strategy you could use would be to add your directory containing all files to PHP's include path (via <code>set_include_path()</code>).<br>
And since you require your configuration files as well, you would use <code>spl_autoload_extensions()</code> to list the extensions that you want PHP to look for. </p>
<p>Example:</p>
<pre><code>set_include_path(get_include_path().PATH_SEPARATOR.'path/to/my/directory/');
spl_autoload_extensions('.php, .inc');
spl_autoload_register();
</code></pre>
<p>Since spl_autoload is the default implementation of the <code>__autoload()</code> magic method, PHP will call spl_autoload when you try and instantiate a new class. </p>
<p>Hope this helps...</p> | {
"question_id": 7651509,
"question_date": "2011-10-04T17:07:06.477Z",
"question_score": 227,
"tags": "php|autoload|spl",
"answer_id": 7987085,
"answer_date": "2011-11-02T20:45:38.960Z",
"answer_score": 382
} |
Please answer the following Stack Overflow question:
Title: How come an array's address is equal to its value in C?
<p>In the following bit of code, pointer values and pointer addresses differ as expected.</p>
<p>But array values and addresses don't!</p>
<p>How can this be?</p>
<p>Output</p>
<pre><code>my_array = 0022FF00
&my_array = 0022FF00
pointer_to_array = 0022FF00
&pointer_to_array = 0022FEFC
</code></pre>
<pre><code>#include <stdio.h>
int main()
{
char my_array[100] = "some cool string";
printf("my_array = %p\n", my_array);
printf("&my_array = %p\n", &my_array);
char *pointer_to_array = my_array;
printf("pointer_to_array = %p\n", pointer_to_array);
printf("&pointer_to_array = %p\n", &pointer_to_array);
printf("Press ENTER to continue...\n");
getchar();
return 0;
}
</code></pre> | <p>The name of an array usually evaluates to the address of the first element of the array, so <code>array</code> and <code>&array</code> have the same value (but different types, so <code>array+1</code> and <code>&array+1</code> will <em>not</em> be equal if the array is more than 1 element long).</p>
<p>There are two exceptions to this: when the array name is an operand of <code>sizeof</code> or unary <code>&</code> (address-of), the name refers to the array object itself. Thus <code>sizeof array</code> gives you the size in bytes of the entire array, not the size of a pointer.</p>
<p>For an array defined as <code>T array[size]</code>, it will have type <code>T *</code>. When/if you increment it, you get to the next element in the array.</p>
<p><code>&array</code> evaluates to the same address, but given the same definition, it creates a pointer of the type <code>T(*)[size]</code> -- i.e., it's a pointer to an array, not to a single element. If you increment this pointer, it'll add the size of the entire array, not the size of a single element. For example, with code like this:</p>
<pre><code>char array[16];
printf("%p\t%p", (void*)&array, (void*)(&array+1));
</code></pre>
<p>We can expect the second pointer to be 16 greater than the first (because it's an array of 16 char's). Since %p typically converts pointers in hexadecimal, it might look something like:</p>
<pre><code>0x12341000 0x12341010
</code></pre> | {
"question_id": 2528318,
"question_date": "2010-03-27T05:59:56.193Z",
"question_score": 227,
"tags": "c|pointers|arrays",
"answer_id": 2528328,
"answer_date": "2010-03-27T06:04:43.920Z",
"answer_score": 247
} |
Please answer the following Stack Overflow question:
Title: Python 3.x rounding behavior
<p>I was just re-reading <a href="http://docs.python.org/py3k/whatsnew/3.0.html" rel="noreferrer">What’s New In Python 3.0</a> and it states:</p>
<blockquote>
<p>The round() function rounding strategy and return type have changed.
Exact halfway cases are now rounded to the nearest even result instead
of away from zero. (For example, round(2.5) now returns 2 rather than
3.)</p>
</blockquote>
<p>and
the documentation for <a href="http://docs.python.org/release/3.1.5/library/functions.html#round" rel="noreferrer">round</a>:</p>
<blockquote>
<p>For the built-in types supporting round(), values are rounded to the
closest multiple of 10 to the power minus n; if two multiples are
equally close, rounding is done toward the even choice</p>
</blockquote>
<p>So, under <strong>v2.7.3</strong>:</p>
<pre><code>In [85]: round(2.5)
Out[85]: 3.0
In [86]: round(3.5)
Out[86]: 4.0
</code></pre>
<p>as I'd have expected. However, now under <strong>v3.2.3</strong>:</p>
<pre><code>In [32]: round(2.5)
Out[32]: 2
In [33]: round(3.5)
Out[33]: 4
</code></pre>
<p>This seems counter-intuitive and contrary to what I understand about
rounding (and bound to trip up people). English isn't my native language but
until I read this I thought I knew what rounding meant :-/ I am sure
at the time v3 was introduced there must have been some discussion of
this, but I was unable to find a good reason in my search.</p>
<ol>
<li>Does anyone have insight into why this was changed to this?</li>
<li>Are there any other mainstream programming languages (e.g., <em>C, C++, Java, Perl,</em> ..) that do this sort of (to me inconsistent) rounding?</li>
</ol>
<p>What am I missing here?</p>
<p>UPDATE: @Li-aungYip's comment re "Banker's rounding" gave me the right search term/keywords to search for and I found this SO question: <a href="https://stackoverflow.com/questions/311696/why-does-net-use-bankers-rounding-as-default">Why does .NET use banker's rounding as default?</a>, so I will be reading that carefully.</p> | <p>Python 3's way (called "<a href="https://en.wikipedia.org/wiki/Rounding#Round_half_to_even" rel="noreferrer">round half to even</a>" or "banker's rounding") is considered the standard rounding method these days, though some language implementations aren't on the bus yet.</p>
<p>The simple "<a href="https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero" rel="noreferrer">always round 0.5 up</a>" technique results in a slight bias toward the higher number. With large numbers of calculations, this can be significant. The Python 3.0 approach eliminates this issue.</p>
<p>There is more than one method of rounding in common use. IEEE 754, the international standard for floating-point math, defines <a href="https://en.wikipedia.org/wiki/IEEE_754#Rounding_rules" rel="noreferrer">five different rounding methods</a> (the one used by Python 3.0 is the default). And <a href="https://en.wikipedia.org/wiki/Rounding#Rounding_to_integer" rel="noreferrer">there are others</a>.</p>
<p>This behavior is not as widely known as it ought to be. AppleScript was, if I remember correctly, an early adopter of this rounding method. The <a href="https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/reference/ASLR_cmds.html#//apple_ref/doc/uid/TP40000983-CH216-SW43" rel="noreferrer"><code>round</code> command in AppleScript</a> offers several options, but round-toward-even is the default as it is in IEEE 754. Apparently the engineer who implemented the <code>round</code> command got so fed up with all the requests to "make it work like I learned in school" that he implemented just that: <code>round 2.5 rounding as taught in school</code> is a valid AppleScript command. :-)</p> | {
"question_id": 10825926,
"question_date": "2012-05-31T00:11:09.400Z",
"question_score": 227,
"tags": "python|python-3.x|rounding",
"answer_id": 10825998,
"answer_date": "2012-05-31T00:24:15.787Z",
"answer_score": 207
} |
Please answer the following Stack Overflow question:
Title: Access properties of the parent with a Handlebars 'each' loop
<p>Consider the following simplified data:</p>
<pre><code>var viewData = {
itemSize: 20,
items: [
'Zimbabwe', 'dog', 'falafel'
]
};
</code></pre>
<p>And a Handlebars template:</p>
<pre><code>{{#each items}}
<div style="font-size:{{itemSize}}px">{{this}}</div>
{{/each}}
</code></pre>
<p>This won't work because within the <code>each</code> loop, the parent scope is not accessible -- at least not in any way that I've tried. I'm hoping that there's a way of doing this though!</p> | <p>There are two valid ways to achieve this.</p>
<h3>Dereference the parent scope with <code>../</code></h3>
<p>By prepending <code>../</code> to the property name, you can reference the parent scope.</p>
<pre><code>{{#each items}}
<div style="font-size:{{../itemSize}}px">{{this}}</div>
{{#if this.items.someKey}}
<div style="font-size:{{../../itemSize}}px">{{this}}</div>
{{/if}}
{{/each}}
</code></pre>
<p>You can go up multiple levels via repeating the <code>../</code>. For example, to go up two levels use <code>../../key</code>.</p>
<p>For more information, see the <a href="https://handlebarsjs.com/guide/expressions.html#changing-the-context" rel="noreferrer">Handlebars documentation on paths</a>.</p>
<h3>Dereference the root scope with <code>@root</code></h3>
<p>By prepending <code>@root</code> to the property path, you can navigate downwards from the topmost scope (as shown in <a href="https://stackoverflow.com/a/36725440/24874">caballerog's answer</a>).</p>
<p>For more information, see the <a href="https://handlebarsjs.com/api-reference/data-variables.html#data-variables" rel="noreferrer">Handlebars documentation on @data variables</a>.</p> | {
"question_id": 12297959,
"question_date": "2012-09-06T10:24:24.023Z",
"question_score": 227,
"tags": "javascript|handlebars.js",
"answer_id": 12297980,
"answer_date": "2012-09-06T10:26:11.433Z",
"answer_score": 471
} |
Please answer the following Stack Overflow question:
Title: Installing libv8 gem on OS X 10.9+
<p>I'm trying to install libv8 3.16.14.3 but getting an error on OSX Mavericks using latest stable rvm and ruby-1.9.3-p125.</p>
<p>This is the output of running the command 'gem install libv8':</p>
<pre><code>~/src(branch:master) » gem install libv8
Fetching: libv8-3.16.14.3.gem (100%)
Building native extensions. This could take a while...
ERROR: Error installing therubyracer:
ERROR: Failed to build gem native extension.
/Users/me/.rvm/rubies/ruby-1.9.3-p125/bin/ruby extconf.rb
creating Makefile
Compiling v8 for x64
Using python 2.7.5
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Unable to find a compiler officially supported by v8.
It is recommended to use GCC v4.4 or higher
Using compiler: g++
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Unable to find a compiler officially supported by v8.
It is recommended to use GCC v4.4 or higher
libtool: unrecognized option `-static'
libtool: Try `libtool --help' for more information.
make[1]: *** [/Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/libpreparser_lib.a] Error 1
make: *** [x64.release] Error 2
/Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/ext/libv8/location.rb:36:in `block in verify_installation!': libv8 did not install properly, expected binary v8 archive '/Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/tools/gyp/libv8_base.a'to exist, but it was not found (Libv8::Location::Vendor::ArchiveNotFound)
from /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/ext/libv8/location.rb:35:in `each'
from /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/ext/libv8/location.rb:35:in `verify_installation!'
from /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/ext/libv8/location.rb:26:in `install!'
from extconf.rb:7:in `<main>'
GYP_GENERATORS=make \
build/gyp/gyp --generator-output="out" build/all.gyp \
-Ibuild/standalone.gypi --depth=. \
-Dv8_target_arch=x64 \
-S.x64 -Dv8_enable_backtrace=1 -Dv8_can_use_vfp2_instructions=true -Darm_fpu=vfpv2 -Dv8_can_use_vfp3_instructions=true -Darm_fpu=vfpv3
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/allocation.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/atomicops_internals_x86_gcc.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/bignum.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/bignum-dtoa.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/cached-powers.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/conversions.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/diy-fp.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/dtoa.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/fast-dtoa.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/fixed-dtoa.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/once.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/preparse-data.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/preparser.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/preparser-api.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/scanner.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/strtod.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/token.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/unicode.o
CXX(target) /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/obj.target/preparser_lib/src/utils.o
LIBTOOL-STATIC /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/vendor/v8/out/x64.release/libpreparser_lib.a
Gem files will remain installed in /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3 for inspection.
Results logged to /Users/me/.rvm/gems/ruby-1.9.3-p125@proj-rails3-ruby19/gems/libv8-3.16.14.3/ext/libv8/gem_make.out
</code></pre> | <p>This is due to the fact that OS X 10.9+ is using version 4.8 of GCC. This is not supported officially in older versions of libv8 as mentioned in the pull request (<a href="https://github.com/cowboyd/libv8/pull/95" rel="noreferrer">https://github.com/cowboyd/libv8/pull/95</a>). Please try bumping up the version of libv8 in your Gemfile (or) a <code>bundle update</code> should suffice. Hope this helps.</p>
<p>From the libv8 <a href="https://github.com/cowboyd/libv8#bring-your-own-compiler" rel="noreferrer">README</a></p>
<p><strong>Bring your own V8</strong></p>
<p>Because libv8 is the interface for the V8 engine used by therubyracer, you may need to use libv8, even if you have V8 installed already. If you wish to use your own V8 installation, rather than have it built for you, use the --with-system-v8 option.</p>
<p>Using RubyGems:</p>
<blockquote>
<p>gem install libv8 [-v YOUR_VERSION] -- --with-system-v8</p>
</blockquote>
<p>Using Bundler (in your Gemfile):</p>
<blockquote>
<p>bundle config build.libv8 --with-system-v8</p>
</blockquote>
<p>Please note that if you intend to run your own V8, you must install both V8 and its headers (found in libv8-dev for Debian distros).</p>
<p><strong>Bring your own compiler</strong></p>
<p>You can specify a compiler of your choice by either setting the CXX environment variable before compilation, or by adding the --with-cxx= option to the bundle configuration:</p>
<blockquote>
<p>bundle config build.libv8 --with-cxx=clang++</p>
</blockquote>
<p>Edit:</p>
<p>If this issue is brought on by <code>therubyracer</code>, try the following as suggested by <a href="https://stackoverflow.com/users/1197091/rider-on-rails">rider_on_rails</a> <a href="https://stackoverflow.com/questions/23536893/installing-libv8-and-therubyracer-gems-on-mavericks-with-system-v8-installation">here</a>:</p>
<blockquote>
<p>gem uninstall libv8</p>
<p>gem install therubyracer -v YOUR_RUBY_RACER_VERSION</p>
<p>gem install libv8 -v YOUR_VERSION -- --with-system-v8</p>
</blockquote> | {
"question_id": 19577759,
"question_date": "2013-10-24T22:17:59.677Z",
"question_score": 227,
"tags": "gem|rubygems|osx-mavericks|osx-yosemite|libv8",
"answer_id": 19586282,
"answer_date": "2013-10-25T09:39:31.463Z",
"answer_score": 479
} |
Please answer the following Stack Overflow question:
Title: Rails: Is there a rails trick to adding commas to large numbers?
<p>Is there a way to have rails print out a number with commas in it?</p>
<p>For example, if I have a number 54000000.34, I can run <%= number.function %>, which would print out "54,000,000.34" </p>
<p>thanks!</p> | <p>You want the <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#M001971" rel="noreferrer"><code>number_with_delimiter</code></a> method. For example:</p>
<pre><code><%= number_with_delimiter(@number, :delimiter => ',') %>
</code></pre>
<p>Alternatively, you can use the <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#M001972" rel="noreferrer"><code>number_with_precision</code></a> method to ensure that the number is always displayed with two decimal places of precision:</p>
<pre><code><%= number_with_precision(@number, :precision => 2, :delimiter => ',') %>
</code></pre> | {
"question_id": 1078347,
"question_date": "2009-07-03T08:24:06.227Z",
"question_score": 227,
"tags": "ruby-on-rails|ruby",
"answer_id": 1078366,
"answer_date": "2009-07-03T08:28:36.953Z",
"answer_score": 386
} |
Please answer the following Stack Overflow question:
Title: UITapGestureRecognizer breaks UITableView didSelectRowAtIndexPath
<p>I have written my own function to scroll text fields up when the keyboard shows up. In order to dismiss the keyboard by tapping away from the text field, I've created a <code>UITapGestureRecognizer</code> that takes care of resigning first responder on the text field when tapping away.</p>
<p>Now I've also created an autocomplete for the textfield that creates a <code>UITableView</code> just below the text field and populates it with items as the user enters text.</p>
<p>However, when selecting one of the entries in the auto completed table, <code>didSelectRowAtIndexPath</code> does not get called. Instead, it seems that the tap gesture recognizer is getting called and just resigns first responder.</p>
<p>I'm guessing there's some way to tell the tap gesture recognizer to keep passing the tap message on down to the <code>UITableView</code>, but I can't figure out what it is. Any help would be very appreciated.</p> | <p>Ok, finally found it after some searching through gesture recognizer docs.</p>
<p>The solution was to implement <code>UIGestureRecognizerDelegate</code> and add the following:</p>
<pre><code>#pragma mark UIGestureRecognizerDelegate methods
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
if ([touch.view isDescendantOfView:autocompleteTableView]) {
// Don't let selections of auto-complete entries fire the
// gesture recognizer
return NO;
}
return YES;
}
</code></pre>
<p>That took care of it. Hopefully this will help others as well.</p> | {
"question_id": 8192480,
"question_date": "2011-11-19T06:58:44.147Z",
"question_score": 227,
"tags": "ios|uitableview|uitapgesturerecognizer",
"answer_id": 8198502,
"answer_date": "2011-11-20T00:30:58.983Z",
"answer_score": 279
} |
Please answer the following Stack Overflow question:
Title: Why are dashes preferred for CSS selectors / HTML attributes?
<p>In the past I've always used underscores for defining <em>class</em> and <em>id</em> attributes in HTML. Over the last few years I changed over to dashes, mostly to align myself with the <a href="http://css-tricks.com/5016-new-poll-hyphens-or-dashes/" rel="noreferrer">trend in the community</a>, not necessarily because it made sense to me.</p>
<p>I've always thought dashes have more drawbacks, and I don't see the benefits:</p>
<h3>Code completion & Editing</h3>
<p>Most editors treat dashes as word separators, so I can't tab through to the symbol I want. Say the class is "<code>featured-product</code>", I have to auto-complete "<code>featured</code>", enter a hyphen, and complete "<code>product</code>".</p>
<p>With underscores "<code>featured_product</code>" is treated as one word, so it can be filled in one step.</p>
<p>The same applies to navigating through the document. Jumping by words or double-clicking on class names is broken by hyphens.</p>
<p>(More generally, I think of classes and ids as <em>tokens</em>, so it doesn't make sense to me that a token should be so easily splittable on hyphens.)</p>
<h3>Ambiguity with arithmetic operator</h3>
<p>Using dashes breaks object-property <a href="https://stackoverflow.com/questions/2119629/javascript-and-css-using-dashes/2119668#2119668">access to form elements</a> in JavaScript. This is only possible with underscores:</p>
<pre><code>form.first_name.value='Stormageddon';
</code></pre>
<p>(Admittedly I don't access form elements this way myself, but when deciding on dashes vs underscores as a universal rule, consider that someone might.)</p>
<p>Languages like <a href="http://sass-lang.com/" rel="noreferrer">Sass</a> (especially throughout the <a href="http://compass-style.org/" rel="noreferrer">Compass</a> framework) have settled on dashes as a standard, even for variable names. They originally used underscores in the beginning too. The fact that this is parsed differently strikes me as odd:</p>
<pre><code>$list-item-10
$list-item - 10
</code></pre>
<h3>Inconsistency with variable naming across languages</h3>
<p>Back in the day, I used to write <code>underscored_names</code> for variables in PHP, ruby, HTML/CSS, and JavaScript. This was convenient and consistent, but again in order to "fit in" I now use:</p>
<ul>
<li><code>dash-case</code> in HTML/CSS</li>
<li><code>camelCase</code> in JavaScript</li>
<li><code>underscore_case</code> in PHP and ruby</li>
</ul>
<p>This doesn't really bother me too much, but I wonder why these became so misaligned, seemingly on purpose. At least with underscores it was possible to maintain consistency:</p>
<pre><code>var featured_product = $('#featured_product'); // instead of
var featuredProduct = $('#featured-product');
</code></pre>
<p>The differences create situations where we have to <a href="https://stackoverflow.com/questions/7286607/jquery-camel-case-mapping-from-data-attribute-names-to-data-keys">translate strings</a> unnecessarily, along with the potential for bugs.</p>
<p>So I ask: Why did the community almost universally settle on dashes, and are there any reasons that outweigh underscores?</p>
<p>There is a <a href="https://stackoverflow.com/questions/1686337/hyphens-or-underscores-in-css-and-html-identifiers">related question</a> from back around the time this started, but I'm of the opinion that it's not (or <em>shouldn't</em> have been) just a matter of taste. I'd like to understand why we all settled on this convention if it really was just a matter of taste.</p> | <h2>Code completion</h2>
<p>Whether dash is interpreted as punctuation or as an opaque identifier depends on the editor of choice, I guess. However, as a personal preference, I favor being able to tab between each word in a CSS file and would find it annoying if they were separated with underscore and there were no stops.</p>
<p>Also, using hyphens allows you to take advantage of the <a href="http://www.w3.org/TR/CSS21/selector.html#attribute-selectors" rel="noreferrer">|= attribute selector</a>, which selects any element containing the text, optionally followed by a dash:</p>
<pre><code>span[class|="em"] { font-style: italic; }
</code></pre>
<p>This would make the following HTML elements have italic font-style:</p>
<pre><code><span class="em">I'm italic</span>
<span class="em-strong">I'm italic too</span>
</code></pre>
<h2>Ambiguity with arithmetic operator</h2>
<p>I'd say that access to HTML elements via dot notation in JavaScript is a bug rather than a feature. It's a terrible construct from the early days of terrible JavaScript implementations and isn't really a great practice. For most of the stuff you do with JavaScript these days, you'd want to use <a href="http://www.w3.org/TR/CSS21/selector.html" rel="noreferrer">CSS Selectors</a> for fetching elements from the DOM anyway, which makes the whole dot notation rather useless. Which one would you prefer?</p>
<pre><code>var firstName = $('#first-name');
var firstName = document.querySelector('#first-name');
var firstName = document.forms[0].first_name;
</code></pre>
<p>I find the two first options much more preferable, especially since <code>'#first-name'</code> can be replaced with a JavaScript variable and built dynamically. I also find them more pleasant on the eyes.</p>
<p>The fact that Sass enables arithmetic in its extensions to CSS doesn't really apply to CSS itself, but I do understand (and embrace) the fact that Sass follows the language style of CSS (except for the <code>$</code> prefix of variables, which of course should have been <code>@</code>). If Sass documents are to look and feel like CSS documents, they need to follow the same style as CSS, which uses dash as a delimiter. In CSS3, arithmetic is limited to the <a href="http://www.w3.org/TR/css3-values/#calc" rel="noreferrer"><code>calc</code></a> function, which goes to show that in CSS itself, this isn't an issue.</p>
<h2>Inconsistency with variable naming across languages</h2>
<p>All languages, being markup languages, programming languages, styling languages or scripting languages, have their own style. You will find this within sub-languages of language groups like XML, where e.g. <a href="http://www.w3.org/TR/xslt" rel="noreferrer">XSLT</a> uses lower-case with hyphen delimiters and <a href="http://www.w3.org/XML/Schema" rel="noreferrer">XML Schema</a> uses camel-casing.</p>
<p>In general, you will find that adopting the style that feels and looks most "native" to the language you're writing in is better than trying to shoe-horn your own style into every different language. Since you can't avoid having to use native libraries and language constructs, your style will be "polluted" by the native style whether you like it or not, so it's pretty much futile to even try.</p>
<p>My advice is to not find a favorite style across languages, but instead make yourself at home within each language and learn to love all of its quirks. One of CSS' quirks is that keywords and identifiers are written in lowercase and separated by hyphens. Personally, I find this very visually appealing and think it fits in with the all-lowercase (although no-hyphen) <a href="http://www.w3.org/TR/html401/" rel="noreferrer">HTML</a>.</p> | {
"question_id": 7560813,
"question_date": "2011-09-26T20:18:13.367Z",
"question_score": 227,
"tags": "html|css|coding-style|naming-conventions",
"answer_id": 7561329,
"answer_date": "2011-09-26T21:07:48.617Z",
"answer_score": 142
} |
Please answer the following Stack Overflow question:
Title: Autolayout - intrinsic size of UIButton does not include title insets
<p>If I have a UIButton arranged using autolayout, its size adjusts nicely to fit its content.</p>
<p>If I set an image as <code>button.image</code>, the instrinsic size again seems to account for this.</p>
<p>However, if I tweak the <code>titleEdgeInsets</code> of the button, the layout does not account for this and instead truncates the button title.</p>
<p>How can I ensure that the intrinsic width of the button accounts for the inset?</p>
<p><img src="https://i.stack.imgur.com/bFikp.png" alt="enter image description here"></p>
<p>Edit:</p>
<p>I am using the following:</p>
<pre><code>[self.backButton setTitleEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 0)];
</code></pre>
<p>The goal is to add some separation between the image and the text.</p> | <p>You can solve this without having to override any methods or set an arbitrary width constraint. You can do it all in Interface Builder as follows.</p>
<ul>
<li><p>Intrinsic button width is derived from the title width plus the icon width plus the left and right <em>content</em> edge insets.</p></li>
<li><p>If a button has both an image and text, they’re centered as a group, with no padding between.</p></li>
<li><p>If you add a left content inset, it’s calculated relative to the text, not the text + icon.</p></li>
<li><p>If you set a negative left image inset, the image is pulled out to the left but the overall button width is unaffected.</p></li>
<li><p>If you set a negative left image inset, the actual layout uses half that value. So to get a -20 point left inset, you must use a -40 point left inset value in Interface Builder.</p></li>
</ul>
<p>So you provide a big enough left content inset to create space for both the desired left inset <em>and</em> the inner padding between the icon and the text, and then shift the icon left by doubling the amount of padding you want between the icon and the text. The result is a button with equal left and right content insets, and a text and icon pair that are centered as a group, with a specific amount of padding between them.</p>
<p>Some example values:</p>
<pre><code>// Produces a button with the layout:
// |-20-icon-10-text-20-|
// AutoLayout intrinsic width works as you'd desire.
button.contentEdgeInsets = UIEdgeInsetsMake(10, 30, 10, 20)
button.imageEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0)
</code></pre> | {
"question_id": 17800288,
"question_date": "2013-07-23T01:52:53.230Z",
"question_score": 227,
"tags": "ios|cocoa-touch|uiview|uibutton|autolayout",
"answer_id": 37218908,
"answer_date": "2016-05-13T20:32:03.357Z",
"answer_score": 204
} |
Please answer the following Stack Overflow question:
Title: What is purpose of the property "private" in package.json?
<p>I'm learning node.js and express, I am wondering what is the property "private" in ./package.json file used for?</p> | <p>From the <a href="https://docs.npmjs.com/cli/v7/configuring-npm/package-json#private" rel="noreferrer">NPM docs on <code>package.json</code></a>:</p>
<blockquote>
<p><code>private</code></p>
<p>If you set <code>"private": true</code> in your package.json, then npm will refuse to publish it.</p>
<p>This is a way to prevent accidental publication of private repositories.</p>
</blockquote> | {
"question_id": 7314849,
"question_date": "2011-09-06T04:14:04.443Z",
"question_score": 227,
"tags": "node.js|package.json",
"answer_id": 7314961,
"answer_date": "2011-09-06T04:31:30.147Z",
"answer_score": 297
} |
Please answer the following Stack Overflow question:
Title: Undefined reference to static constexpr char[]
<p>I want to have a <code>static const</code> <code>char</code> array in my class. GCC complained and told me I should use <code>constexpr</code>, although now it's telling me it's an undefined reference. If I make the array a non-member then it compiles. What is going on?</p>
<pre><code>// .hpp
struct foo {
void bar();
static constexpr char baz[] = "quz";
};
// .cpp
void foo::bar() {
std::string str(baz); // undefined reference to baz
}
</code></pre> | <p>Add to your cpp file:</p>
<pre><code>constexpr char foo::baz[];
</code></pre>
<p>Reason: You have to provide the <em>definition</em> of the static member as well as the declaration. The declaration and the initializer go inside the class definition, but the member definition has to be separate.</p> | {
"question_id": 8016780,
"question_date": "2011-11-04T23:11:45.040Z",
"question_score": 227,
"tags": "c++|c++11|static-members|constexpr",
"answer_id": 8016853,
"answer_date": "2011-11-04T23:22:03.210Z",
"answer_score": 227
} |
Please answer the following Stack Overflow question:
Title: How can I show hidden files (starting with period) in NERDTree?
<p>How can I make <a href="https://github.com/scrooloose/nerdtree" rel="noreferrer">NERDTree</a> show files that begin with an <code>.</code> (period)?</p>
<p>I have a file named <code>.hgignore</code> in a project directory. If I browse to that directory using NERDTree, the file is not displayed within the tree.</p>
<p>I am using gvim on Windows.</p> | <p>Press <kbd>I</kbd> (<kbd>Shift</kbd>+<kbd>i</kbd>) to toggle hidden files in the NERDTree explorer window.</p>
<p>To enable this behavior by default, add this line to your <code>.vimrc</code> file:</p>
<pre><code>let NERDTreeShowHidden=1
</code></pre>
<p>For more detail, access the NERDTree help file <code>:help NERD_tree.txt</code> and search for "hidden".</p> | {
"question_id": 5057359,
"question_date": "2011-02-20T13:41:31.753Z",
"question_score": 227,
"tags": "windows|vim|nerdtree",
"answer_id": 5057406,
"answer_date": "2011-02-20T13:50:11.410Z",
"answer_score": 452
} |
Please answer the following Stack Overflow question:
Title: What is unit testing?
<p>I saw many questions asking 'how' to unit test in a specific language, but no question asking 'what', 'why', and 'when'.</p>
<ul>
<li>What is it?</li>
<li>What does it do for me?</li>
<li>Why should I use it?</li>
<li>When should I use it (also when not)?</li>
<li>What are some common pitfalls and misconceptions</li>
</ul> | <p>Unit testing is, roughly speaking, testing bits of your code in isolation with test code. The immediate advantages that come to mind are:</p>
<ul>
<li>Running the tests becomes automate-able and repeatable</li>
<li>You can test at a much more granular level than point-and-click testing via a GUI</li>
</ul>
<p>Note that if your test code writes to a file, opens a database connection or does something over the network, it's more appropriately categorized as an integration test. Integration tests are a good thing, but should not be confused with unit tests. Unit test code should be short, sweet and quick to execute.</p>
<p>Another way to look at unit testing is that you write the tests first. This is known as Test-Driven Development (TDD for short). TDD brings additional advantages:</p>
<ul>
<li>You don't write speculative "I might need this in the future" code -- just enough to make the tests pass</li>
<li>The code you've written is always covered by tests</li>
<li>By writing the test first, you're forced into thinking about how you want to call the code, which usually improves the design of the code in the long run.</li>
</ul>
<p>If you're not doing unit testing now, I recommend you get started on it. Get a good book, practically any xUnit-book will do because the concepts are very much transferable between them. </p>
<p>Sometimes writing unit tests can be painful. When it gets that way, try to find someone to help you, and resist the temptation to "just write the damn code". Unit testing is a lot like washing the dishes. It's not always pleasant, but it keeps your metaphorical kitchen clean, and you really want it to be clean. :)</p>
<hr>
<p>Edit: One misconception comes to mind, although I'm not sure if it's so common. I've heard a project manager say that unit tests made the team write all the code twice. If it looks and feels that way, well, you're doing it wrong. Not only does writing the tests usually speed up development, but it also gives you a convenient "now I'm done" indicator that you wouldn't have otherwise.</p> | {
"question_id": 1383,
"question_date": "2008-08-04T16:27:39.787Z",
"question_score": 227,
"tags": "unit-testing",
"answer_id": 1393,
"answer_date": "2008-08-04T16:36:51.750Z",
"answer_score": 216
} |
Please answer the following Stack Overflow question:
Title: Typical AngularJS workflow and project structure (with Python Flask)
<p>I am pretty new to this whole MV* client-side framework frenzy. It doesn't have to be AngularJS, but I picked it because it feels more natural to me than either Knockout, Ember or Backbone. Anyway what is the workflow like? Do people start with developing a client-side application in AngularJS and then hooking up the back-end to it?</p>
<p>Or the other way around by first building the back-end in Django, Flask, Rails and then attaching an AngularJS app to it? Is there a "right" way of doing it, or is it just a personal preference in the end?</p>
<p>I am also not sure whether to structure my project according to the Flask or AngularJS? community practices.</p>
<p>For example, Flask's minitwit app is structured like so:</p>
<pre><code>minitwit
|-- minitwit.py
|-- static
|-- css, js, images, etc...
`-- templates
|-- html files and base layout
</code></pre>
<p>AngularJS tutorial app is structured like this:</p>
<pre><code>angular-phonecat
|-- app
`-- css
`-- img
`-- js
`-- lib
`-- partials
`-- index.html
|-- scripts
`-- node.js server and test server files
</code></pre>
<p>I could picture a Flask app by itself, and it's fairly easy to see AngularJS app like ToDo List by itself but when it comes to using both of these technologies I don't understand how they work together. It almost seems like I don't need a server-side web-framework when you already have AngularJS, a simple Python web server will suffice. In the AngularJS to-do app for example they use MongoLab to talk to the database using Restful API. There was no need having a web framework on the back-end.</p>
<p>Maybe I am just awfully confused, and AngularJS is nothing more than a fancy jQuery library so I should use just like I would use jQuery in my Flask projects (assuming I change the AngularJS template syntax to something that doesn't conflict with Jinja2). I hope my questions make some sense. I mainly work on the back-end and this client-side framework is an unknown territory for me.</p> | <p>I would start out by organizing the Flask app in the standard structure as follows:</p>
<pre><code>app
|-- app.py
|-- static
|-- css
|-- img
|-- js
|-- templates
</code></pre>
<p>And as btford mentioned, if you are doing an Angular app, you'll want to focus on using Angular client-side templates and stay away from server-side templates. Using render_template('index.html') will cause Flask to interpret your angular templates as jinja templates, so they won't render correctly. Instead, you'll want to do the following:</p>
<pre><code>@app.route("/")
def index():
return send_file('templates/index.html')
</code></pre>
<p>Note that using send_file() means that the files will be cached, so you might want to use make_response() instead, at least for development:</p>
<pre><code> return make_response(open('templates/index.html').read())
</code></pre>
<p>Afterwards, build out the AngularJS part of your app, modifying the app structure so that it looks like this:</p>
<pre><code>app
|-- app.py
|-- static
|-- css
|-- img
|-- js
|-- app.js, controllers.js, etc.
|-- lib
|-- angular
|-- angular.js, etc.
|-- partials
|-- templates
|-- index.html
</code></pre>
<p>Make sure your index.html includes AngularJS, as well as any other files:</p>
<pre><code><script src="static/lib/angular/angular.js"></script>
</code></pre>
<p>At this point, you haven't yet constructed your RESTful API, so you can have your js controllers return predefined sample data (only a temporary setup). When you're ready, implement the RESTful API and hook it up to your angular app with angular-resource.js.</p>
<p>EDIT: I put together an app template that, though a little more complex that what I've described above, illustrates how one could build an app with AngularJS + Flask, complete with communication between AngularJS and a simple Flask API. Here it is if you want to check it out: <a href="https://github.com/rxl/angular-flask">https://github.com/rxl/angular-flask</a></p> | {
"question_id": 11522151,
"question_date": "2012-07-17T12:10:07.237Z",
"question_score": 227,
"tags": "javascript|python|flask|angularjs",
"answer_id": 15144980,
"answer_date": "2013-02-28T20:23:33.423Z",
"answer_score": 170
} |
Please answer the following Stack Overflow question:
Title: Is there any difference between "foo is None" and "foo == None"?
<p>Is there any difference between:</p>
<pre><code>if foo is None: pass
</code></pre>
<p>and</p>
<pre><code>if foo == None: pass
</code></pre>
<p>The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?</p> | <p><code>is</code> always returns <code>True</code> if it compares the same object instance</p>
<p>Whereas <code>==</code> is ultimately determined by the <code>__eq__()</code> method</p>
<p>i.e.</p>
<pre><code>
>>> class Foo(object):
def __eq__(self, other):
return True
>>> f = Foo()
>>> f == None
True
>>> f is None
False
</code></pre> | {
"question_id": 26595,
"question_date": "2008-08-25T18:27:16.330Z",
"question_score": 227,
"tags": "python",
"answer_id": 26611,
"answer_date": "2008-08-25T18:38:10.267Z",
"answer_score": 265
} |
Please answer the following Stack Overflow question:
Title: Print list without brackets in a single row
<p>I have a list in Python
e.g.</p>
<pre><code>names = ["Sam", "Peter", "James", "Julian", "Ann"]
</code></pre>
<p>I want to print the array in a single line without the normal " []</p>
<pre><code>names = ["Sam", "Peter", "James", "Julian", "Ann"]
print (names)
</code></pre>
<p>Will give the output as;</p>
<pre><code>["Sam", "Peter", "James", "Julian", "Ann"]
</code></pre>
<p>That is not the format I want instead I want it to be like this;</p>
<pre><code>Sam, Peter, James, Julian, Ann
</code></pre>
<p>Note: It must be in a single row.</p> | <pre><code>print(', '.join(names))
</code></pre>
<p>This, like it sounds, just takes all the elements of the list and joins them with <code>', '</code>.</p> | {
"question_id": 11178061,
"question_date": "2012-06-24T13:59:28.870Z",
"question_score": 226,
"tags": "python|list",
"answer_id": 11178075,
"answer_date": "2012-06-24T14:01:07.273Z",
"answer_score": 330
} |
Please answer the following Stack Overflow question:
Title: Remove NA values from a vector
<p>I have a huge vector which has a couple of <code>NA</code> values, and I'm trying to find the max value in that vector (the vector is all numbers), but I can't do this because of the <code>NA</code> values.</p>
<p>How can I remove the <code>NA</code> values so that I can compute the max?</p> | <p>Trying <code>?max</code>, you'll see that it actually has a <code>na.rm =</code> argument, set by default to <code>FALSE</code>. (That's the common default for many other R functions, including <code>sum()</code>, <code>mean()</code>, etc.) </p>
<p>Setting <code>na.rm=TRUE</code> does just what you're asking for:</p>
<pre><code>d <- c(1, 100, NA, 10)
max(d, na.rm=TRUE)
</code></pre>
<p>If you do want to remove all of the <code>NA</code>s, use this idiom instead:</p>
<pre><code>d <- d[!is.na(d)]
</code></pre>
<p>A final note: Other functions (e.g. <code>table()</code>, <code>lm()</code>, and <code>sort()</code>) have <code>NA</code>-related arguments that use different names (and offer different options). So if <code>NA</code>'s cause you problems in a function call, it's worth checking for a built-in solution among the function's arguments. I've found there's <em>usually</em> one already there.</p> | {
"question_id": 7706876,
"question_date": "2011-10-09T22:08:07.370Z",
"question_score": 226,
"tags": "r",
"answer_id": 7706959,
"answer_date": "2011-10-09T22:21:48.687Z",
"answer_score": 306
} |
Please answer the following Stack Overflow question:
Title: Convert [key1,val1,key2,val2] to a dict?
<p>Let's say I have a list <code>a</code> in Python whose entries conveniently map to a dictionary. Each even element represents the key to the dictionary, and the following odd element is the value</p>
<p>for example,</p>
<pre><code>a = ['hello','world','1','2']
</code></pre>
<p>and I'd like to convert it to a dictionary <code>b</code>, where </p>
<pre><code>b['hello'] = 'world'
b['1'] = '2'
</code></pre>
<p>What is the syntactically cleanest way to accomplish this?</p> | <pre><code>b = dict(zip(a[::2], a[1::2]))
</code></pre>
<p>If <code>a</code> is large, you will probably want to do something like the following, which doesn't make any temporary lists like the above.</p>
<pre><code>from itertools import izip
i = iter(a)
b = dict(izip(i, i))
</code></pre>
<p>In Python 3 you could also use a dict comprehension, but ironically I think the simplest way to do it will be with <code>range()</code> and <code>len()</code>, which would normally be a code smell.</p>
<pre><code>b = {a[i]: a[i+1] for i in range(0, len(a), 2)}
</code></pre>
<p>So the <code>iter()/izip()</code> method is still probably the most Pythonic in Python 3, although as EOL notes in a comment, <code>zip()</code> is already lazy in Python 3 so you don't need <code>izip()</code>.</p>
<pre><code>i = iter(a)
b = dict(zip(i, i))
</code></pre>
<p>In Python 3.8 and later you can write this on one line using the "walrus" operator (<code>:=</code>):</p>
<pre><code>b = dict(zip(i := iter(a), i))
</code></pre>
<p>Otherwise you'd need to use a semicolon to get it on one line.</p> | {
"question_id": 4576115,
"question_date": "2011-01-01T22:29:00.440Z",
"question_score": 226,
"tags": "python|list|dictionary",
"answer_id": 4576128,
"answer_date": "2011-01-01T22:32:19.013Z",
"answer_score": 302
} |
Please answer the following Stack Overflow question:
Title: How to align an image dead center with bootstrap
<p>I'm using the bootstrap framework and trying to get an image centered horizontally without success..</p>
<p>I've tried various techniques such as splitting the the 12 grid system in 3 equal blocks e.g</p>
<pre><code><div class="container">
<div class="row">
<div class="span4"></div>
<div class="span4"><img src="logo.png" /></div>
<div class="span4"></div>
</div>
</div>
</code></pre>
<p>What's the easiest method to get an image centered relative to the page?</p> | <p>Twitter Bootstrap v3.0.3 has a class: center-block</p>
<blockquote>
<p>Center content blocks</p>
<p>Set an element to display: block and center via margin. Available as a mixin and class.</p>
</blockquote>
<p>Just need to add a class <code>.center-block</code> in the <code>img</code> tag, looks like this</p>
<pre><code><div class="container">
<div class="row">
<div class="span4"></div>
<div class="span4"><img class="center-block" src="logo.png" /></div>
<div class="span4"></div>
</div>
</div>
</code></pre>
<p>In Bootstrap already has css style call .center-block</p>
<pre><code>.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
</code></pre>
<p>You can see a sample from <a href="http://jsfiddle.net/vxad5/1/" rel="noreferrer">here</a></p> | {
"question_id": 10879955,
"question_date": "2012-06-04T10:40:33.190Z",
"question_score": 226,
"tags": "css|twitter-bootstrap",
"answer_id": 20561635,
"answer_date": "2013-12-13T07:55:37.573Z",
"answer_score": 282
} |
Please answer the following Stack Overflow question:
Title: What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?
<p>Let's assume an iteration in which we call a function without a return value. The way I think my program should behave is explained in this pseudocode:</p>
<pre><code>for element in some_list:
foo(element)
def foo(element):
do something
if check is true:
do more (because check was succesful)
else:
return None
do much much more...
</code></pre>
<p>If I implement this in python, it bothers me, that the function returns a <code>None</code>. Is there a better way for "exiting a function, that has no return value, if a check fails in the body of the function"?</p> | <p>You could simply use</p>
<pre><code>return
</code></pre>
<p>which does exactly the same as</p>
<pre><code>return None
</code></pre>
<p>Your function will also return <code>None</code> if execution reaches the end of the function body without hitting a <code>return</code> statement. Returning nothing is the same as returning <code>None</code> in Python.</p> | {
"question_id": 6190776,
"question_date": "2011-05-31T16:42:57.490Z",
"question_score": 226,
"tags": "python|function|return",
"answer_id": 6190798,
"answer_date": "2011-05-31T16:44:39.347Z",
"answer_score": 375
} |
Please answer the following Stack Overflow question:
Title: Counting unique values in a column in pandas dataframe like in Qlik?
<p>If I have a table like this: </p>
<pre><code>df = pd.DataFrame({
'hID': [101, 102, 103, 101, 102, 104, 105, 101],
'dID': [10, 11, 12, 10, 11, 10, 12, 10],
'uID': ['James', 'Henry', 'Abe', 'James', 'Henry', 'Brian', 'Claude', 'James'],
'mID': ['A', 'B', 'A', 'B', 'A', 'A', 'A', 'C']
})
</code></pre>
<p>I can do <code>count(distinct hID)</code> in Qlik to come up with count of 5 for unique hID. How do I do that in python using a pandas dataframe? Or maybe a numpy array? Similarly, if were to do <code>count(hID)</code> I will get 8 in Qlik. What is the equivalent way to do it in pandas?</p> | <p>Count distinct values, use <code>nunique</code>:</p>
<pre><code>df['hID'].nunique()
5
</code></pre>
<p>Count only non-null values, use <code>count</code>:</p>
<pre><code>df['hID'].count()
8
</code></pre>
<p>Count total values including null values, use the <code>size</code> attribute:</p>
<pre><code>df['hID'].size
8
</code></pre>
<h1>Edit to add condition</h1>
<p>Use boolean indexing:</p>
<pre><code>df.loc[df['mID']=='A','hID'].agg(['nunique','count','size'])
</code></pre>
<p>OR using <code>query</code>:</p>
<pre><code>df.query('mID == "A"')['hID'].agg(['nunique','count','size'])
</code></pre>
<p>Output:</p>
<pre><code>nunique 5
count 5
size 5
Name: hID, dtype: int64
</code></pre> | {
"question_id": 45759966,
"question_date": "2017-08-18T15:15:32.890Z",
"question_score": 226,
"tags": "python|pandas|numpy|qlikview|qliksense",
"answer_id": 45760042,
"answer_date": "2017-08-18T15:20:29.183Z",
"answer_score": 348
} |
Please answer the following Stack Overflow question:
Title: Installing Java 7 on Ubuntu
<p>to install java I have always used the classic way from the terminal.
I would like to install java manually.
I placed the folder of the JDK on the desk and I set environment variables (PATH, CLASSPATH and JAVA_HOME).
From the terminal, if I type <code>java -version</code> I get printed</p>
<pre><code>foralobo@ubuntu-vincy:~$ java -version
java version "1.7.0_21"
Java(TM) SE Runtime Environment (build 1.7.0_21-b11)
Java HotSpot(TM) 64-Bit Server VM (build 23.21-b01, mixed mode)
</code></pre>
<p>But when I try to install eclipse or netbeans, the system warns by saying that there is no java installed on the machine.</p>
<p>What is missing to compleatare manual installation?
(Ubuntu 13.04)</p> | <blockquote>
<p>This answer used to describe how to install Oracle Java 7. This no longer works since Oracle end-of-lifed Java 7 and put the binary downloads for versions with security patches behind a paywall. Also, OpenJDK has grown up and is a more viable alternative nowadays.</p>
</blockquote>
<p>In Ubuntu 16.04 and higher, Java 7 is no longer available. Usually you're best off installing Java 8 (or 9) instead.</p>
<pre><code>sudo apt-get install openjdk-8-jre
</code></pre>
<p>or, f you also want the compiler, get the jdk: </p>
<pre><code>sudo apt-get install openjdk-8-jdk
</code></pre>
<p>In Trusty, the easiest way to install Java 7 currently is to install OpenJDK package:</p>
<pre><code>sudo apt-get install openjdk-7-jre
</code></pre>
<p>or, for the jdk:</p>
<pre><code>sudo apt-get install openjdk-7-jdk
</code></pre>
<p>If you are specifically looking for Java 7 on a version of Ubuntu that no longer supports it, see <a href="https://askubuntu.com/questions/761127/how-do-i-install-openjdk-7-on-ubuntu-16-04-or-higher">https://askubuntu.com/questions/761127/how-do-i-install-openjdk-7-on-ubuntu-16-04-or-higher</a> .</p> | {
"question_id": 16263556,
"question_date": "2013-04-28T13:53:11.207Z",
"question_score": 226,
"tags": "java|ubuntu|installation",
"answer_id": 16263651,
"answer_date": "2013-04-28T14:03:47.337Z",
"answer_score": 552
} |
Please answer the following Stack Overflow question:
Title: Is it possible to use if...else... statement in React render function?
<p>Basically, I have a react component, its <code>render()</code> function body is as below: (It is my ideal one, which means it currently does not work)</p>
<pre class="lang-js prettyprint-override"><code>render(){
return (
<div>
<Element1/>
<Element2/>
// note: logic only, code does not work here
if (this.props.hasImage) <ElementWithImage/>
else <ElementWithoutImage/>
</div>
)
}
</code></pre> | <p>Not exactly like that, but there are workarounds. There's a section in <a href="https://reactjs.org/docs/conditional-rendering.html" rel="noreferrer">React's docs</a> about conditional rendering that you should take a look. Here's an example of what you could do using inline if-else.</p>
<pre><code>render() {
const isLoggedIn = this.state.isLoggedIn;
return (
<div>
{isLoggedIn ? (
<LogoutButton onClick={this.handleLogoutClick} />
) : (
<LoginButton onClick={this.handleLoginClick} />
)}
</div>
);
}
</code></pre>
<p>You can also deal with it inside the render function, but before returning the jsx. </p>
<pre><code>if (isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
return (
<div>
<Greeting isLoggedIn={isLoggedIn} />
{button}
</div>
);
</code></pre>
<p>It's also worth mentioning what ZekeDroid brought up in the comments. If you're just checking for a condition and don't want to render a particular piece of code that doesn't comply, you can use the <code>&& operator</code>.</p>
<pre><code> return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 &&
<h2>
You have {unreadMessages.length} unread messages.
</h2>
}
</div>
);
</code></pre> | {
"question_id": 40477245,
"question_date": "2016-11-08T00:54:31.340Z",
"question_score": 226,
"tags": "reactjs",
"answer_id": 40477289,
"answer_date": "2016-11-08T01:01:09.593Z",
"answer_score": 390
} |
Please answer the following Stack Overflow question:
Title: How to commit changes to another pre-existent branch
<p>I just made changes to a branch. How can I commit the changes to the other branch?</p>
<p>I am trying to use:</p>
<pre><code>git checkout "the commmit to the changed branch" -b "the other branch"
</code></pre>
<p>However, I don't think this is the right thing to do, because in this case I'm creating a new branch instead of committing the changes to "the other branch".</p>
<p>Should I use the following command instead?</p>
<pre><code>git merge "the other branch"
</code></pre> | <pre><code>git checkout -b your-new-branch
git add <files>
git commit -m <message>
</code></pre>
<p>First, checkout to your new branch. Then, add all the files you want to commit to staging. Lastly, commit all the files you just added. You might want to do a <code>git push origin your-new-branch</code> afterwards, so your changes show up on the remote.</p> | {
"question_id": 14655816,
"question_date": "2013-02-01T22:05:55.273Z",
"question_score": 226,
"tags": "git",
"answer_id": 14655842,
"answer_date": "2013-02-01T22:08:38.077Z",
"answer_score": 389
} |
Please answer the following Stack Overflow question:
Title: Member '<member name>' cannot be accessed with an instance reference
<p>I am getting into C# and I am having this issue:</p>
<pre><code>namespace MyDataLayer
{
namespace Section1
{
public class MyClass
{
public class MyItem
{
public static string Property1{ get; set; }
}
public static MyItem GetItem()
{
MyItem theItem = new MyItem();
theItem.Property1 = "MyValue";
return theItem;
}
}
}
}
</code></pre>
<p>I have this code on a UserControl:</p>
<pre><code>using MyDataLayer.Section1;
public class MyClass
{
protected void MyMethod
{
MyClass.MyItem oItem = new MyClass.MyItem();
oItem = MyClass.GetItem();
someLiteral.Text = oItem.Property1;
}
}
</code></pre>
<p>Everything works fine, except when I go to access <code>Property1</code>. The intellisense only gives me "<code>Equals</code>, <code>GetHashCode</code>, <code>GetType</code>, and <code>ToString</code>" as options. When I mouse over the <code>oItem.Property1</code>, Visual Studio gives me this explanation:</p>
<blockquote>
<p><code>Member</code>MyDataLayer.Section1.MyClass.MyItem.Property1.get<code>cannot be accessed with an instance reference, qualify it with a type name instead</code></p>
</blockquote>
<p>I am unsure of what this means, I did some googling but wasn't able to figure it out. </p> | <p>In C#, unlike VB.NET and Java, you can't access <code>static</code> members with instance syntax. You should do:</p>
<pre><code>MyClass.MyItem.Property1
</code></pre>
<p>to refer to that property or remove the <code>static</code> modifier from <code>Property1</code> (which is what you probably want to do). For a conceptual idea about what <a href="https://stackoverflow.com/questions/413898/what-does-the-static-keyword-do-in-java/413904#413904"><code>static</code> is, see my other answer</a>.</p> | {
"question_id": 1100009,
"question_date": "2009-07-08T19:11:17.107Z",
"question_score": 226,
"tags": "c#|asp.net",
"answer_id": 1100023,
"answer_date": "2009-07-08T19:13:27.743Z",
"answer_score": 328
} |
Please answer the following Stack Overflow question:
Title: Disable Input fields in reactive form
<p>I already tried to follow the example of other answers from here and I did not succeed! </p>
<p>I created a reactive form (ie, dynamic) and I want to disable some fields at any given time. My form code:</p>
<pre><code>this.form = this._fb.group({
name: ['', Validators.required],
options: this._fb.array([])
});
const control = <FormArray>this.form.controls['options'];
control.push(this._fb.group({
value: ['']
}));
</code></pre>
<p>my html:</p>
<pre><code><div class='row' formArrayName="options">
<div *ngFor="let opt of form.controls.options.controls; let i=index">
<div [formGroupName]="i">
<select formArrayName="value">
<option></option>
<option>{{ opt.controls.value }}</option>
</select>
</div>
</div>
</div>
</code></pre>
<p>I reduced the code to facilitate. I want to disable the field of type select. I tried to do the following:</p>
<pre><code>form = new FormGroup({
first: new FormControl({value: '', disabled: true}, Validators.required),
});
</code></pre>
<p>not working! Does anyone have a suggestion?</p> | <pre><code>name: [{value: '', disabled: true}, Validators.required],
name: [{value: '', disabled: this.isDisabled}, Validators.required],
</code></pre>
<p>or</p>
<pre><code>this.form.controls['name'].disable();
</code></pre> | {
"question_id": 42840136,
"question_date": "2017-03-16T16:47:51.663Z",
"question_score": 226,
"tags": "angular",
"answer_id": 44548569,
"answer_date": "2017-06-14T15:12:22.207Z",
"answer_score": 444
} |
Please answer the following Stack Overflow question:
Title: Fatal error: Class 'ZipArchive' not found in
<p>I have a problem that I install 'Archive_Zip 0.1.1' on Linux server, but when I try to run the script to create the zip file it gives the fatal error</p>
<blockquote>
<p>Fatal error: Class <code>ZipArchive</code> not found in ...</p>
</blockquote>
<p>where I put the code </p>
<pre><code>$zip = new ZipArchive;
var_dump($zip);
$res = $zip->open($filename, ZipArchive::OVERWRITE);
if ($res !== TRUE) {
echo 'Error: Unable to create zip file';
exit;
}
if (is_file($src)) {
$zip->addFile($src);
} else {
// echo "<br>" . dirname(__FILE__) . $src;//'/install1';
if (!is_dir($src)) {
$zip->close();
@unlink($filename);
echo 'Error: File not found';
exit;
}
recurse_zip($src, $zip, $path_length);
}
$zip->close();
echo "<br>file name ".$filename;
</code></pre>
<p>but it doesn't find the class file. </p>
<p>Please tell me the solution. What should I do to resolve the problem?
I also put <code>php.ini</code> file to the folder where script is, but it does not work.</p> | <p>For the <a href="http://www.php.net/manual/en/class.ziparchive.php" rel="noreferrer"><code>ZipArchive</code> class</a> to be present, PHP needs to have the <a href="http://www.php.net/manual/en/book.zip.php" rel="noreferrer">zip extension</a> installed.</p>
<p>See <a href="http://www.php.net/manual/en/zip.installation.php" rel="noreferrer">this page</a> for installation instructions (both Linux and Windows).</p> | {
"question_id": 3872555,
"question_date": "2010-10-06T12:47:01.663Z",
"question_score": 226,
"tags": "php|zip|ziparchive",
"answer_id": 3872578,
"answer_date": "2010-10-06T12:49:51.843Z",
"answer_score": 252
} |
Please answer the following Stack Overflow question:
Title: How to strip all whitespace from string
<p>How do I strip all the spaces in a python string? For example, I want a string like <code>strip my spaces</code> to be turned into <code>stripmyspaces</code>, but I cannot seem to accomplish that with <code>strip()</code>:</p>
<pre><code>>>> 'strip my spaces'.strip()
'strip my spaces'
</code></pre> | <p>Taking advantage of str.split's behavior with no sep parameter:</p>
<pre><code>>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'
</code></pre>
<p>If you just want to remove spaces instead of all whitespace:</p>
<pre><code>>>> s.replace(" ", "")
'\tfoo\nbar'
</code></pre>
<h2>Premature optimization</h2>
<p>Even though efficiency isn't the primary goal—writing clear code is—here are some initial timings:</p>
<pre><code>$ python -m timeit '"".join(" \t foo \n bar ".split())'
1000000 loops, best of 3: 1.38 usec per loop
$ python -m timeit -s 'import re' 're.sub(r"\s+", "", " \t foo \n bar ")'
100000 loops, best of 3: 15.6 usec per loop
</code></pre>
<p>Note the regex is cached, so it's not as slow as you'd imagine. Compiling it beforehand helps some, but would only matter in practice if you call this <em>many</em> times:</p>
<pre><code>$ python -m timeit -s 'import re; e = re.compile(r"\s+")' 'e.sub("", " \t foo \n bar ")'
100000 loops, best of 3: 7.76 usec per loop
</code></pre>
<p>Even though re.sub is 11.3x slower, remember your bottlenecks are assuredly elsewhere. Most programs would not notice the difference between any of these 3 choices.</p> | {
"question_id": 3739909,
"question_date": "2010-09-18T00:42:10.413Z",
"question_score": 226,
"tags": "python|python-3.x|spaces|strip",
"answer_id": 3739939,
"answer_date": "2010-09-18T00:54:26.467Z",
"answer_score": 381
} |
Please answer the following Stack Overflow question:
Title: Android SDK manager won't open
<p>So I installed the android sdk for Windows:</p>
<p><a href="http://developer.android.com/sdk/index.html" rel="noreferrer">http://developer.android.com/sdk/index.html</a> (the installation link) </p>
<p>And ran into the path variable problem. So I fixed that by changing "PATH" in enviroment variables to include where my java.exe file is located from the JDK. </p>
<p>But now when I open the android sdk manager, a cmd-like screen just briefly flashes on for half a second then disappears. I have no idea what's going on and how to get this thing working. </p> | <p>Make sure your <code>java\bin</code> directory is in your path statement before the <code>windows\system32</code> directory.
The SDK Manager uses java and it was finding the one in the system32 folder. </p>
<p>In a CMD window, you can run '<code>where java</code>'.
Don't forget to restart your CMD after changing the path variable for checking.</p> | {
"question_id": 5199811,
"question_date": "2011-03-04T22:04:17.280Z",
"question_score": 226,
"tags": "android|path",
"answer_id": 5734845,
"answer_date": "2011-04-20T18:22:04.417Z",
"answer_score": 268
} |
Please answer the following Stack Overflow question:
Title: Iterate through <select> options
<p>I have a <code><select></code> element in HTML. This element represents a drop down list. I'm trying to understand how to iterate through the options in the <code><select></code> element via JQuery.</p>
<p>How do I use JQuery to display the value and text of each option in a <code><select></code> element? I just want to display them in an <code>alert()</code> box.</p> | <pre><code>$("#selectId > option").each(function() {
alert(this.text + ' ' + this.value);
});
</code></pre>
<ul>
<li><a href="http://api.jquery.com/each/" rel="noreferrer">http://api.jquery.com/each/</a></li>
<li><a href="http://jsfiddle.net/Rx3AP/" rel="noreferrer">http://jsfiddle.net/Rx3AP/</a></li>
</ul> | {
"question_id": 2950152,
"question_date": "2010-06-01T13:30:35.140Z",
"question_score": 226,
"tags": "jquery",
"answer_id": 2950163,
"answer_date": "2010-06-01T13:31:50.637Z",
"answer_score": 392
} |
Please answer the following Stack Overflow question:
Title: How to append text to a text file in C++?
<p>How to append text to a text file in C++? And create a new text file if it does not already exist and append text to it if it does exist.</p> | <p>You need to specify the append open mode like</p>
<pre><code>#include <fstream>
int main() {
std::ofstream outfile;
outfile.open("test.txt", std::ios_base::app); // append instead of overwrite
outfile << "Data";
return 0;
}
</code></pre> | {
"question_id": 2393345,
"question_date": "2010-03-06T17:16:31.683Z",
"question_score": 226,
"tags": "c++|filestream",
"answer_id": 2393389,
"answer_date": "2010-03-06T17:27:47.940Z",
"answer_score": 360
} |
Please answer the following Stack Overflow question:
Title: How do I drop a foreign key in SQL Server?
<p>I have created a foreign key (in SQL Server) by:</p>
<pre><code>alter table company add CountryID varchar(3);
alter table company add constraint Company_CountryID_FK foreign key(CountryID)
references Country;
</code></pre>
<p>I then run this query:</p>
<pre><code>alter table company drop column CountryID;
</code></pre>
<p>and I get this error:</p>
<blockquote>
<p><em>Msg 5074, Level 16, State 4, Line 2<br>
The object 'Company_CountryID_FK' is dependent on column 'CountryID'.<br>
Msg 4922, Level 16, State 9, Line 2<br>
ALTER TABLE DROP COLUMN CountryID failed because one or more objects access this column</em></p>
</blockquote>
<p>I have tried this, yet it does not seem to work:</p>
<pre><code>alter table company drop foreign key Company_CountryID_FK;
alter table company drop column CountryID;
</code></pre>
<p>What do I need to do to drop the <code>CountryID</code> column?</p>
<p>Thanks.</p> | <p>Try</p>
<pre><code>alter table company drop constraint Company_CountryID_FK
alter table company drop column CountryID
</code></pre> | {
"question_id": 93264,
"question_date": "2008-09-18T14:50:36.493Z",
"question_score": 226,
"tags": "sql-server|tsql",
"answer_id": 93292,
"answer_date": "2008-09-18T14:54:18.310Z",
"answer_score": 345
} |
Please answer the following Stack Overflow question:
Title: Extract digits from a string in Java
<p>I have a Java <code>String</code> object. I need to extract only digits from it. I'll give an example:</p>
<p><code>"123-456-789"</code> I want <code>"123456789"</code></p>
<p>Is there a library function that extracts only digits?</p>
<p>Thanks for the answers. Before I try these I need to know if I have to install any additional llibraries?</p> | <p>You can use regex and delete non-digits.</p>
<pre><code>str = str.replaceAll("\\D+","");
</code></pre> | {
"question_id": 4030928,
"question_date": "2010-10-27T07:41:35.977Z",
"question_score": 226,
"tags": "java|string",
"answer_id": 4030936,
"answer_date": "2010-10-27T07:43:08.330Z",
"answer_score": 605
} |
Please answer the following Stack Overflow question:
Title: Multi-line strings in PHP
<p>Consider:</p>
<pre><code>$xml = "l";
$xml = "vv";
echo $xml;
</code></pre>
<p>This will echo <strong>vv</strong>. Why and how can I do multi-line strings for things like <a href="https://en.wikipedia.org/wiki/SimpleXML">SimpleXML</a>, etc.?</p> | <p>Well,</p>
<pre><code>$xml = "l
vv";
</code></pre>
<p>Works.</p>
<p>You can also use the following:</p>
<pre><code>$xml = "l\nvv";
</code></pre>
<p>or</p>
<pre><code>$xml = <<<XML
l
vv
XML;
</code></pre>
<hr>
<h2>Edit based on comment:</h2>
<p>You can concatenate strings using the <code>.=</code> operator.</p>
<pre><code>$str = "Hello";
$str .= " World";
echo $str; //Will echo out "Hello World";
</code></pre> | {
"question_id": 9744192,
"question_date": "2012-03-16T20:37:04.670Z",
"question_score": 226,
"tags": "php|string",
"answer_id": 9744216,
"answer_date": "2012-03-16T20:39:09.257Z",
"answer_score": 378
} |
Please answer the following Stack Overflow question:
Title: How do I initialize weights in PyTorch?
<p>How do I initialize weights and biases of a network (via e.g. He or Xavier initialization)?</p> | <h1>Single layer</h1>
<p>To initialize the weights of a single layer, use a function from <a href="https://pytorch.org/docs/master/nn.init.html" rel="noreferrer"><code>torch.nn.init</code></a>. For instance:</p>
<pre><code>conv1 = torch.nn.Conv2d(...)
torch.nn.init.xavier_uniform(conv1.weight)
</code></pre>
<p>Alternatively, you can modify the parameters by writing to <code>conv1.weight.data</code> (which is a <a href="http://pytorch.org/docs/master/tensors.html#torch.Tensor" rel="noreferrer"><code>torch.Tensor</code></a>). Example:</p>
<pre><code>conv1.weight.data.fill_(0.01)
</code></pre>
<p>The same applies for biases:</p>
<pre><code>conv1.bias.data.fill_(0.01)
</code></pre>
<h2><code>nn.Sequential</code> or custom <code>nn.Module</code></h2>
<p>Pass an initialization function to <a href="http://pytorch.org/docs/master/nn.html#torch.nn.Module.apply" rel="noreferrer"><code>torch.nn.Module.apply</code></a>. It will initialize the weights in the entire <code>nn.Module</code> recursively.</p>
<blockquote>
<p><strong>apply(<em>fn</em>):</strong> Applies <code>fn</code> recursively to every submodule (as returned by <code>.children()</code>) as well as self. Typical use includes initializing the parameters of a model (see also torch-nn-init).</p>
</blockquote>
<p>Example:</p>
<pre><code>def init_weights(m):
if isinstance(m, nn.Linear):
torch.nn.init.xavier_uniform(m.weight)
m.bias.data.fill_(0.01)
net = nn.Sequential(nn.Linear(2, 2), nn.Linear(2, 2))
net.apply(init_weights)
</code></pre> | {
"question_id": 49433936,
"question_date": "2018-03-22T16:34:42.580Z",
"question_score": 226,
"tags": "python|machine-learning|deep-learning|neural-network|pytorch",
"answer_id": 49433937,
"answer_date": "2018-03-22T16:34:42.580Z",
"answer_score": 300
} |
Please answer the following Stack Overflow question:
Title: Date ticks and rotation in matplotlib
<p>I am having an issue trying to get my date ticks rotated in matplotlib. A small sample program is below. If I try to rotate the ticks at the end, the ticks do not get rotated. If I try to rotate the ticks as shown under the comment 'crashes', then matplot lib crashes. </p>
<p>This only happens if the x-values are dates. If I replaces the variable <code>dates</code> with the variable <code>t</code> in the call to <code>avail_plot</code>, the <code>xticks(rotation=70)</code> call works just fine inside <code>avail_plot</code>. </p>
<p>Any ideas? </p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
def avail_plot(ax, x, y, label, lcolor):
ax.plot(x,y,'b')
ax.set_ylabel(label, rotation='horizontal', color=lcolor)
ax.get_yaxis().set_ticks([])
#crashes
#plt.xticks(rotation=70)
ax2 = ax.twinx()
ax2.plot(x, [1 for a in y], 'b')
ax2.get_yaxis().set_ticks([])
ax2.set_ylabel('testing')
f, axs = plt.subplots(2, sharex=True, sharey=True)
t = np.arange(0.01, 5, 1)
s1 = np.exp(t)
start = dt.datetime.now()
dates=[]
for val in t:
next_val = start + dt.timedelta(0,val)
dates.append(next_val)
start = next_val
avail_plot(axs[0], dates, s1, 'testing', 'green')
avail_plot(axs[1], dates, s1, 'testing2', 'red')
plt.subplots_adjust(hspace=0, bottom=0.3)
plt.yticks([0.5,],("",""))
#doesn't crash, but does not rotate the xticks
#plt.xticks(rotation=70)
plt.show()
</code></pre> | <p>If you prefer a non-object-oriented approach, move <code>plt.xticks(rotation=70)</code> to right <em>before</em> the two <code>avail_plot</code> calls, eg</p>
<pre><code>plt.xticks(rotation=70)
avail_plot(axs[0], dates, s1, 'testing', 'green')
avail_plot(axs[1], dates, s1, 'testing2', 'red')
</code></pre>
<p>This sets the rotation property before setting up the labels. Since you have two axes here, <code>plt.xticks</code> gets confused after you've made the two plots. At the point when <code>plt.xticks</code> doesn't do anything, <code>plt.gca()</code> does <em>not</em> give you the axes you want to modify, and so <code>plt.xticks</code>, which acts on the current axes, is not going to work.</p>
<p>For an object-oriented approach not using <code>plt.xticks</code>, you can use</p>
<pre><code>plt.setp( axs[1].xaxis.get_majorticklabels(), rotation=70 )
</code></pre>
<p><em>after</em> the two <code>avail_plot</code> calls. This sets the rotation on the correct axes specifically.</p> | {
"question_id": 11264521,
"question_date": "2012-06-29T15:22:18.987Z",
"question_score": 226,
"tags": "python|matplotlib",
"answer_id": 11269325,
"answer_date": "2012-06-29T21:40:03.377Z",
"answer_score": 297
} |
Please answer the following Stack Overflow question:
Title: Find the unique values in a column and then sort them
<p>I have a pandas dataframe. I want to print the unique values of one of its columns in ascending order. This is how I am doing it:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
print a.sort()
</code></pre>
<p>The problem is that I am getting a <code>None</code> for the output.</p> | <p><a href="https://docs.python.org/3/library/functions.html#sorted" rel="noreferrer"><code>sorted(iterable)</code></a>: Return a new sorted list from the items in <em>iterable</em>.
<bR><br><strong>CODE</strong><br></p>
<pre><code>import pandas as pd
df = pd.DataFrame({'A':[1,1,3,2,6,2,8]})
a = df['A'].unique()
print(sorted(a))
</code></pre>
<p><strong>OUTPUT</strong></p>
<pre><code>[1, 2, 3, 6, 8]
</code></pre> | {
"question_id": 32072076,
"question_date": "2015-08-18T12:10:49.053Z",
"question_score": 226,
"tags": "python|pandas|sorting|dataframe|unique",
"answer_id": 32072252,
"answer_date": "2015-08-18T12:18:58.840Z",
"answer_score": 306
} |
Please answer the following Stack Overflow question:
Title: Random String Generator Returning Same String
<p>I've developed a random string generator but it's not behaving quite as I'm hoping. My goal is to be able to run this twice and generate two distinct four character random strings. However, it just generates one four character random string twice.</p>
<p>Here's the code and an example of its output:</p>
<pre><code>private string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
// get 1st random string
string Rand1 = RandomString(4);
// get 2nd random string
string Rand2 = RandomString(4);
// create full rand string
string docNum = Rand1 + "-" + Rand2;
</code></pre>
<p>...and the output looks like this: UNTE-UNTE
...but it should look something like this UNTE-FWNU</p>
<p>How can I ensure two distinctly random strings?</p> | <p>You're making the Random instance in the method, which causes it to return the same values when called in quick succession. I would do something like this:</p>
<pre><code>private static Random random = new Random((int)DateTime.Now.Ticks);//thanks to McAden
private string RandomString(int size)
{
StringBuilder builder = new StringBuilder();
char ch;
for (int i = 0; i < size; i++)
{
ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return builder.ToString();
}
// get 1st random string
string Rand1 = RandomString(4);
// get 2nd random string
string Rand2 = RandomString(4);
// creat full rand string
string docNum = Rand1 + "-" + Rand2;
</code></pre>
<p>(modified version of your code)</p> | {
"question_id": 1122483,
"question_date": "2009-07-13T22:38:54.447Z",
"question_score": 226,
"tags": "c#|random",
"answer_id": 1122519,
"answer_date": "2009-07-13T22:49:28.480Z",
"answer_score": 309
} |
Please answer the following Stack Overflow question:
Title: Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; }
<p>I have some vanilla javascript code that takes a string input, splits the string into characters, and then matches those characters to a key on an object.</p>
<pre><code>DNATranscriber = {
"G":"C",
"C": "G",
"T": "A",
"A": "U"
}
function toRna(sequence){
const sequenceArray = [...sequence];
const transcriptionArray = sequenceArray.map(character =>{
return this.DNATranscriber[character];
});
return transcriptionArray.join("");
}
console.log(toRna("ACGTGGTCTTAA")); //Returns UGCACCAGAAUU
</code></pre>
<p>This works as expected. I'd now like to convert this to typescript. </p>
<pre><code>class Transcriptor {
DNATranscriber = {
G:"C",
C: "G",
T: "A",
A: "U"
}
toRna(sequence: string) {
const sequenceArray = [...sequence];
const transcriptionArray = sequenceArray.map(character =>{
return this.DNATranscriber[character];
});
}
}
export default Transcriptor
</code></pre>
<p>But I'm getting the following error. </p>
<blockquote>
<p>Element implicitly has an 'any' type because expression of type 'string' >can't be used to index type '{ "A": string; }'.
No index signature with a parameter of type 'string' was found on type >'{ "A": string; }'.ts(7053)</p>
</blockquote>
<p>I thought that the issue was that I needed my object key to be a string. But converting them to strings didn't work. </p>
<pre><code>DNATranscriber = {
"G":"C",
"C": "G",
"T": "A",
"A": "U"
}
</code></pre>
<p>I'm quite confused by this. It says that no index signature with a type of string exists on my object. But I'm sure that it does. What am I doing wrong?</p>
<p>Edit - I solved this by giving the DNATranscriber object a type of any.</p>
<pre><code>DNATranscriber: any = {
"G":"C",
"C":"G",
"T":"A",
"A":"U"
}
</code></pre> | <p>You can fix the errors by validating your input, which is something you should do regardless of course.</p>
<p>The following typechecks correctly, via type guarding validations</p>
<pre><code>const DNATranscriber = {
G: 'C',
C: 'G',
T: 'A',
A: 'U'
};
export default class Transcriptor {
toRna(dna: string) {
const codons = [...dna];
if (!isValidSequence(codons)) {
throw Error('invalid sequence');
}
const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
return transcribedRNA;
}
}
function isValidSequence(values: string[]): values is Array<keyof typeof DNATranscriber> {
return values.every(isValidCodon);
}
function isValidCodon(value: string): value is keyof typeof DNATranscriber {
return value in DNATranscriber;
}
</code></pre>
<p>It is worth mentioning that you seem to be under the misapprehention that converting JavaScript to TypeScript involves using classes.</p>
<p>In the following, more idiomatic version, we leverage TypeScript to improve clarity and gain stronger typing of base pair mappings without changing the implementation. We use a <code>function</code>, just like the original, because it makes sense. This is important! Converting JavaScript to TypeScript has nothing to do with classes, it has to do with static types.</p>
<pre><code>const DNATranscriber = {
G: 'C',
C: 'G',
T: 'A',
A: 'U'
};
export default function toRna(dna: string) {
const codons = [...dna];
if (!isValidSequence(codons)) {
throw Error('invalid sequence');
}
const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
return transcribedRNA;
}
function isValidSequence(values: string[]): values is Array<keyof typeof DNATranscriber> {
return values.every(isValidCodon);
}
function isValidCodon(value: string): value is keyof typeof DNATranscriber {
return value in DNATranscriber;
}
</code></pre>
<p><strong>Update</strong>:</p>
<p>Since TypeScript 3.7, we can write this more expressively, formalizing the correspondence between input validation and its type implication using <em>assertion signatures</em>.</p>
<pre><code>const DNATranscriber = {
G: 'C',
C: 'G',
T: 'A',
A: 'U'
} as const;
type DNACodon = keyof typeof DNATranscriber;
type RNACodon = typeof DNATranscriber[DNACodon];
export default function toRna(dna: string): RNACodon[] {
const codons = [...dna];
validateSequence(codons);
const transcribedRNA = codons.map(codon => DNATranscriber[codon]);
return transcribedRNA;
}
function validateSequence(values: string[]): asserts values is DNACodon[] {
if (!values.every(isValidCodon)) {
throw Error('invalid sequence');
}
}
function isValidCodon(value: string): value is DNACodon {
return value in DNATranscriber;
}
</code></pre>
<p>You can read more about <em>assertion signatures</em> in the <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html" rel="noreferrer">TypeScript 3.7 release notes</a>.</p> | {
"question_id": 56568423,
"question_date": "2019-06-12T18:33:58.783Z",
"question_score": 226,
"tags": "javascript|typescript",
"answer_id": 56569217,
"answer_date": "2019-06-12T19:33:14.277Z",
"answer_score": 99
} |
Please answer the following Stack Overflow question:
Title: Angular 2: 404 error occur when I refresh through the browser
<p>I'm new to Angular 2. I have stored my single-page application in my server within a folder named as "myapp". I have changed the URL in the base to <a href="http://example.com/myapp/%60" rel="noreferrer">http://example.com/myapp/`</a>.</p>
<p>My project has two pages. So I implement Angular 2 routing. I set the default page as login. When I type <code>http://example.com/myapp/</code> in my browser it will redirect automatically to <code>http://example.com/myapp/login</code>. But if refresh that page I get a <code>404</code> error, saying that <code>http://example.com/myapp/login</code> is not found.</p>
<p>But if I run my project using the lite server everything is working. In this case the base URL in index.html will be <code>"/"</code>. How do fix it?</p> | <p>In fact, it's normal that you have a 404 error when refreshing your application since the actual address within the browser is updating (and without # / hashbang approach). By default, HTML5 history is used for reusing in Angular2.</p>
<p>To fix the 404 error, you need to update your server to serve the <code>index.html</code> file for each route path you defined.</p>
<p>If you want to switch to the HashBang approach, you need to use this configuration:</p>
<pre class="lang-js prettyprint-override"><code>import {bootstrap} from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {LocationStrategy, HashLocationStrategy} from '@angular/common';
import {MyApp} from './myapp';
bootstrap(MyApp, [
ROUTER_PROVIDERS,
{provide: LocationStrategy, useClass: HashLocationStrategy}
]);
</code></pre>
<p>In this case, when you refresh the page, it will be displayed again (but you will have a <code>#</code> in your address).</p>
<p>This link could help you as well: <a href="https://stackoverflow.com/questions/34415725/when-i-refresh-my-website-i-get-a-404-this-is-with-angular2-and-firebase/">When I refresh my website I get a 404. This is with Angular2 and firebase</a>.</p>
<p>Hope it helps you,
Thierry</p> | {
"question_id": 35284988,
"question_date": "2016-02-09T06:04:17.920Z",
"question_score": 226,
"tags": "angular|angular2-routing",
"answer_id": 35285068,
"answer_date": "2016-02-09T06:09:41.707Z",
"answer_score": 152
} |
Please answer the following Stack Overflow question:
Title: How to update only one field using Entity Framework?
<p>Here's the table</p>
<p><strong>Users</strong></p>
<pre><code>UserId
UserName
Password
EmailAddress
</code></pre>
<p>and the code..</p>
<pre class="lang-csharp prettyprint-override"><code>public void ChangePassword(int userId, string password){
//code to update the password..
}
</code></pre> | <p>Ladislav's answer updated to use DbContext (introduced in EF 4.1):</p>
<pre class="lang-cs prettyprint-override"><code>public void ChangePassword(int userId, string password)
{
var user = new User() { Id = userId, Password = password };
using (var db = new MyEfContextName())
{
db.Users.Attach(user);
db.Entry(user).Property(x => x.Password).IsModified = true;
db.SaveChanges();
}
}
</code></pre> | {
"question_id": 3642371,
"question_date": "2010-09-04T12:56:59.073Z",
"question_score": 226,
"tags": "sql|entity-framework-4|entity|field|dbcontext",
"answer_id": 5567616,
"answer_date": "2011-04-06T14:02:24.373Z",
"answer_score": 420
} |
Please answer the following Stack Overflow question:
Title: IIS7 deployment - duplicate 'system.web.extensions/scripting/scriptResourceHandler' section
<p>On attempting to deploy a .net 3.5 website on the default app pool in IIS7 having the framework section set to 4.0, I get the following error.</p>
<blockquote>
<p>There is a duplicate
'system.web.extensions/scripting/scriptResourceHandler' section
defined.</p>
</blockquote>
<p>Commenting off the offending lines didn't help either. Any pointers on what I need to do or look at?</p> | <p>If your plan is to deploy to an IIS that has an Application Pool running in .net 4.0 you will need to cleanup the web.config that includes all the section Definitions that point to .net 3.5. The reason this fails is because these section definitions are already included in the root web.config in .NET 4.0 (see %windir%\microsoft.net\framework\v4.0.30319\config\machine.config) that include all the system.web.extensions declared already.</p>
<p>Another quick fix is to have the application pool set to 2.0 just as your development machine appears to have,.</p> | {
"question_id": 3387322,
"question_date": "2010-08-02T11:38:20.827Z",
"question_score": 226,
"tags": "asp.net|deployment|iis-7",
"answer_id": 3402442,
"answer_date": "2010-08-04T03:48:37.600Z",
"answer_score": 360
} |
Please answer the following Stack Overflow question:
Title: How to Select Columns in Editors (Atom,Notepad++, Kate, VIM, Sublime, Textpad,etc) and IDEs (NetBeans, IntelliJ IDEA, Eclipse, Visual Studio, etc)
<p>How to select columns in Editors and IDEs to columnar delete, insert or replace some characters ?</p>
<p>Editors:</p>
<ul>
<li>Atom</li>
<li>Notepad++</li>
<li>Kate</li>
<li>VIM</li>
<li>Sublime</li>
<li>Emacs</li>
<li>Textpad</li>
<li>Emerald Editor</li>
<li>UltraEdit</li>
<li>MCEdit</li>
<li>jEdit</li>
<li>Nedit</li>
</ul>
<p>IDEs:</p>
<ul>
<li>NetBeans</li>
<li>Eclipse</li>
<li>Visual Studio</li>
<li>IntelliJ IDEA</li>
<li>Flash Builder</li>
<li>Aptana Studio</li>
</ul> | <ul>
<li>Notepad++, Visual Studio, and some others: <kbd>Alt</kbd> + <kbd>drag</kbd>.</li>
<li>vim: <kbd>Ctrl</kbd> + <kbd>v</kbd> or (bizarrely enough) Quad-click-drag. In windows: <kbd>Ctrl</kbd> + <kbd>Q</kbd> (since <kbd>Ctrl</kbd> + <kbd>V</kbd> is the standard for paste)</li>
</ul> | {
"question_id": 1802616,
"question_date": "2009-11-26T09:38:43.973Z",
"question_score": 226,
"tags": "ide|editor",
"answer_id": 1802634,
"answer_date": "2009-11-26T09:42:58.350Z",
"answer_score": 221
} |
Please answer the following Stack Overflow question:
Title: How to list all the available keyspaces in Cassandra?
<p>I am newbie in Cassandra and trying to implement one toy application using Cassandra. I had created one keyspace and few column families in my Cassandra DB but I forgot the name of my cluster.</p>
<p>I am trying to find if there is any query which can list down all the available keyspaces.</p>
<p>Anybody knows such a query or command?</p> | <p>If you want to do this outside of the <code>cqlsh</code> tool you can query the <code>schema_keyspaces</code> table in the <code>system</code> keyspace. There's also a table called <code>schema_columnfamilies</code> which contains information about all tables.</p>
<p>The <code>DESCRIBE</code> and <code>SHOW</code> commands only work in <code>cqlsh</code> and <code>cassandra-cli</code>.</p> | {
"question_id": 18712967,
"question_date": "2013-09-10T07:28:35.880Z",
"question_score": 226,
"tags": "cassandra|cassandra-cli",
"answer_id": 18749576,
"answer_date": "2013-09-11T19:23:34.520Z",
"answer_score": 104
} |
Please answer the following Stack Overflow question:
Title: Specifying and saving a figure with exact size in pixels
<p>Say I have an image of size 3841 x 7195 pixels. I would like to save the contents of the figure to disk, resulting in an image of the <strong>exact size</strong> I specify in pixels.</p>
<p>No axis, no titles. Just the image. I don't personally care about DPIs, as I only want to specify the size the image takes in the screen in disk <strong>in pixels</strong>.</p>
<p>I have read <a href="https://stackoverflow.com/search?q=figure%20size%20matplotlib">other</a> <a href="https://stackoverflow.com/questions/8775622/exact-figure-size-in-matplotlib-with-title-axis-labels">threads</a>, and they all seem to do conversions to inches and then specify the dimensions of the figure in inches and adjust dpi's in some way. I would like to avoid dealing with the potential loss of accuracy that could result from pixel-to-inches conversions.</p>
<p>I have tried with:</p>
<pre><code>w = 7195
h = 3841
fig = plt.figure(frameon=False)
fig.set_size_inches(w,h)
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)
ax.imshow(im_np, aspect='normal')
fig.savefig(some_path, dpi=1)
</code></pre>
<p>with no luck (Python complains that width and height must each be below 32768 (?))</p>
<p>From everything I have seen, <code>matplotlib</code> requires the figure size to be specified in <code>inches</code> and <code>dpi</code>, but I am only interested in <strong>the pixels</strong> the figure takes in disk. How can I do this?</p>
<p>To clarify: I am looking for a way to do this with <code>matplotlib</code>, and not with other image-saving libraries.</p> | <p>Matplotlib doesn't work with pixels directly, but rather physical sizes and DPI. If you want to display a figure with a certain pixel size, you need to know the DPI of your monitor. For example <a href="http://www.infobyip.com/detectmonitordpi.php" rel="noreferrer">this link</a> will detect that for you.</p>
<p>If you have an image of 3841x7195 pixels it is unlikely that you monitor will be that large, so you won't be able to show a figure of that size (matplotlib requires the figure to fit in the screen, if you ask for a size too large it will shrink to the screen size). Let's imagine you want an 800x800 pixel image just for an example. Here's how to show an 800x800 pixel image in my monitor (<code>my_dpi=96</code>):</p>
<pre><code>plt.figure(figsize=(800/my_dpi, 800/my_dpi), dpi=my_dpi)
</code></pre>
<p>So you basically just divide the dimensions in inches by your DPI. </p>
<p>If you want to save a figure of a specific size, then it is a different matter. Screen DPIs are not so important anymore (unless you ask for a figure that won't fit in the screen). Using the same example of the 800x800 pixel figure, we can save it in different resolutions using the <code>dpi</code> keyword of <code>savefig</code>. To save it in the same resolution as the screen just use the same dpi:</p>
<pre><code>plt.savefig('my_fig.png', dpi=my_dpi)
</code></pre>
<p>To to save it as an 8000x8000 pixel image, use a dpi 10 times larger:</p>
<pre><code>plt.savefig('my_fig.png', dpi=my_dpi * 10)
</code></pre>
<p>Note that the setting of the DPI is not supported by all backends. Here, the PNG backend is used, but the pdf and ps backends will implement the size differently. Also, changing the DPI and sizes will also affect things like fontsize. A larger DPI will keep the same relative sizes of fonts and elements, but if you want smaller fonts for a larger figure you need to increase the physical size instead of the DPI. </p>
<p>Getting back to your example, if you want to save a image with 3841 x 7195 pixels, you could do the following:</p>
<pre><code>plt.figure(figsize=(3.841, 7.195), dpi=100)
( your code ...)
plt.savefig('myfig.png', dpi=1000)
</code></pre>
<p>Note that I used the figure dpi of 100 to fit in most screens, but saved with <code>dpi=1000</code> to achieve the required resolution. In my system this produces a png with 3840x7190 pixels -- it seems that the DPI saved is always 0.02 pixels/inch smaller than the selected value, which will have a (small) effect on large image sizes. Some more discussion of this <a href="https://stackoverflow.com/questions/8775622/exact-figure-size-in-matplotlib-with-title-axis-labels">here</a>.</p> | {
"question_id": 13714454,
"question_date": "2012-12-05T00:34:49.690Z",
"question_score": 226,
"tags": "python|matplotlib|scipy",
"answer_id": 13714720,
"answer_date": "2012-12-05T01:04:51.907Z",
"answer_score": 246
} |
Please answer the following Stack Overflow question:
Title: How to play a sound using Swift?
<p>I would like to play a sound using Swift.</p>
<p>My code worked in Swift 1.0 but now it doesn't work anymore in Swift 2 or newer.</p>
<pre><code>override func viewDidLoad() {
super.viewDidLoad()
let url:NSURL = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: url, fileTypeHint: nil)
} catch _{
return
}
bgMusic.numberOfLoops = 1
bgMusic.prepareToPlay()
if (Data.backgroundMenuPlayed == 0){
player.play()
Data.backgroundMenuPlayed = 1
}
}
</code></pre> | <p><strong>Most preferably you might want to use <a href="https://developer.apple.com/av-foundation/" rel="noreferrer">AVFoundation</a>.
It provides all the essentials for working with audiovisual media.</strong></p>
<blockquote>
<p><strong>Update:</strong> Compatible with <strong>Swift 2</strong>, <strong>Swift 3</strong> and <strong>Swift 4</strong> as suggested by some of you in the comments.</p>
</blockquote>
<hr>
<h2>Swift 2.3</h2>
<pre><code>import AVFoundation
var player: AVAudioPlayer?
func playSound() {
let url = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOfURL: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
}
</code></pre>
<hr>
<h2>Swift 3</h2>
<pre><code>import AVFoundation
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
let player = try AVAudioPlayer(contentsOf: url)
player.play()
} catch let error {
print(error.localizedDescription)
}
}
</code></pre>
<hr>
<h2>Swift 4 (iOS 13 compatible)</h2>
<pre><code>import AVFoundation
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
</code></pre>
<blockquote>
<p><em>Make sure to change the name of your tune as well as the <a href="http://wikipedia.org/wiki/Audio_file_format" rel="noreferrer">extension</a>.</em>
<em>The file needs to be properly imported (<code>Project Build Phases</code> > <code>Copy Bundle Resources</code>). You might want to place it in <code>assets.xcassets</code> for
greater convenience.</em></p>
</blockquote>
<p><em>For short sound files you might want to go for non-compressed audio formats such as <code>.wav</code> since they have the best quality and a low cpu impact. The higher disk-space consumption should not be a big deal for short sound files. The longer the files are, you might want to go for a compressed format such as <code>.mp3</code> etc. pp. Check the <a href="https://developer.apple.com/library/content/documentation/MusicAudio/Conceptual/CoreAudioOverview/SupportedAudioFormatsMacOSX/SupportedAudioFormatsMacOSX.html" rel="noreferrer">compatible audio formats</a> of <code>CoreAudio</code>.</em></p>
<hr>
<p><strong>Fun-fact:</strong> There are neat little libraries which make playing sounds even easier. :) <br>
For example: <a href="https://github.com/adamcichy/SwiftySound" rel="noreferrer">SwiftySound</a></p> | {
"question_id": 32036146,
"question_date": "2015-08-16T14:25:37.587Z",
"question_score": 226,
"tags": "ios|swift|avfoundation",
"answer_id": 32036291,
"answer_date": "2015-08-16T14:41:08.950Z",
"answer_score": 421
} |
Please answer the following Stack Overflow question:
Title: How to escape double quotes in a title attribute
<p>I am trying to use a string that contains double quotes in the title attribute of an anchor. So far I tried these:</p>
<pre><code><a href=".." title="Some \"text\"">Some text</a>
<!-- The title looks like `Some \` --!>
</code></pre>
<p>and</p>
<pre><code><a href=".." title="Some &quot;text&quot;">Some text</a>
<!-- The title looks like `Some ` --!>
</code></pre>
<p>Please note that using single quotes is <em>not</em> an option.</p> | <p>This variant - </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><a title="Some &quot;text&quot;">Hover me</a></code></pre>
</div>
</div>
</p>
<p>Is correct and it works as expected - you see normal quotes in rendered page.</p> | {
"question_id": 3752769,
"question_date": "2010-09-20T15:10:21.263Z",
"question_score": 226,
"tags": "html|escaping|quotes",
"answer_id": 3752794,
"answer_date": "2010-09-20T15:13:17.387Z",
"answer_score": 347
} |
Please answer the following Stack Overflow question:
Title: Unable to find a @SpringBootConfiguration when doing a JpaTest
<p>I'm new to frameworks (just passed the class) and this is my first time using Spring Boot.</p>
<p>I'm trying to run a simple Junit test to see if my CrudRepositories are indeed working.</p>
<p>The error I keep getting is:</p>
<blockquote>
<p>Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
java.lang.IllegalStateException</p>
</blockquote>
<p>Doesn't Spring Boot configure itself?</p>
<p>My Test Class:</p>
<pre><code>@RunWith(SpringRunner.class)
@DataJpaTest
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class JpaTest {
@Autowired
private AccountRepository repository;
@After
public void clearDb(){
repository.deleteAll();
}
@Test
public void createAccount(){
long id = 12;
Account u = new Account(id,"Tim Viz");
repository.save(u);
assertEquals(repository.findOne(id),u);
}
@Test
public void findAccountByUsername(){
long id = 12;
String username = "Tim Viz";
Account u = new Account(id,username);
repository.save(u);
assertEquals(repository.findByUsername(username),u);
}
</code></pre>
<p>My Spring Boot application starter:</p>
<pre><code>@SpringBootApplication
@EnableJpaRepositories(basePackages = {"domain.repositories"})
@ComponentScan(basePackages = {"controllers","domain"})
@EnableWebMvc
@PropertySources(value {@PropertySource("classpath:application.properties")})
@EntityScan(basePackages={"domain"})
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
}
}
</code></pre>
<p>My Repository:</p>
<pre><code>public interface AccountRepository extends CrudRepository<Account,Long> {
public Account findByUsername(String username);
}
}
</code></pre> | <p>Indeed, Spring Boot does set itself up for the most part. You can probably already get rid of a lot of the code you posted, especially in <code>Application</code>.</p>
<p>I wish you had included the package names of all your classes, or at least the ones for <code>Application</code> and <code>JpaTest</code>. The thing about <code>@DataJpaTest</code> and a few other annotations is that they look for a <code>@SpringBootConfiguration</code> annotation in the current package, and if they cannot find it there, they traverse the package hierarchy until they find it.</p>
<p>For example, if the fully qualified name for your test class was <code>com.example.test.JpaTest</code> and the one for your application was <code>com.example.Application</code>, then your test class would be able to find the <code>@SpringBootApplication</code> (and therein, the <code>@SpringBootConfiguration</code>).</p>
<p>If the application resided in a different branch of the package hierarchy, however, like <code>com.example.application.Application</code>, it would <em>not</em> find it.</p>
<h2>Example</h2>
<p>Consider the following Maven project:</p>
<pre><code>my-test-project
+--pom.xml
+--src
+--main
+--com
+--example
+--Application.java
+--test
+--com
+--example
+--test
+--JpaTest.java
</code></pre>
<p>And then the following content in <code>Application.java</code>:</p>
<pre><code>package com.example;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
</code></pre>
<p>Followed by the contents of <code>JpaTest.java</code>:</p>
<pre><code>package com.example.test;
@RunWith(SpringRunner.class)
@DataJpaTest
public class JpaTest {
@Test
public void testDummy() {
}
}
</code></pre>
<p>Everything should be working. If you create a new folder inside <code>src/main/com/example</code> called <code>app</code>, and then put your <code>Application.java</code> inside it (and update the <code>package</code> declaration inside the file), running the test will give you the following error:</p>
<blockquote>
<p>java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test</p>
</blockquote> | {
"question_id": 39084491,
"question_date": "2016-08-22T16:30:02.070Z",
"question_score": 226,
"tags": "java|spring|junit|spring-boot|spring-data",
"answer_id": 39084906,
"answer_date": "2016-08-22T16:56:00.553Z",
"answer_score": 337
} |
Please answer the following Stack Overflow question:
Title: Java Swing revalidate() vs repaint()
<p>I'm putting together a Swing application where I often want to replace the contents of a JPanel. To do this, I'm calling <code>removeAll()</code>, then adding my new content, then calling <code>revalidate()</code>.</p>
<p>However I'm finding that the old content is still actually visible (though obscured by the the new content). If I add a call to <code>repaint()</code> in addition to <code>revalidate()</code>, it works as expected.</p>
<p>I'm sure on other occasions I've experienced that just calling <code>revalidate()</code> is enough.</p>
<p>So basically my question is - should I need to call both functions and if not, when should I call each of them?</p> | <p>You need to call <code>repaint()</code> and <code>revalidate()</code>. The former tells Swing that an area of the window is dirty (which is necessary to erase the image of the old children removed by <code>removeAll()</code>); the latter tells the layout manager to recalculate the layout (which is necessary when adding components). This should cause <em>children</em> of the panel to repaint, but may not cause the panel itself to do so (see <a href="http://www.oracle.com/technetwork/java/painting-140037.html#triggers" rel="noreferrer">this</a> for the list of repaint triggers).</p>
<p>On a more general note: rather than reusing the original panel, I'd recommend building a new panel and swapping them at the parent.</p> | {
"question_id": 1097366,
"question_date": "2009-07-08T10:58:31.633Z",
"question_score": 226,
"tags": "java|swing",
"answer_id": 1097544,
"answer_date": "2009-07-08T11:43:56.423Z",
"answer_score": 171
} |
Please answer the following Stack Overflow question:
Title: How to assert a type of an HTMLElement in TypeScript?
<p>I'm trying to do this:</p>
<pre><code>var script:HTMLScriptElement = document.getElementsByName("script")[0];
alert(script.type);
</code></pre>
<p>but it's giving me an error:</p>
<pre><code>Cannot convert 'Node' to 'HTMLScriptElement': Type 'Node' is missing property 'defer' from type 'HTMLScriptElement'
(elementName: string) => NodeList
</code></pre>
<p>I can't access the 'type' member of the script element unless I cast it to the correct type, but I don't know how to do this. I searched the docs & samples, but I couldn't find anything.</p> | <p>TypeScript uses '<>' to surround casts, so the above becomes:</p>
<pre><code>var script = <HTMLScriptElement>document.getElementsByName("script")[0];
</code></pre>
<p>However, unfortunately you cannot do:</p>
<pre><code>var script = (<HTMLScriptElement[]>document.getElementsByName(id))[0];
</code></pre>
<p>You get the error</p>
<pre><code>Cannot convert 'NodeList' to 'HTMLScriptElement[]'
</code></pre>
<p>But you can do : </p>
<pre><code>(<HTMLScriptElement[]><any>document.getElementsByName(id))[0];
</code></pre> | {
"question_id": 12686927,
"question_date": "2012-10-02T08:33:05.020Z",
"question_score": 226,
"tags": "typescript|type-assertion|typescript-types|typescript-lib-dom",
"answer_id": 12687137,
"answer_date": "2012-10-02T08:47:36.087Z",
"answer_score": 285
} |
Please answer the following Stack Overflow question:
Title: How to hide close button in WPF window?
<p>I'm writing a modal dialog in WPF. How do I set a WPF window to not have a close button? I'd still like for its <code>WindowState</code> to have a normal title bar.</p>
<p>I found <code>ResizeMode</code>, <code>WindowState</code>, and <code>WindowStyle</code>, but none of those properties allow me to hide the close button but show the title bar, as in modal dialogs.</p> | <p>WPF doesn't have a built-in property to hide the title bar's Close button, but you can do it with a few lines of P/Invoke.</p>
<p>First, add these declarations to your Window class:</p>
<pre class="lang-cs prettyprint-override"><code>private const int GWL_STYLE = -16;
private const int WS_SYSMENU = 0x80000;
[DllImport("user32.dll", SetLastError = true)]
private static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
</code></pre>
<p>Then put this code in the Window's <code>Loaded</code> event:</p>
<pre class="lang-cs prettyprint-override"><code>var hwnd = new WindowInteropHelper(this).Handle;
SetWindowLong(hwnd, GWL_STYLE, GetWindowLong(hwnd, GWL_STYLE) & ~WS_SYSMENU);
</code></pre>
<p>And there you go: no more Close button. You also won't have a window icon on the left side of the title bar, which means no system menu, even when you right-click the title bar - they all go together.</p>
<p>Important note: <strong>all this does is hide the button.</strong> The user can still close the window! If the user presses <kbd>Alt</kbd>+<kbd>F4</kbd>, or closes the app via the taskbar, the window will still close.</p>
<p>If you don't want to allow the window to close before the background thread is done, then you could also override <code>OnClosing</code> and set <code>Cancel</code> to true, as Gabe suggested.</p> | {
"question_id": 743906,
"question_date": "2009-04-13T13:39:08.173Z",
"question_score": 226,
"tags": "c#|wpf|xaml|button|dialog",
"answer_id": 958980,
"answer_date": "2009-06-06T04:15:13.733Z",
"answer_score": 294
} |
Please answer the following Stack Overflow question:
Title: How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?
<p>I'm using the PostgreSQL database for my Ruby on Rails application (on Mac OS X 10.9).</p>
<p>Are there any detailed instructions on how to upgrade PostgreSQL database?</p>
<p>I'm afraid I will destroy the data in the database or mess it up.</p> | <p>Assuming you've used home-brew to install and upgrade Postgres, you can perform the following steps.</p>
<ol>
<li><p>Stop current Postgres server:</p>
<p><code>launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist</code></p></li>
<li><p>Initialize a new 10.1 database:</p>
<p><code>initdb /usr/local/var/postgres10.1 -E utf8</code></p></li>
<li><p>run <code>pg_upgrade</code> <em>(note: change bin version if you're upgrading from something other than below)</em>:</p>
<pre><code>pg_upgrade -v \
-d /usr/local/var/postgres \
-D /usr/local/var/postgres10.1 \
-b /usr/local/Cellar/postgresql/9.6.5/bin/ \
-B /usr/local/Cellar/postgresql/10.1/bin/
</code></pre>
<p><code>-v</code> to enable verbose internal logging</p>
<p><code>-d</code> the old database cluster configuration directory</p>
<p><code>-D</code> the new database cluster configuration directory</p>
<p><code>-b</code> the old PostgreSQL executable directory</p>
<p><code>-B</code> the new PostgreSQL executable directory</p></li>
<li><p>Move new data into place:</p>
<pre><code>cd /usr/local/var
mv postgres postgres9.6
mv postgres10.1 postgres
</code></pre></li>
<li><p>Restart Postgres:</p>
<p><code>launchctl load ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist</code></p></li>
<li><p>Check <code>/usr/local/var/postgres/server.log</code> for details and to make sure the new server started properly.</p></li>
<li><p>Finally, re-install the rails <code>pg</code> gem</p>
<pre><code>gem uninstall pg
gem install pg
</code></pre></li>
</ol>
<p>I suggest you take some time to read the <a href="https://www.postgresql.org/docs/10/static/upgrading.html" rel="noreferrer">PostgreSQL documentation</a> to understand exactly what you're doing in the above steps to minimize frustrations.</p> | {
"question_id": 24379373,
"question_date": "2014-06-24T06:03:46.113Z",
"question_score": 226,
"tags": "postgresql|upgrade",
"answer_id": 27624397,
"answer_date": "2014-12-23T16:36:09.047Z",
"answer_score": 416
} |
Please answer the following Stack Overflow question:
Title: JMS Topic vs Queues
<p>I was wondering what is the difference between a JMS Queue and JMS Topic.</p>
<p><a href="http://activemq.apache.org/how-does-a-queue-compare-to-a-topic.html" rel="noreferrer">ActiveMQ page</a> says </p>
<blockquote>
<h2>Topics</h2>
<p>In JMS a Topic implements <em>publish and subscribe</em> semantics. When you publish a message it goes to all the subscribers who are
interested - so zero to many subscribers will receive a copy of the
message. Only subscribers who had an active subscription at the time
the broker receives the message will get a copy of the message.</p>
<h2>Queues</h2>
<p>A JMS Queue implements <em>load balancer</em> semantics. A single message will be received by exactly one consumer. If there are no
consumers available at the time the message is sent it will be kept
until a consumer is available that can process the message. If a
consumer receives a message and does not acknowledge it before closing
then the message will be redelivered to another consumer. A queue can
have many consumers with messages <em>load balanced</em> across the available
consumers.</p>
</blockquote>
<p>I want to have 'something' what will send a copy of the message to each subscriber in the same sequence as that in which the message was received by the ActiveMQ broker.</p>
<p>Any thoughts?</p> | <p>That means a topic is appropriate. A queue means a message goes to one and only one possible subscriber. A topic goes to each and every subscriber.</p> | {
"question_id": 5576415,
"question_date": "2011-04-07T05:27:57.357Z",
"question_score": 226,
"tags": "jms|activemq",
"answer_id": 5578058,
"answer_date": "2011-04-07T08:23:32.123Z",
"answer_score": 170
} |
Please answer the following Stack Overflow question:
Title: String vs. StringBuilder
<p>I understand the difference between <code>String</code> and <code>StringBuilder</code> (<code>StringBuilder</code> being mutable) but is there a large performance difference between the two? </p>
<p>The program I’m working on has a lot of case driven string appends (500+). Is using <code>StringBuilder</code> a better choice?</p> | <p>Yes, the performance difference is significant. See the KB article "<a href="http://support.microsoft.com/kb/306822" rel="noreferrer">How to improve string concatenation performance in Visual C#</a>".</p>
<p>I have always tried to code for clarity first, and then optimize for performance later. That's much easier than doing it the other way around! However, having seen the enormous performance difference in my applications between the two, I now think about it a little more carefully. </p>
<p>Luckily, it's relatively straightforward to run performance analysis on your code to see where you're spending the time, and then to modify it to use <code>StringBuilder</code> where needed.</p> | {
"question_id": 73883,
"question_date": "2008-09-16T15:55:54.390Z",
"question_score": 226,
"tags": "c#|.net|performance",
"answer_id": 73929,
"answer_date": "2008-09-16T15:59:58.763Z",
"answer_score": 248
} |
Please answer the following Stack Overflow question:
Title: How to add a new audio (not mixing) into a video using ffmpeg?
<p>I used a command like:</p>
<pre><code>ffmpeg -i video.avi -i audio.mp3 -vcodec codec -acodec codec output_video.avi -newaudio
</code></pre>
<p>in latest version for adding new audio track to video (not mix). </p>
<p>But I updated the ffmpeg to the newest version (<strong>ffmpeg version git-2012-06-16-809d71d</strong>) and now in this version the parameter <code>-newaudio</code> doesn't work.</p>
<p>Tell me please how I can add new audio to my video (not mix) using <code>ffmpeg</code>.</p> | <h1>Replace audio</h1>
<p><a href="https://i.stack.imgur.com/DYx0E.png" rel="noreferrer"><img src="https://i.stack.imgur.com/DYx0E.png" alt="diagram of audio stream replacement" /></a></p>
<pre><code>ffmpeg -i video.mp4 -i audio.wav -map 0:v -map 1:a -c:v copy -shortest output.mp4
</code></pre>
<ul>
<li>The <code>-map</code> option allows you to manually select streams / tracks. See <a href="https://trac.ffmpeg.org/wiki/Map" rel="noreferrer">FFmpeg Wiki: Map</a> for more info.</li>
<li>This example uses <code>-c:v copy</code> to <a href="http://ffmpeg.org/ffmpeg.html#Stream-copy" rel="noreferrer">stream copy</a> (mux) the video. No re-encoding of the video occurs. Quality is preserved and the process is fast.
<ul>
<li>If your input audio format is compatible with the output format then change <code>-c:v copy</code> to <code>-c copy</code> to stream copy <strong>both</strong> the video and audio.</li>
<li>If you want to re-encode video and audio then remove <code>-c:v copy</code> / <code>-c copy</code>.</li>
</ul>
</li>
<li>The <code>-shortest</code> option will make the output the same duration as the shortest input.</li>
</ul>
<h1>Add audio</h1>
<p><a href="https://i.stack.imgur.com/eyCVy.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eyCVy.png" alt="diagram of audio stream addition" /></a></p>
<pre><code>ffmpeg -i video.mkv -i audio.mp3 -map 0 -map 1:a -c:v copy -shortest output.mkv
</code></pre>
<ul>
<li>The <code>-map</code> option allows you to manually select streams / tracks. See <a href="https://trac.ffmpeg.org/wiki/Map" rel="noreferrer">FFmpeg Wiki: Map</a> for more info.</li>
<li>This example uses <code>-c:v copy</code> to <a href="http://ffmpeg.org/ffmpeg.html#Stream-copy" rel="noreferrer">stream copy</a> (mux) the video. No re-encoding of the video occurs. Quality is preserved and the process is fast.
<ul>
<li>If your input audio format is compatible with the output format then change <code>-c:v copy</code> to <code>-c copy</code> to stream copy <strong>both</strong> the video and audio.</li>
<li>If you want to re-encode video and audio then remove <code>-c:v copy</code> / <code>-c copy</code>.</li>
</ul>
</li>
<li>The <code>-shortest</code> option will make the output the same duration as the shortest input.</li>
</ul>
<h1>Mixing/combining two audio inputs into one</h1>
<p><a href="https://i.stack.imgur.com/2P6Ls.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2P6Ls.png" alt="diagram of audio downmix" /></a></p>
<p>Use video from <code>video.mkv</code>. Mix audio from <code>video.mkv</code> and <code>audio.m4a</code> using the <a href="http://ffmpeg.org/ffmpeg-filters.html#amerge" rel="noreferrer">amerge filter</a>:</p>
<pre><code>ffmpeg -i video.mkv -i audio.m4a -filter_complex "[0:a][1:a]amerge=inputs=2[a]" -map 0:v -map "[a]" -c:v copy -ac 2 -shortest output.mkv
</code></pre>
<p>See <a href="https://trac.ffmpeg.org/wiki/AudioChannelManipulation" rel="noreferrer">FFmpeg Wiki: Audio Channels</a> for more info.</p>
<h1>Generate silent audio</h1>
<p>You can use the <a href="https://ffmpeg.org/ffmpeg-filters.html#anullsrc" rel="noreferrer">anullsrc filter</a> to make a silent audio stream. The filter allows you to choose the desired channel layout (mono, stereo, 5.1, etc) and the sample rate.</p>
<pre><code>ffmpeg -i video.mp4 -f lavfi -i anullsrc=channel_layout=stereo:sample_rate=44100 \
-c:v copy -shortest output.mp4
</code></pre>
<h1>Also see</h1>
<ul>
<li><a href="https://superuser.com/a/800251/110524">Combine two audio streams into one</a></li>
<li><a href="https://trac.ffmpeg.org/wiki/AudioChannelManipulation" rel="noreferrer">FFmpeg Wiki: Audio Channel Manipulation</a></li>
<li><a href="https://stackoverflow.com/a/12943003/1109017">FFmpeg mux video and audio from another video</a></li>
</ul> | {
"question_id": 11779490,
"question_date": "2012-08-02T14:23:38.503Z",
"question_score": 226,
"tags": "audio|video|ffmpeg",
"answer_id": 11783474,
"answer_date": "2012-08-02T18:20:56.113Z",
"answer_score": 498
} |
Please answer the following Stack Overflow question:
Title: Using "super" in C++
<p>My style of coding includes the following idiom:</p>
<pre><code>class Derived : public Base
{
public :
typedef Base super; // note that it could be hidden in
// protected/private section, instead
// Etc.
} ;
</code></pre>
<p>This enables me to use "super" as an alias to Base, for example, in constructors:</p>
<pre><code>Derived(int i, int j)
: super(i), J(j)
{
}
</code></pre>
<p>Or even when calling the method from the base class inside its overridden version:</p>
<pre><code>void Derived::foo()
{
super::foo() ;
// ... And then, do something else
}
</code></pre>
<p>It can even be chained (I have still to find the use for that, though):</p>
<pre><code>class DerivedDerived : public Derived
{
public :
typedef Derived super; // note that it could be hidden in
// protected/private section, instead
// Etc.
} ;
void DerivedDerived::bar()
{
super::bar() ; // will call Derived::bar
super::super::bar ; // will call Base::bar
// ... And then, do something else
}
</code></pre>
<p>Anyway, I find the use of "typedef super" very useful, for example, when Base is either verbose and/or templated.</p>
<p>The fact is that super is implemented in Java, as well as in C# (where it is called "base", unless I'm wrong). But C++ lacks this keyword.</p>
<p>So, my questions:</p>
<ul>
<li>is this use of typedef super common/rare/never seen in the code you work with?</li>
<li>is this use of typedef super Ok (i.e. do you see strong or not so strong reasons to not use it)?</li>
<li>should "super" be a good thing, should it be somewhat standardized in C++, or is this use through a typedef enough already?</li>
</ul>
<p><b>Edit:</b> Roddy mentionned the fact the typedef should be private. This would mean any derived class would not be able to use it without redeclaring it. But I guess it would also prevent the super::super chaining (but who's gonna cry for that?).</p>
<p><b>Edit 2:</b> Now, some months after massively using "super", I wholeheartedly agree with Roddy's viewpoint: "super" should be private.</p> | <p>Bjarne Stroustrup mentions in <em>Design and Evolution of C++</em> that <code>super</code> as a keyword was considered by the ISO C++ Standards committee the first time C++ was standardized.</p>
<p>Dag Bruck proposed this extension, calling the base class "inherited." The proposal mentioned the multiple inheritance issue, and would have flagged ambiguous uses. Even Stroustrup was convinced.</p>
<p>After discussion, Dag Bruck (yes, the same person making the proposal) wrote that the proposal was implementable, technically sound, and free of major flaws, and handled multiple inheritance. On the other hand, there wasn't enough bang for the buck, and the committee should handle a thornier problem.</p>
<p>Michael Tiemann arrived late, and then showed that a typedef'ed super would work just fine, using the same technique that was asked about in this post.</p>
<p>So, no, this will probably never get standardized.</p>
<p>If you don't have a copy, <em>Design and Evolution</em> is well worth the cover price. Used copies can be had for about $10.</p> | {
"question_id": 180601,
"question_date": "2008-10-07T21:49:42.770Z",
"question_score": 226,
"tags": "c++|coding-style",
"answer_id": 180633,
"answer_date": "2008-10-07T22:00:31.997Z",
"answer_score": 173
} |
Please answer the following Stack Overflow question:
Title: Java "lambda expressions not supported at this language level"
<p>I was testing out some new features of Java 8 and copied the example into my IDE (Eclipse originally, then IntelliJ) as shown <a href="http://docs.oracle.com/javase/tutorial/java/javaOO/examples/RosterTest.java" rel="noreferrer">here</a></p>
<p>Eclipse offered no support whatsoever for lambda expressions, and IntelliJ kept reporting an error </p>
<blockquote>
<p>Lambda expressions not supported at this language level</p>
</blockquote>
<p>I would like to know if this is a problem with my install, the code, or support.</p> | <p>In IntelliJ IDEA:</p>
<p>In <code>File Menu</code> → <code>Project Structure</code> → <code>Project</code>, change <code>Project Language Level</code> to <code>8.0 - Lambdas, type annotations etc.</code></p>
<p>For Android 3.0+ Go <code>File</code> → <code>Project Structure</code> → <code>Module</code> → <code>app</code> and In Properties Tab set <code>Source Compatibility</code> and <code>Target Compatibility</code> to <code>1.8 (Java 8)</code></p>
<p>Screenshot:</p>
<p><a href="https://i.stack.imgur.com/PRjlJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PRjlJ.png" alt="enter image description here"></a></p> | {
"question_id": 22703412,
"question_date": "2014-03-28T03:04:37.640Z",
"question_score": 226,
"tags": "java|intellij-idea|lambda|java-8",
"answer_id": 22704620,
"answer_date": "2014-03-28T05:05:23.683Z",
"answer_score": 397
} |
Please answer the following Stack Overflow question:
Title: How to replace NaNs by preceding or next values in pandas DataFrame?
<p>Suppose I have a DataFrame with some <code>NaN</code>s:</p>
<pre><code>>>> import pandas as pd
>>> df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
>>> df
0 1 2
0 1 2 3
1 4 NaN NaN
2 NaN NaN 9
</code></pre>
<p>What I need to do is replace every <code>NaN</code> with the first non-<code>NaN</code> value in the same column above it. It is assumed that the first row will never contain a <code>NaN</code>. So for the previous example the result would be</p>
<pre><code> 0 1 2
0 1 2 3
1 4 2 3
2 4 2 9
</code></pre>
<p>I can just loop through the whole DataFrame column-by-column, element-by-element and set the values directly, but is there an easy (optimally a loop-free) way of achieving this?</p> | <p>You could use the <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.fillna.html" rel="noreferrer"><code>fillna</code></a> method on the DataFrame and specify the method as <code>ffill</code> (forward fill):</p>
<pre><code>>>> df = pd.DataFrame([[1, 2, 3], [4, None, None], [None, None, 9]])
>>> df.fillna(method='ffill')
0 1 2
0 1 2 3
1 4 2 3
2 4 2 9
</code></pre>
<p>This method...</p>
<blockquote>
<p>propagate[s] last valid observation forward to next valid</p>
</blockquote>
<p>To go the opposite way, there's also a <code>bfill</code> method.</p>
<p>This method doesn't modify the DataFrame inplace - you'll need to rebind the returned DataFrame to a variable or else specify <code>inplace=True</code>:</p>
<pre><code>df.fillna(method='ffill', inplace=True)
</code></pre> | {
"question_id": 27905295,
"question_date": "2015-01-12T15:22:48.147Z",
"question_score": 226,
"tags": "python|python-3.x|pandas|dataframe|nan",
"answer_id": 27905350,
"answer_date": "2015-01-12T15:25:42.520Z",
"answer_score": 352
} |
Please answer the following Stack Overflow question:
Title: Turn Pandas Multi-Index into column
<p>I have a dataframe with 2 index levels:</p>
<pre><code> value
Trial measurement
1 0 13
1 3
2 4
2 0 NaN
1 12
3 0 34
</code></pre>
<p>Which I want to turn into this:</p>
<pre><code>Trial measurement value
1 0 13
1 1 3
1 2 4
2 0 NaN
2 1 12
3 0 34
</code></pre>
<p>How can I best do this? </p>
<p>I need this because I want to aggregate the data <a href="https://stackoverflow.com/a/20108446/1893275">as instructed here</a>, but I can't select my columns like that if they are in use as indices.</p> | <p>The <em>reset_index()</em> is a pandas DataFrame method that will transfer index values into the DataFrame as columns. The default setting for the parameter is <em>drop=False</em> (which will keep the index values as columns).</p>
<p>All you have to do call <code>.reset_index()</code> after the name of the DataFrame:</p>
<pre><code>df = df.reset_index()
</code></pre> | {
"question_id": 20110170,
"question_date": "2013-11-21T00:37:03.023Z",
"question_score": 226,
"tags": "python|pandas|dataframe|flatten|multi-index",
"answer_id": 25733562,
"answer_date": "2014-09-08T21:42:18.217Z",
"answer_score": 277
} |
Please answer the following Stack Overflow question:
Title: Disable form auto submit on button click
<p>I have a HTML form where I use several buttons. The problem is that no matter which button I click, the form will get submitted even if the button is not of type "submit". e.g. Buttons like :<code><button>Click to do something</button></code>, result in form submission.</p>
<p>It's quite painful to do an <code>e.preventDefault()</code> for each one of these buttons.</p>
<p>I use jQuery and jQuery UI and the website is in HTML5.</p>
<p>Is there a way to disable this automatic behavior?</p> | <p>Buttons like <code><button>Click to do something</button></code> <strong>are</strong> submit buttons.</p>
<p>Set <code>type="button"</code> to change that. <code>type="submit"</code> is the default (as <a href="https://html.spec.whatwg.org/multipage/form-elements.html#attr-button-type" rel="noreferrer">specified by the HTML spec</a>):</p>
<blockquote>
<p>The missing value default and invalid value default are the Submit Button state.</p>
</blockquote> | {
"question_id": 9824808,
"question_date": "2012-03-22T14:56:50.130Z",
"question_score": 226,
"tags": "javascript|html|button|form-submit|forms",
"answer_id": 9824845,
"answer_date": "2012-03-22T14:58:17.967Z",
"answer_score": 568
} |
Please answer the following Stack Overflow question:
Title: Finding which process was killed by Linux OOM killer
<p>When Linux runs out of memory (OOM), the OOM killer chooses a process to kill based on some heuristics (it's an interesting read: <a href="http://lwn.net/Articles/317814/" rel="noreferrer">http://lwn.net/Articles/317814/</a>).</p>
<p>How can one <em>programmatically</em> determine which processes have recently been killed by the OOM killer?</p> | <p>Try this out:</p>
<pre><code>grep -i 'killed process' /var/log/messages
</code></pre> | {
"question_id": 624857,
"question_date": "2009-03-09T02:47:54.817Z",
"question_score": 226,
"tags": "linux|linux-kernel",
"answer_id": 624868,
"answer_date": "2009-03-09T02:54:54.987Z",
"answer_score": 203
} |
Please answer the following Stack Overflow question:
Title: AngularJS routing without the hash '#'
<p>I'm learning AngularJS and there's one thing that really annoys me.</p>
<p>I use <code>$routeProvider</code> to declare routing rules for my application:</p>
<pre><code>$routeProvider.when('/test', {
controller: TestCtrl,
templateUrl: 'views/test.html'
})
.otherwise({ redirectTo: '/test' });
</code></pre>
<p>but when I navigate to my app in browser I see <code>app/#/test</code> instead of <code>app/test</code>.</p>
<p>So my question is why AngularJS adds this hash <code>#</code> to urls? Is there any possibility to avoid it?</p> | <p>In fact you need the # (hashtag) for non HTML5 browsers.</p>
<p>Otherwise they will just do an HTTP call to the server at the mentioned href.
The # is an old browser shortcircuit which doesn't fire the request, which allows many js frameworks to build their own clientside rerouting on top of that.</p>
<p>You can use <code>$locationProvider.html5Mode(true)</code> to tell angular to use HTML5 strategy if available.</p>
<p>Here the list of browser that support HTML5 strategy: <a href="http://caniuse.com/#feat=history" rel="noreferrer">http://caniuse.com/#feat=history</a></p> | {
"question_id": 14319967,
"question_date": "2013-01-14T14:06:02.100Z",
"question_score": 226,
"tags": "javascript|angularjs",
"answer_id": 14320468,
"answer_date": "2013-01-14T14:36:01.890Z",
"answer_score": 268
} |
Please answer the following Stack Overflow question:
Title: Clicking a button within a form causes page refresh
<p>I have a form in Angular that has two buttons tags in it. One button submits the form on <code>ng-click</code>. The other button is purely for navigation using <code>ng-click</code>. However, when this second button is clicked, AngularJS is causing a page refresh which triggers a 404. I’ve dropped a breakpoint in the function and it is triggering my function. If I do any of the following, it stops:</p>
<ol>
<li>If I remove the <code>ng-click</code>, the button doesn’t cause a page refresh. </li>
<li>If I comment out the code in the function, it doesn’t cause a page refresh. </li>
<li>If I change the button tag to an anchor tag (<code><a></code>) with <code>href=""</code>, then it doesn’t cause a refresh.</li>
</ol>
<p>The latter seems like the simplest workaround, but why is AngularJS even running any code after my function that causes the page to reload? Seems like a bug.</p>
<p>Here is the form:</p>
<pre><code><form class="form-horizontal" name="myProfile" ng-switch-when="profile">
<fieldset>
<div class="control-group">
<label class="control-label" for="passwordButton">Password</label>
<div class="controls">
<button id="passwordButton" class="secondaryButton" ng-click="showChangePassword()">Change</button>
</div>
</div>
<div class="buttonBar">
<button id="saveProfileButton" class="primaryButton" ng-click="saveUser()">Save</button>
</div>
</fieldset>
</form>
</code></pre>
<p>Here is the controller method:</p>
<pre><code>$scope.showChangePassword = function() {
$scope.selectedLink = "changePassword";
};
</code></pre> | <p>If you have a look at the <a href="https://www.w3.org/wiki/HTML/Elements/button" rel="noreferrer">W3C specification</a>, it would seem like the obvious thing to try is to mark your button elements with <code>type='button'</code> when you don't want them to submit.</p>
<p>The thing to note in particular is where it says </p>
<blockquote>
<p>A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit"</p>
</blockquote> | {
"question_id": 12319758,
"question_date": "2012-09-07T14:07:52.433Z",
"question_score": 226,
"tags": "javascript|angularjs",
"answer_id": 15314160,
"answer_date": "2013-03-09T18:12:05.483Z",
"answer_score": 494
} |
Please answer the following Stack Overflow question:
Title: Free XML Formatting tool
<p>Is there a free XML formatting (indent) tool available where I can past an XML string and have it formatted so I can read the XML document correctly?</p>
<p>Thanks</p>
<p>Edit ~ I am using XML Notepad on Windows XP.</p> | <p>I believe that <a href="http://notepad-plus.sourceforge.net/" rel="noreferrer">Notepad++</a> has this feature.</p>
<p><strong>Edit (for newer versions)</strong><br>
Install the "XML Tools" plugin (Menu Plugins, Plugin Manager)<br>
Then run: Menu Plugins, Xml Tools, Pretty Print (XML only - with line breaks)</p>
<p><strong>Original answer (for older versions of Notepad++)</strong> </p>
<p>Notepad++ menu: TextFX -> HTML Tidy -> Tidy: Reindent XML</p>
<p>This feature however wraps XMLs and that makes it look 'unclean'.
To have no wrap, </p>
<ul>
<li>open <code>C:\Program Files\Notepad++\plugins\Config\tidy\TIDYCFG.INI</code>, </li>
<li>find the entry <code>[Tidy: Reindent XML]</code> and add <code>wrap:0</code> so that it looks like this: </li>
</ul>
<pre>
[Tidy: Reindent XML]
input-xml: yes
indent:yes
wrap:0
</pre> | {
"question_id": 193728,
"question_date": "2008-10-11T05:56:06.470Z",
"question_score": 226,
"tags": "xml|xml-formatting",
"answer_id": 193753,
"answer_date": "2008-10-11T06:30:37.510Z",
"answer_score": 351
} |
Please answer the following Stack Overflow question:
Title: How to debug a GLSL shader?
<p>I need to debug a GLSL program but I don't know how to output intermediate result.
Is it possible to make some debug traces (like with printf) with GLSL ?</p> | <p>You can't easily communicate back to the CPU from within GLSL. Using glslDevil or other tools is your best bet. </p>
<p>A printf would require trying to get back to the CPU from the GPU running the GLSL code. Instead, you can try pushing ahead to the display. Instead of trying to output text, output something visually distinctive to the screen. For example you can paint something a specific color only if you reach the point of your code where you want add a printf. If you need to printf a value you can set the color according to that value.</p> | {
"question_id": 2508818,
"question_date": "2010-03-24T15:11:37.670Z",
"question_score": 226,
"tags": "opengl|debugging|glsl",
"answer_id": 2509845,
"answer_date": "2010-03-24T17:14:44.227Z",
"answer_score": 146
} |
Please answer the following Stack Overflow question:
Title: Automatic creation date for Django model form objects
<p>What's the best way to set a creation date for an object automatically, and also a field that will record when the object was last updated?</p>
<p><strong>models.py:</strong></p>
<pre><code>created_at = models.DateTimeField(False, True, editable=False)
updated_at = models.DateTimeField(True, True, editable=False)
</code></pre>
<p><strong>views.py:</strong></p>
<pre><code>if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.user = request.user
obj.save()
return HttpResponseRedirect('obj_list')
</code></pre>
<p>I get the error:</p>
<pre><code>objects_object.created_at may not be NULL
</code></pre>
<p>Do I have to manually set this value myself? I thought that was the point of the parameters passed to <code>DateTimeField</code> (or are they just defaults, and since I've set <code>editable=False</code> they don't get displayed on the form, hence don't get submitted in the request, and therefore don't get put into the form?).</p>
<p>What's the best way of doing this? An <code>__init__</code> method?</p> | <p>You can use the <a href="http://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.DateField.auto_now" rel="noreferrer"><code>auto_now</code></a> and <a href="http://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.DateField.auto_now_add" rel="noreferrer"><code>auto_now_add</code></a> options for <code>updated_at</code> and <code>created_at</code> respectively.</p>
<pre><code>class MyModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
</code></pre> | {
"question_id": 3429878,
"question_date": "2010-08-07T09:21:28.120Z",
"question_score": 226,
"tags": "python|django|django-models",
"answer_id": 3429915,
"answer_date": "2010-08-07T09:33:49.897Z",
"answer_score": 438
} |
Please answer the following Stack Overflow question:
Title: How to convert a plain object into an ES6 Map?
<p>For some reason I can't find this simple thing in the <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map">MDN docs</a> (maybe I'm just missing it).</p>
<p>I expected this to work:</p>
<pre><code>const map = new Map({foo: 'bar'});
map.get('foo'); // 'bar'
</code></pre>
<p>...but the first line throws <code>TypeError: (var)[Symbol.iterator] is not a function</code></p>
<p>How do I make a Map from a plain object? Do I really have to first convert it into an array of arrays of key-value pairs?</p> | <p>Yes, the <code>Map</code> constructor takes an array of key-value pairs.</p>
<p><code>Object.entries</code> is a new Object static method available in <a href="https://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf" rel="noreferrer">ES2017 (19.1.2.5)</a>.</p>
<pre><code>const map = new Map(Object.entries({foo: 'bar'}));
map.get('foo'); // 'bar'
</code></pre>
<p><a href="http://kangax.github.io/compat-table/esnext/#test-Object.entries" rel="noreferrer">It's currently implemented in Firefox 46+ and Edge 14+ and newer versions of Chrome</a></p>
<p>If you need to support older environments and transpilation is not an option for you, use a polyfill, such as the one recommended by georg:</p>
<pre><code>Object.entries = typeof Object.entries === 'function' ? Object.entries : obj => Object.keys(obj).map(k => [k, obj[k]]);
</code></pre> | {
"question_id": 36644438,
"question_date": "2016-04-15T10:18:23.970Z",
"question_score": 226,
"tags": "javascript|ecmascript-6",
"answer_id": 36644558,
"answer_date": "2016-04-15T10:23:31.723Z",
"answer_score": 330
} |
Please answer the following Stack Overflow question:
Title: How do you find all subclasses of a given class in Java?
<p>How does one go about and try to find all subclasses of a given class (or all implementors of a given interface) in Java?
As of now, I have a method to do this, but I find it quite inefficient (to say the least).
The method is: </p>
<ol>
<li>Get a list of all class names that exist on the class path</li>
<li>Load each class and test to see if it is a subclass or implementor of the desired class or interface</li>
</ol>
<p>In Eclipse, there is a nice feature called the Type Hierarchy that manages to show this quite efficiently.
How does one go about and do it programmatically?</p> | <p>There is no other way to do it other than what you described. Think about it - how can anyone know what classes extend ClassX without scanning each class on the classpath?</p>
<p>Eclipse can only tell you about the super and subclasses in what seems to be an "efficient" amount of time because it already has all of the type data loaded at the point where you press the "Display in Type Hierarchy" button (since it is constantly compiling your classes, knows about everything on the classpath, etc).</p> | {
"question_id": 492184,
"question_date": "2009-01-29T15:53:02.780Z",
"question_score": 226,
"tags": "java|class|interface|subclass",
"answer_id": 492210,
"answer_date": "2009-01-29T15:58:52.300Z",
"answer_score": 80
} |
Please answer the following Stack Overflow question:
Title: Running a single test file
<p>Is there a way to run <code>ng test</code> for a single file instead of for the entire test suite? Ideally, I'd like to get the quickest possible feedback loop when I'm editing a file, but <code>karma</code> executes the whole suite on each save, which is a bit slow when you build up a big enough test suite.</p>
<hr>
<p>This is different from <a href="https://stackoverflow.com/questions/40683673/how-to-execute-only-one-test-spec-with-angular-cli">How to execute only one test spec with angular-cli</a> in that that question is about running an individual spec. This is about running an individual file. The solution involves the same Jasmine spec feature, but the nature of the question is slightly different.</p> | <p>I discovered that Jasmine allows you to prefix <code>describe</code> and <code>it</code> methods with an <code>f</code> (for focus): <code>fdescribe</code> and <code>fit</code>. If you use either of these, <a href="https://jasmine.github.io/2.1/focused_specs.html" rel="noreferrer">Karma</a> will only run the relevant tests. To focus the current file, you can just take the top level <code>describe</code> and change it to <code>fdescribe</code>. If you use Jasmine prior to version 2.1, the focusing keywords are: <code>iit</code> and <code>ddescribe</code>.</p>
<p>This example code runs just the first test:</p>
<pre><code>// Jasmine versions >/=2.1 use 'fdescribe'; versions <2.1 use 'ddescribe'
fdescribe('MySpec1', function () {
it('should do something', function () {
// ...
});
});
describe('MyOtherSpec', function () {
it('should do something else', function () {
// ...
});
});
</code></pre>
<p><a href="https://jasmine.github.io/2.1/focused_specs.html" rel="noreferrer">Here</a> is the Jasmine documentation on Focusing Specs, and <a href="https://stackoverflow.com/q/8527786/212950">here</a> is a related SO article that provides additional thoughtful solutions.</p> | {
"question_id": 41132933,
"question_date": "2016-12-14T00:36:16.953Z",
"question_score": 226,
"tags": "angular|jasmine|angular-cli|karma-runner",
"answer_id": 41195601,
"answer_date": "2016-12-17T05:19:38.563Z",
"answer_score": 358
} |
Please answer the following Stack Overflow question:
Title: Ruby: How to turn a hash into HTTP parameters?
<p>That is pretty easy with a plain hash like </p>
<pre><code>{:a => "a", :b => "b"}
</code></pre>
<p>which would translate into </p>
<pre><code>"a=a&b=b"
</code></pre>
<p>But what do you do with something more complex like </p>
<pre><code>{:a => "a", :b => ["c", "d", "e"]}
</code></pre>
<p>which should translate into </p>
<pre><code>"a=a&b[0]=c&b[1]=d&b[2]=e"
</code></pre>
<p>Or even worse, (what to do) with something like: </p>
<pre><code>{:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}]
</code></pre>
<p>Thanks for the much appreciated help with that!</p> | <p><strong>Update:</strong> This functionality was removed from the gem.</p>
<p>Julien, your self-answer is a good one, and I've shameless borrowed from it, but it doesn't properly escape reserved characters, and there are a few other edge cases where it breaks down.</p>
<pre><code>require "addressable/uri"
uri = Addressable::URI.new
uri.query_values = {:a => "a", :b => ["c", "d", "e"]}
uri.query
# => "a=a&b[0]=c&b[1]=d&b[2]=e"
uri.query_values = {:a => "a", :b => [{:c => "c", :d => "d"}, {:e => "e", :f => "f"}]}
uri.query
# => "a=a&b[0][c]=c&b[0][d]=d&b[1][e]=e&b[1][f]=f"
uri.query_values = {:a => "a", :b => {:c => "c", :d => "d"}}
uri.query
# => "a=a&b[c]=c&b[d]=d"
uri.query_values = {:a => "a", :b => {:c => "c", :d => true}}
uri.query
# => "a=a&b[c]=c&b[d]"
uri.query_values = {:a => "a", :b => {:c => "c", :d => true}, :e => []}
uri.query
# => "a=a&b[c]=c&b[d]"
</code></pre>
<p>The gem is '<a href="https://github.com/sporkmonger/addressable" rel="noreferrer">addressable</a>'</p>
<pre><code>gem install addressable
</code></pre> | {
"question_id": 798710,
"question_date": "2009-04-28T16:06:34.293Z",
"question_score": 226,
"tags": "ruby|http|parameters|hashmap",
"answer_id": 803067,
"answer_date": "2009-04-29T16:00:12.833Z",
"answer_score": 89
} |
Please answer the following Stack Overflow question:
Title: Numbering rows within groups in a data frame
<p>Working with a data frame similar to this:</p>
<pre class="lang-r prettyprint-override"><code>set.seed(100)
df <- data.frame(cat = c(rep("aaa", 5), rep("bbb", 5), rep("ccc", 5)), val = runif(15))
df <- df[order(df$cat, df$val), ]
df
</code></pre>
<pre class="lang-none prettyprint-override"><code> cat val
1 aaa 0.05638315
2 aaa 0.25767250
3 aaa 0.30776611
4 aaa 0.46854928
5 aaa 0.55232243
6 bbb 0.17026205
7 bbb 0.37032054
8 bbb 0.48377074
9 bbb 0.54655860
10 bbb 0.81240262
11 ccc 0.28035384
12 ccc 0.39848790
13 ccc 0.62499648
14 ccc 0.76255108
15 ccc 0.88216552
</code></pre>
<p>I am trying to add a column with numbering within each group. Doing it this way obviously isn't using the powers of R:</p>
<pre class="lang-r prettyprint-override"><code> df$num <- 1
for (i in 2:(length(df[,1]))) {
if (df[i,"cat"]==df[(i-1),"cat"]) {
df[i,"num"]<-df[i-1,"num"]+1
}
}
df
</code></pre>
<pre class="lang-none prettyprint-override"><code> cat val num
1 aaa 0.05638315 1
2 aaa 0.25767250 2
3 aaa 0.30776611 3
4 aaa 0.46854928 4
5 aaa 0.55232243 5
6 bbb 0.17026205 1
7 bbb 0.37032054 2
8 bbb 0.48377074 3
9 bbb 0.54655860 4
10 bbb 0.81240262 5
11 ccc 0.28035384 1
12 ccc 0.39848790 2
13 ccc 0.62499648 3
14 ccc 0.76255108 4
15 ccc 0.88216552 5
</code></pre>
<p>What would be a good way to do this?</p> | <p>Use <code>ave</code>, <code>ddply</code>, <code>dplyr</code> or <code>data.table</code>:</p>
<pre><code>df$num <- ave(df$val, df$cat, FUN = seq_along)
</code></pre>
<p>or:</p>
<pre><code>library(plyr)
ddply(df, .(cat), mutate, id = seq_along(val))
</code></pre>
<p>or:</p>
<pre><code>library(dplyr)
df %>% group_by(cat) %>% mutate(id = row_number())
</code></pre>
<p>or (the most memory efficient, as it assigns by reference within <code>DT</code>):</p>
<pre><code>library(data.table)
DT <- data.table(df)
DT[, id := seq_len(.N), by = cat]
DT[, id := rowid(cat)]
</code></pre> | {
"question_id": 12925063,
"question_date": "2012-10-16T23:38:41.953Z",
"question_score": 226,
"tags": "r|dataframe|r-faq|running-count",
"answer_id": 12925090,
"answer_date": "2012-10-16T23:41:50.337Z",
"answer_score": 357
} |
Please answer the following Stack Overflow question:
Title: QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota
<p>Using LocalStorage on iPhone with iOS 7 throws this error. I've been looking around for a resolvant, but considering I'm not even browsing in private, nothing is relevant.</p>
<p>I don't understand why localStorage would be disabled by default in iOS 7, but it seems it is? I've tested on other websites as well, but with no luck. I even tried testing it using this website: <a href="http://arty.name/localstorage.html">http://arty.name/localstorage.html</a>, but it doesn't seem like it's saving anything at all for some weird reason.</p>
<p>Has anyone had the same problem, only they've had luck fixing it? Should I switch my storage method?</p>
<p>I tried hard-debugging it by only storing a few lines of information, but to no avail. I used the standard <code>localStorage.setItem()</code> function to save.</p> | <p>This can occur when Safari is in private mode browsing. While in private browsing, local storage is not available at all.</p>
<p>One solution is to warn the user that the app needs non-private mode to work.</p>
<p>UPDATE: This has been fixed in <a href="https://bugs.webkit.org/show_bug.cgi?id=157010" rel="noreferrer">Safari 11</a>, so the behaviour is now aligned with other browsers.</p> | {
"question_id": 21159301,
"question_date": "2014-01-16T10:35:52.613Z",
"question_score": 226,
"tags": "javascript|iphone|html|local-storage",
"answer_id": 23453866,
"answer_date": "2014-05-04T07:48:25.307Z",
"answer_score": 378
} |
Please answer the following Stack Overflow question:
Title: Ruby on Rails form_for select field with class
<p>I am beating my head against the wall on this one. I want to make a simple select tag using the <code>f.select</code> tag but nothing I do works. I put an example below:</p>
<pre><code><%= f.select(:object_field, ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 4'], :class => 'my_style_class')%>
</code></pre>
<p>Ok, so basically it is a simple list that once the form is submitted it places the value into the <code>object_field</code>. That all works, but viewing the page source the class tag is not included. It doesn't throw an error, it just skips it all together.</p>
<p>If anyone has any suggestions I would greatly appreciate it.</p> | <p>Try this way:</p>
<pre><code><%= f.select(:object_field, ['Item 1', ...], {}, { :class => 'my_style_class' }) %>
</code></pre>
<p><code>select</code> helper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class to <code>html_options</code>.</p>
<p><a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select" rel="noreferrer">http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select</a></p> | {
"question_id": 4081907,
"question_date": "2010-11-02T20:42:00.350Z",
"question_score": 226,
"tags": "ruby-on-rails",
"answer_id": 4081944,
"answer_date": "2010-11-02T20:46:12.657Z",
"answer_score": 500
} |
Please answer the following Stack Overflow question:
Title: How to display the app version in Angular?
<p>How do I display the app version in angular application? the version should be taken from <code>package.json</code> file</p>
<pre><code>{
"name": "angular-app",
"version": "0.0.1",
...
}
</code></pre>
<p>In angular 1.x, I have this html:</p>
<pre><code><p><%=version %></p>
</code></pre>
<p>In angular, this is not rendered as version number, but instead just printed as it is (<code><%=version %></code> instead of <code>0.0.1</code>).</p> | <p>If you want to use/show the version number in your angular app please do the following:</p>
<p><strong>Prerequisites:</strong></p>
<ul>
<li>Angular file and folder structure created via Angular CLI</li>
</ul>
<p><strong>Steps for Angular 6.1 (TS 2.9+) till Angular 11</strong></p>
<ol>
<li>In your <code>/tsconfig.json</code> (sometimes also necessary in <code>/src/tsconfig.app.json</code>) enable the following option (webpack dev server restart required afterwards):</li>
</ol>
<pre><code> "compilerOptions": {
...
"resolveJsonModule": true,
...
</code></pre>
<ol start="2">
<li>Then in your component, for example <code>/src/app/app.component.ts</code> use the version info like this:</li>
</ol>
<pre><code> import { version } from '../../package.json';
...
export class AppComponent {
public version: string = version;
}
</code></pre>
<p>When using this code with Angular 12+ you will probably get: <code>Error: Should not import the named export 'version' (imported as 'version') from default-exporting module (only default export is available soon)</code>.
In this case please use the following code:</p>
<p><strong>Steps for Angular 12+</strong></p>
<ol>
<li>In your <code>/tsconfig.json</code> (sometimes also necessary in <code>/src/tsconfig.app.json</code>) enable the following options (webpack dev server restart required afterwards):</li>
</ol>
<pre><code> "compilerOptions": {
...
"resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
...
</code></pre>
<ol start="2">
<li>Then in your component, for example <code>/src/app/app.component.ts</code> use the version info like this:</li>
</ol>
<pre><code> import packageJson from '../../package.json';
...
export class AppComponent {
public version: string = packageJson.version;
}
</code></pre>
<p>It's also possible to do step 2 in your environment.ts file, making the version info accessible from there.</p>
<p>Thx <strong>@Ionaru</strong> and <strong>@MarcoRinck</strong> for helping out.</p>
<p>This solution should not include the package.json contents when doing a production build - only the version number (checked w/Angular 8 and 13).</p>
<p><strong>To be sure please check your generated main.#hash#.js file too!</strong></p> | {
"question_id": 34907682,
"question_date": "2016-01-20T18:25:43.987Z",
"question_score": 226,
"tags": "angular|typescript|ionic-framework|version|package.json",
"answer_id": 48869478,
"answer_date": "2018-02-19T15:40:42.213Z",
"answer_score": 384
} |
Please answer the following Stack Overflow question:
Title: Where to place JavaScript in an HTML file?
<p>Say I have a fairly hefty JavaScript file, packed down to roughly 100kb or so. By file I mean it’s an external file that would be linked in via <code><script src="..."></code>, not pasted into the HTML itself.</p>
<p>Where’s the best place to put this in the HTML?</p>
<pre><code><html>
<head>
<!-- here? -->
<link rel="stylesheet" href="stylez.css" type="text/css" />
<!-- here? -->
</head>
<body>
<!-- here? -->
<p>All the page content ...</p>
<!-- or here? -->
</body>
</html>
</code></pre>
<p>Will there be any functional difference between each of the options?</p> | <p>The Yahoo! Exceptional Performance team recommend <a href="http://developer.yahoo.com/performance/rules.html#js_bottom" rel="noreferrer">placing scripts at the bottom of your page</a> because of the way browsers download components.</p>
<p>Of course Levi's comment "just before you need it and no sooner" is really the correct answer, i.e. "it depends".</p> | {
"question_id": 196702,
"question_date": "2008-10-13T04:19:52.390Z",
"question_score": 226,
"tags": "javascript|html|optimization",
"answer_id": 196718,
"answer_date": "2008-10-13T04:34:18.257Z",
"answer_score": 180
} |
Please answer the following Stack Overflow question:
Title: HorizontalScrollView within ScrollView Touch Handling
<p>I have a ScrollView that surrounds my entire layout so that the entire screen is scrollable. The first element I have in this ScrollView is a HorizontalScrollView block that has features that can be scrolled through horizontally. I've added an ontouchlistener to the horizontalscrollview to handle touch events and force the view to "snap" to the closest image on the ACTION_UP event.</p>
<p>So the effect I'm going for is like the stock android homescreen where you can scroll from one to the other and it snaps to one screen when you lift your finger.</p>
<p>This all works great except for one problem: I need to swipe left to right almost perfectly horizontally for an ACTION_UP to ever register. If I swipe vertically in the very least (which I think many people tend to do on their phones when swiping side to side), I will receive an ACTION_CANCEL instead of an ACTION_UP. My theory is that this is because the horizontalscrollview is within a scrollview, and the scrollview is hijacking the vertical touch to allow for vertical scrolling. </p>
<p>How can I disable the touch events for the scrollview from just within my horizontal scrollview, but still allow for normal vertical scrolling elsewhere in the scrollview?</p>
<p>Here's a sample of my code:</p>
<pre><code> public class HomeFeatureLayout extends HorizontalScrollView {
private ArrayList<ListItem> items = null;
private GestureDetector gestureDetector;
View.OnTouchListener gestureListener;
private static final int SWIPE_MIN_DISTANCE = 5;
private static final int SWIPE_THRESHOLD_VELOCITY = 300;
private int activeFeature = 0;
public HomeFeatureLayout(Context context, ArrayList<ListItem> items){
super(context);
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
setFadingEdgeLength(0);
this.setHorizontalScrollBarEnabled(false);
this.setVerticalScrollBarEnabled(false);
LinearLayout internalWrapper = new LinearLayout(context);
internalWrapper.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
internalWrapper.setOrientation(LinearLayout.HORIZONTAL);
addView(internalWrapper);
this.items = items;
for(int i = 0; i< items.size();i++){
LinearLayout featureLayout = (LinearLayout) View.inflate(this.getContext(),R.layout.homefeature,null);
TextView header = (TextView) featureLayout.findViewById(R.id.featureheader);
ImageView image = (ImageView) featureLayout.findViewById(R.id.featureimage);
TextView title = (TextView) featureLayout.findViewById(R.id.featuretitle);
title.setTag(items.get(i).GetLinkURL());
TextView date = (TextView) featureLayout.findViewById(R.id.featuredate);
header.setText("FEATURED");
Image cachedImage = new Image(this.getContext(), items.get(i).GetImageURL());
image.setImageDrawable(cachedImage.getImage());
title.setText(items.get(i).GetTitle());
date.setText(items.get(i).GetDate());
internalWrapper.addView(featureLayout);
}
gestureDetector = new GestureDetector(new MyGestureDetector());
setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
else if(event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL ){
int scrollX = getScrollX();
int featureWidth = getMeasuredWidth();
activeFeature = ((scrollX + (featureWidth/2))/featureWidth);
int scrollTo = activeFeature*featureWidth;
smoothScrollTo(scrollTo, 0);
return true;
}
else{
return false;
}
}
});
}
class MyGestureDetector extends SimpleOnGestureListener {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
//right to left
if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
activeFeature = (activeFeature < (items.size() - 1))? activeFeature + 1:items.size() -1;
smoothScrollTo(activeFeature*getMeasuredWidth(), 0);
return true;
}
//left to right
else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
activeFeature = (activeFeature > 0)? activeFeature - 1:0;
smoothScrollTo(activeFeature*getMeasuredWidth(), 0);
return true;
}
} catch (Exception e) {
// nothing
}
return false;
}
}
}
</code></pre> | <p>Update: I figured this out. On my ScrollView, I needed to override the onInterceptTouchEvent method to only intercept the touch event if the Y motion is > the X motion. It seems like the default behavior of a ScrollView is to intercept the touch event whenever there is ANY Y motion. So with the fix, the ScrollView will only intercept the event if the user is deliberately scrolling in the Y direction and in that case pass off the ACTION_CANCEL to the children.</p>
<p>Here is the code for my Scroll View class that contains the HorizontalScrollView:</p>
<pre><code>public class CustomScrollView extends ScrollView {
private GestureDetector mGestureDetector;
public CustomScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
mGestureDetector = new GestureDetector(context, new YScrollDetector());
setFadingEdgeLength(0);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev) && mGestureDetector.onTouchEvent(ev);
}
// Return false if we're scrolling in the x direction
class YScrollDetector extends SimpleOnGestureListener {
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return Math.abs(distanceY) > Math.abs(distanceX);
}
}
}
</code></pre> | {
"question_id": 2646028,
"question_date": "2010-04-15T14:12:08.917Z",
"question_score": 226,
"tags": "android|ontouchlistener|android-scrollview|horizontalscrollview",
"answer_id": 2655740,
"answer_date": "2010-04-16T19:51:34.933Z",
"answer_score": 284
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.