input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: Upgrading Node.js to latest version
<p>So, I have Node.js installed and now when I tried to install Mongoosejs I got an error telling me that I don't have the needed version of Node.js (I have v0.4.11 and v0.4.12 is needed).</p>
<p>How can I upgrade to this version? I suppose I just could install it again with the latest version, but I don't want to do it before I'm sure that my project folders in the folder "node" won't be deleted.</p> | <h3>Ubuntu Linux/Mac:</h3>
<p>The module <code>n</code> makes version-management easy:</p>
<pre><code>npm install n -g
</code></pre>
<p>For the latest stable version:</p>
<pre><code>n stable
</code></pre>
<p>For the latest version:</p>
<pre><code>n latest
</code></pre>
<h3>Windows:</h3>
<p>just reinstall node from the .msi in Windows from the <a href="https://nodejs.org/en/download/" rel="noreferrer">node website</a>.</p> | {
"question_id": 10075990,
"question_date": "2012-04-09T16:02:57.117Z",
"question_score": 976,
"tags": "node.js|upgrade",
"answer_id": 10076029,
"answer_date": "2012-04-09T16:06:14.213Z",
"answer_score": 1596
} |
Please answer the following Stack Overflow question:
Title: How can I make a Python script standalone executable to run without ANY dependency?
<p>I'm building a Python application and don't want to force my clients to install Python and modules.</p>
<p>So, is there a way to compile a Python script to be a standalone executable?</p> | <p>You can use <a href="http://www.py2exe.org/" rel="noreferrer">py2exe</a> as already answered and use <a href="http://cython.org/" rel="noreferrer">Cython</a> to convert your key <code>.py</code> files in <code>.pyc</code>, C compiled files, like <code>.dll</code> in Windows and <code>.so</code> on Linux.</p>
<p>It is much harder to revert than common <code>.pyo</code> and <code>.pyc</code> files (and also gain in performance!).</p> | {
"question_id": 5458048,
"question_date": "2011-03-28T11:04:09.657Z",
"question_score": 976,
"tags": "python|executable",
"answer_id": 5458807,
"answer_date": "2011-03-28T12:12:41.520Z",
"answer_score": 293
} |
Please answer the following Stack Overflow question:
Title: How can I pass a parameter to a setTimeout() callback?
<p>I have some JavaScript code that looks like:</p>
<pre><code>function statechangedPostQuestion()
{
//alert("statechangedPostQuestion");
if (xmlhttp.readyState==4)
{
var topicId = xmlhttp.responseText;
setTimeout("postinsql(topicId)",4000);
}
}
function postinsql(topicId)
{
//alert(topicId);
}
</code></pre>
<p>I get an error that <code>topicId</code> is not defined
Everything was working before I used the <code>setTimeout()</code> function.</p>
<p>I want my <code>postinsql(topicId)</code> function to be called after some time.
What should I do?</p> | <pre><code>setTimeout(function() {
postinsql(topicId);
}, 4000)
</code></pre>
<p>You need to feed an anonymous function as a parameter instead of a string, the latter method shouldn't even work per the ECMAScript specification but browsers are just lenient. This is the proper solution, don't ever rely on passing a string as a 'function' when using <code>setTimeout()</code> or <code>setInterval()</code>, it's slower because it has to be evaluated and it just isn't right.</p>
<h2>UPDATE:</h2>
<p>As Hobblin said in his <a href="https://stackoverflow.com/questions/1190642/how-can-i-pass-a-parameter-to-a-settimeout-callback#comment8933108_1190642">comments</a> to the question, now you can pass arguments to the function inside setTimeout using <a href="https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_objects/Function/bind" rel="noreferrer"><code>Function.prototype.bind()</code></a>.</p>
<p><strong>Example:</strong></p>
<pre><code>setTimeout(postinsql.bind(null, topicId), 4000);
</code></pre> | {
"question_id": 1190642,
"question_date": "2009-07-27T21:13:28.030Z",
"question_score": 976,
"tags": "javascript|parameters|callback|settimeout",
"answer_id": 1190656,
"answer_date": "2009-07-27T21:15:26.263Z",
"answer_score": 1260
} |
Please answer the following Stack Overflow question:
Title: How are lambdas useful?
<p>I'm trying to figure out Python lambdas. Is <code>lambda</code> one of those "interesting" language items that in real life should be forgotten?</p>
<p>I'm sure there are some edge cases where it might be needed, but given the obscurity of it, the potential of it being redefined in future releases (my assumption based on the various definitions of it) and the reduced coding clarity - should it be avoided?</p>
<p>This reminds me of overflowing (buffer overflow) of C types - pointing to the top variable and overloading to set the other field values. It feels like sort of a techie showmanship but maintenance coder nightmare.</p> | <p>Are you talking about <a href="https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions" rel="noreferrer">lambda expressions</a>? Like</p>
<pre><code>lambda x: x**2 + 2*x - 5
</code></pre>
<p>Those things are actually quite useful. Python supports a style of programming called <em>functional programming</em> where you can pass functions to other functions to do stuff. Example:</p>
<pre><code>mult3 = filter(lambda x: x % 3 == 0, [1, 2, 3, 4, 5, 6, 7, 8, 9])
</code></pre>
<p>sets <code>mult3</code> to <code>[3, 6, 9]</code>, those elements of the original list that are multiples of 3. This is shorter (and, one could argue, clearer) than</p>
<pre><code>def filterfunc(x):
return x % 3 == 0
mult3 = filter(filterfunc, [1, 2, 3, 4, 5, 6, 7, 8, 9])
</code></pre>
<p>Of course, in this particular case, you could do the same thing as a list comprehension:</p>
<pre><code>mult3 = [x for x in [1, 2, 3, 4, 5, 6, 7, 8, 9] if x % 3 == 0]
</code></pre>
<p>(or even as <code>range(3,10,3)</code>), but there are many other, more sophisticated use cases where you can't use a list comprehension and a lambda function may be the shortest way to write something out.</p>
<ul>
<li><p>Returning a function from another function</p>
<pre><code> >>> def transform(n):
... return lambda x: x + n
...
>>> f = transform(3)
>>> f(4)
7
</code></pre>
<p>This is often used to create function wrappers, such as Python's decorators.</p>
</li>
<li><p>Combining elements of an iterable sequence with <code>reduce()</code></p>
<pre><code> >>> reduce(lambda a, b: '{}, {}'.format(a, b), [1, 2, 3, 4, 5, 6, 7, 8, 9])
'1, 2, 3, 4, 5, 6, 7, 8, 9'
</code></pre>
</li>
<li><p>Sorting by an alternate key</p>
<pre><code> >>> sorted([1, 2, 3, 4, 5, 6, 7, 8, 9], key=lambda x: abs(5-x))
[5, 4, 6, 3, 7, 2, 8, 1, 9]
</code></pre>
</li>
</ul>
<p>I use lambda functions on a regular basis. It took me a while to get used to them, but eventually I came to understand that they're a very valuable part of the language.</p> | {
"question_id": 890128,
"question_date": "2009-05-20T20:40:01.297Z",
"question_score": 976,
"tags": "python|function|lambda|closures",
"answer_id": 890188,
"answer_date": "2009-05-20T20:52:10.930Z",
"answer_score": 1054
} |
Please answer the following Stack Overflow question:
Title: Peak detection in a 2D array
<p>I'm helping a veterinary clinic measuring pressure under a dogs paw. I use Python for my data analysis and now I'm stuck trying to divide the paws into (anatomical) subregions.</p>
<p>I made a 2D array of each paw, that consists of the maximal values for each sensor that has been loaded by the paw over time. Here's an example of one paw, where I used Excel to draw the areas I want to 'detect'. These are 2 by 2 boxes around the sensor with local maxima's, that together have the largest sum.</p>
<p><img src="https://i.stack.imgur.com/BuUbq.png" alt="alt text" /></p>
<p>So I tried some experimenting and decide to simply look for the maximums of each column and row (can't look in one direction due to the shape of the paw). This seems to 'detect' the location of the separate toes fairly well, but it also marks neighboring sensors.</p>
<p><img src="https://i.stack.imgur.com/UyNRU.png" alt="alt text" /></p>
<p>So what would be the best way to tell Python which of these maximums are the ones I want?</p>
<p><strong>Note: The 2x2 squares can't overlap, since they have to be separate toes!</strong></p>
<p>Also I took 2x2 as a convenience, any more advanced solution is welcome, but I'm simply a human movement scientist, so I'm neither a real programmer or a mathematician, so please keep it 'simple'.</p>
<p>Here's a <a href="https://upl.io/0liy07" rel="noreferrer">version that can be loaded with <code>np.loadtxt</code></a></p>
<hr />
<h2>Results</h2>
<p>So I tried @jextee's solution (see the results below). As you can see, it works very on the front paws, but it works less well for the hind legs.</p>
<p>More specifically, it can't recognize the small peak that's the fourth toe. This is obviously inherent to the fact that the loop looks top down towards the lowest value, without taking into account where this is.</p>
<p>Would anyone know how to tweak @jextee's algorithm, so that it might be able to find the 4th toe too?</p>
<p><img src="https://i.stack.imgur.com/FFX0x.png" alt="alt text" /></p>
<p>Since I haven't processed any other trials yet, I can't supply any other samples. But the data I gave before were the averages of each paw. This file is an array with the maximal data of 9 paws in the order they made contact with the plate.</p>
<p>This image shows how they were spatially spread out over the plate.</p>
<p><img src="https://i.stack.imgur.com/iPXEv.png" alt="alt text" /></p>
<h2>Update:</h2>
<p><strong><a href="http://www.flipserd.com/blog/ivoflipse/post/toe-detection-revisited" rel="noreferrer">I have set up a blog for anyone interested</a></strong> and <a href="https://1drv.ms/u/s!AjVZ_ROiXWgOhDEn4KrRB8mrOZWM?e=aUCCm4" rel="noreferrer">I have setup a OneDrive with all the raw measurements.</a> So to anyone requesting more data: more power to you!</p>
<hr />
<h2>New update:</h2>
<p>So after the help I got with my questions regarding <a href="https://stackoverflow.com/q/4087919/77595">paw detection</a> and <a href="https://stackoverflow.com/q/4502656/77595">paw sorting</a>, I was finally able to check the toe detection for every paw! Turns out, it doesn't work so well in anything but paws sized like the one in my own example. Off course in hindsight, it's my own fault for choosing the 2x2 so arbitrarily.</p>
<p>Here's a nice example of where it goes wrong: a nail is being recognized as a toe and the 'heel' is so wide, it gets recognized twice!</p>
<p><img src="https://i.stack.imgur.com/JEpIa.png" alt="alt text" /></p>
<p>The paw is too large, so taking a 2x2 size with no overlap, causes some toes to be detected twice. The other way around, in small dogs it often fails to find a 5th toe, which I suspect is being caused by the 2x2 area being too large.</p>
<p>After <a href="http://www.flipserd.com/blog/ivoflipse/post/toe-detection-revisited" rel="noreferrer">trying the current solution on all my measurements</a> I came to the staggering conclusion that for nearly all my small dogs it didn't find a 5th toe and that in over 50% of the impacts for the large dogs it would find more!</p>
<p>So clearly I need to change it. My own guess was changing the size of the <code>neighborhood</code> to something smaller for small dogs and larger for large dogs. But <code>generate_binary_structure</code> wouldn't let me change the size of the array.</p>
<p>Therefore, I'm hoping that anyone else has a better suggestion for locating the toes, perhaps having the toe area scale with the paw size?</p> | <p>I detected the peaks using a <strong>local maximum filter</strong>. Here is the result on your first dataset of 4 paws:
<img src="https://i.stack.imgur.com/Kgt4H.png" alt="Peaks detection result"></p>
<p>I also ran it on the second dataset of 9 paws and <a href="https://i.stack.imgur.com/4CKCh.png" rel="noreferrer">it worked as well</a>.</p>
<p>Here is how you do it:</p>
<pre><code>import numpy as np
from scipy.ndimage.filters import maximum_filter
from scipy.ndimage.morphology import generate_binary_structure, binary_erosion
import matplotlib.pyplot as pp
#for some reason I had to reshape. Numpy ignored the shape header.
paws_data = np.loadtxt("paws.txt").reshape(4,11,14)
#getting a list of images
paws = [p.squeeze() for p in np.vsplit(paws_data,4)]
def detect_peaks(image):
"""
Takes an image and detect the peaks usingthe local maximum filter.
Returns a boolean mask of the peaks (i.e. 1 when
the pixel's value is the neighborhood maximum, 0 otherwise)
"""
# define an 8-connected neighborhood
neighborhood = generate_binary_structure(2,2)
#apply the local maximum filter; all pixel of maximal value
#in their neighborhood are set to 1
local_max = maximum_filter(image, footprint=neighborhood)==image
#local_max is a mask that contains the peaks we are
#looking for, but also the background.
#In order to isolate the peaks we must remove the background from the mask.
#we create the mask of the background
background = (image==0)
#a little technicality: we must erode the background in order to
#successfully subtract it form local_max, otherwise a line will
#appear along the background border (artifact of the local maximum filter)
eroded_background = binary_erosion(background, structure=neighborhood, border_value=1)
#we obtain the final mask, containing only peaks,
#by removing the background from the local_max mask (xor operation)
detected_peaks = local_max ^ eroded_background
return detected_peaks
#applying the detection and plotting results
for i, paw in enumerate(paws):
detected_peaks = detect_peaks(paw)
pp.subplot(4,2,(2*i+1))
pp.imshow(paw)
pp.subplot(4,2,(2*i+2) )
pp.imshow(detected_peaks)
pp.show()
</code></pre>
<p>All you need to do after is use <code>scipy.ndimage.measurements.label</code> on the mask to label all distinct objects. Then you'll be able to play with them individually.</p>
<p><strong>Note</strong> that the method works well because the background is not noisy. If it were, you would detect a bunch of other unwanted peaks in the background. Another important factor is the size of the <em>neighborhood</em>. You will need to adjust it if the peak size changes (the should remain roughly proportional).</p> | {
"question_id": 3684484,
"question_date": "2010-09-10T12:12:25.200Z",
"question_score": 976,
"tags": "python|image-processing",
"answer_id": 3689710,
"answer_date": "2010-09-11T03:38:07.857Z",
"answer_score": 376
} |
Please answer the following Stack Overflow question:
Title: Get the full URL in PHP
<p>I use this code to get the full URL:</p>
<pre><code>$actual_link = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
</code></pre>
<p>The problem is that I use some masks in my <code>.htaccess</code>, so what we see in the URL is not always the real path of the file.</p>
<p>What I need is to get the URL, what is written in the URL, nothing more and nothing less—the full URL.</p>
<p>I need to get how it appears in the Navigation Bar in the web browser, and not the real path of the file on the server.</p> | <p>Have a look at <code>$_SERVER['REQUEST_URI']</code>, i.e.</p>
<pre><code>$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
</code></pre>
<p>(Note that the double quoted string syntax is <a href="http://php.net/language.types.string#language.types.string.parsing.simple" rel="noreferrer">perfectly correct</a>)</p>
<p>If you want to support both HTTP and HTTPS, you can use</p>
<pre><code>$actual_link = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
</code></pre>
<p><strong>Editor's note:</strong> using this code has <strong>security implications</strong>. The client can set HTTP_HOST and REQUEST_URI to any arbitrary value it wants.</p> | {
"question_id": 6768793,
"question_date": "2011-07-20T21:29:51.930Z",
"question_score": 975,
"tags": "php|url",
"answer_id": 6768831,
"answer_date": "2011-07-20T21:33:08.707Z",
"answer_score": 2415
} |
Please answer the following Stack Overflow question:
Title: Multiprocessing vs Threading Python
<p>I am trying to understand the advantages of <a href="http://docs.python.org/library/multiprocessing" rel="noreferrer">multiprocessing</a> over <a href="http://docs.python.org/library/threading" rel="noreferrer">threading</a>. I know that <strong>multiprocessing</strong> gets around the Global Interpreter Lock, but what other advantages are there, and can <strong>threading</strong> not do the same thing?</p> | <p>The <code>threading</code> module uses threads, the <code>multiprocessing</code> module uses processes. The difference is that threads run in the same memory space, while processes have separate memory. This makes it a bit harder to share objects between processes with multiprocessing. Since threads use the same memory, precautions have to be taken or two threads will write to the same memory at the same time. This is what the global interpreter lock is for.</p>
<p>Spawning processes is a bit slower than spawning threads.</p> | {
"question_id": 3044580,
"question_date": "2010-06-15T11:12:45.750Z",
"question_score": 975,
"tags": "python|multithreading|multiprocessing",
"answer_id": 3044626,
"answer_date": "2010-06-15T11:19:25.303Z",
"answer_score": 864
} |
Please answer the following Stack Overflow question:
Title: PHP random string generator
<p>I'm trying to create a randomized string in PHP, and I get absolutely no output with this:</p>
<pre><code><?php
function RandomString()
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randstring = '';
for ($i = 0; $i < 10; $i++) {
$randstring = $characters[rand(0, strlen($characters))];
}
return $randstring;
}
RandomString();
echo $randstring;
</code></pre>
<p>What am I doing wrong?</p> | <p>To answer this question specifically, two problems: </p>
<ol>
<li><code>$randstring</code> is not in scope when you echo it.</li>
<li>The characters are not getting concatenated together in the loop.</li>
</ol>
<p>Here's a code snippet with the corrections:</p>
<pre><code>function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
</code></pre>
<p>Output the random string with the call below:</p>
<pre><code>// Echo the random string.
// Optionally, you can give it a desired string length.
echo generateRandomString();
</code></pre>
<blockquote>
<p><strong>Please note that this generates predictable random strings. If you want to create secure tokens, <a href="https://stackoverflow.com/a/31107425/2373138">see this answer</a>.</strong></p>
</blockquote> | {
"question_id": 4356289,
"question_date": "2010-12-04T22:56:21.337Z",
"question_score": 974,
"tags": "php|string|random",
"answer_id": 4356295,
"answer_date": "2010-12-04T22:57:42.110Z",
"answer_score": 1602
} |
Please answer the following Stack Overflow question:
Title: Remove empty array elements
<p>Some elements in my array are empty strings based on what the user has submitted. I need to remove those elements. I have this:</p>
<pre><code>foreach($linksArray as $link)
{
if($link == '')
{
unset($link);
}
}
print_r($linksArray);
</code></pre>
<p>But it doesn't work. <code>$linksArray</code> still has empty elements. I have also tried doing it with the <code>empty()</code> function, but the outcome is the same.</p> | <p>As you're dealing with an array of strings, you can simply use <a href="https://secure.php.net/manual/en/function.array-filter.php" rel="noreferrer"><code>array_filter()</code></a>, which conveniently handles all this for you:</p>
<pre><code>print_r(array_filter($linksArray));
</code></pre>
<p>Keep in mind that <strong>if no callback is supplied</strong>, all entries of array equal to <code>FALSE</code> (see <a href="http://php.net/manual/en/language.types.boolean.php#language.types.boolean.casting" rel="noreferrer">converting to boolean</a>) will be removed. So if you need to preserve elements that are i.e. exact string <code>'0'</code>, you will need a custom callback:</p>
<pre><code>// PHP 7.4 and later
print_r(array_filter($linksArray, fn($value) => !is_null($value) && $value !== ''));
// PHP 5.3 and later
print_r(array_filter($linksArray, function($value) { return !is_null($value) && $value !== ''; }));
// PHP < 5.3
print_r(array_filter($linksArray, create_function('$value', 'return $value !== "";')));
</code></pre>
<br>
<p>Note: If you need to reindex the array after removing the empty elements, use: <code>$linksArray = array_values(array_filter($linksArray));</code></p> | {
"question_id": 3654295,
"question_date": "2010-09-06T21:06:57.727Z",
"question_score": 974,
"tags": "php|arrays|string",
"answer_id": 3654309,
"answer_date": "2010-09-06T21:10:23.107Z",
"answer_score": 1893
} |
Please answer the following Stack Overflow question:
Title: What is the naming convention in Python for variable and function?
<p>Coming from a C# background the naming convention for variables and method names are usually either camelCase or PascalCase:</p>
<pre class="lang-cs prettyprint-override"><code>// C# example
string thisIsMyVariable = "a"
public void ThisIsMyMethod()
</code></pre>
<p>In Python, I have seen the above but I have also seen underscores being used:</p>
<pre class="lang-py prettyprint-override"><code># python example
this_is_my_variable = 'a'
def this_is_my_function():
</code></pre>
<p>Is there a more preferable, definitive coding style for Python?</p> | <p>See Python <a href="https://www.python.org/dev/peps/pep-0008/#function-and-variable-names" rel="noreferrer">PEP 8: Function and Variable Names</a>:</p>
<blockquote>
<p>Function names should be <a href="https://en.wikipedia.org/wiki/Snake_case" rel="noreferrer">lowercase, with words separated by underscores</a> as necessary to improve readability.</p>
<p>Variable names follow the same convention as function names.</p>
<p><a href="https://en.wikipedia.org/wiki/MixedCase" rel="noreferrer">mixedCase</a> is allowed only in contexts where that's already the prevailing style (e.g. <a href="https://docs.python.org/library/threading.html" rel="noreferrer">threading.py</a>), to retain backwards compatibility.</p>
</blockquote> | {
"question_id": 159720,
"question_date": "2008-10-01T21:01:16.757Z",
"question_score": 974,
"tags": "python|python-3.x|function|variables|naming-conventions",
"answer_id": 159745,
"answer_date": "2008-10-01T21:05:24.187Z",
"answer_score": 1059
} |
Please answer the following Stack Overflow question:
Title: How to remove/delete a large file from commit history in the Git repository?
<p>I accidentally dropped a DVD-rip into a website project, then carelessly <code>git commit -a -m ...</code>, and, zap, the repo was bloated by 2.2 gigs. Next time I made some edits, deleted the video file, and committed everything, but the compressed file is still there in the repository, in history.</p>
<p>I know I can start branches from those commits and rebase one branch onto another. But what should I do to merge the 2 commits so that the big file doesn't show in the history and is cleaned in the garbage collection procedure?</p> | <p>Why not use this simple but powerful command?</p>
<pre><code>git filter-branch --tree-filter 'rm -f DVD-rip' HEAD
</code></pre>
<p>The <code>--tree-filter</code> option runs the specified command after each checkout of the project and then recommits the results. In this case, you remove a file called DVD-rip from every snapshot, whether it exists or not. </p>
<p>If you know which commit introduced the huge file (say 35dsa2), you can replace HEAD with 35dsa2..HEAD to avoid rewriting too much history, thus avoiding diverging commits if you haven't pushed yet. This comment courtesy of @alpha_989 seems too important to leave out here.</p>
<p>See <a href="https://git-scm.com/book/en/v2/Git-Tools-Rewriting-History#The-Nuclear-Option:-filter-branch" rel="noreferrer">this link</a>.</p> | {
"question_id": 2100907,
"question_date": "2010-01-20T11:18:48.213Z",
"question_score": 974,
"tags": "git|version-control|git-rebase|git-rewrite-history",
"answer_id": 30274113,
"answer_date": "2015-05-16T09:44:10.450Z",
"answer_score": 281
} |
Please answer the following Stack Overflow question:
Title: Swift Beta performance: sorting arrays
<p>I was implementing an algorithm in Swift Beta and noticed that the performance was very poor. After digging deeper I realized that one of the bottlenecks was something as simple as sorting arrays. The relevant part is here:</p>
<pre><code>let n = 1000000
var x = [Int](repeating: 0, count: n)
for i in 0..<n {
x[i] = random()
}
// start clock here
let y = sort(x)
// stop clock here
</code></pre>
<p>In C++, a similar operation takes <strong>0.06s</strong> on my computer.</p>
<p>In Python, it takes <strong>0.6s</strong> (no tricks, just y = sorted(x) for a list of integers).</p>
<p>In Swift it takes <strong>6s</strong> if I compile it with the following command:</p>
<pre><code>xcrun swift -O3 -sdk `xcrun --show-sdk-path --sdk macosx`
</code></pre>
<p>And it takes as much as <strong>88s</strong> if I compile it with the following command:</p>
<pre><code>xcrun swift -O0 -sdk `xcrun --show-sdk-path --sdk macosx`
</code></pre>
<p>Timings in Xcode with "Release" vs. "Debug" builds are similar.</p>
<p>What is wrong here? I could understand some performance loss in comparison with C++, but not a 10-fold slowdown in comparison with pure Python.</p>
<hr>
<p><strong>Edit:</strong> weather noticed that changing <code>-O3</code> to <code>-Ofast</code> makes this code run almost as fast as the C++ version! However, <code>-Ofast</code> changes the semantics of the language a lot — in my testing, it <strong>disabled the checks for integer overflows and array indexing overflows</strong>. For example, with <code>-Ofast</code> the following Swift code runs silently without crashing (and prints out some garbage):</p>
<pre><code>let n = 10000000
print(n*n*n*n*n)
let x = [Int](repeating: 10, count: n)
print(x[n])
</code></pre>
<p>So <code>-Ofast</code> is not what we want; the whole point of Swift is that we have the safety nets in place. Of course, the safety nets have some impact on the performance, but they should not make the programs 100 times slower. Remember that Java already checks for array bounds, and in typical cases, the slowdown is by a factor much less than 2. And in Clang and GCC we have got <code>-ftrapv</code> for checking (signed) integer overflows, and it is not that slow, either.</p>
<p>Hence the question: how can we get reasonable performance in Swift without losing the safety nets?</p>
<hr>
<p><strong>Edit 2:</strong> I did some more benchmarking, with very simple loops along the lines of</p>
<pre><code>for i in 0..<n {
x[i] = x[i] ^ 12345678
}
</code></pre>
<p>(Here the xor operation is there just so that I can more easily find the relevant loop in the assembly code. I tried to pick an operation that is easy to spot but also "harmless" in the sense that it should not require any checks related to integer overflows.)</p>
<p>Again, there was a huge difference in the performance between <code>-O3</code> and <code>-Ofast</code>. So I had a look at the assembly code:</p>
<ul>
<li><p>With <code>-Ofast</code> I get pretty much what I would expect. The relevant part is a loop with 5 machine language instructions.</p></li>
<li><p>With <code>-O3</code> I get something that was beyond my wildest imagination. The inner loop spans 88 lines of assembly code. I did not try to understand all of it, but the most suspicious parts are 13 invocations of "callq _swift_retain" and another 13 invocations of "callq _swift_release". That is, <strong>26 subroutine calls in the inner loop</strong>!</p></li>
</ul>
<hr>
<p><strong>Edit 3:</strong> In comments, Ferruccio asked for benchmarks that are fair in the sense that they do not rely on built-in functions (e.g. sort). I think the following program is a fairly good example:</p>
<pre><code>let n = 10000
var x = [Int](repeating: 1, count: n)
for i in 0..<n {
for j in 0..<n {
x[i] = x[j]
}
}
</code></pre>
<p>There is no arithmetic, so we do not need to worry about integer overflows. The only thing that we do is just lots of array references. And the results are here—Swift -O3 loses by a factor almost 500 in comparison with -Ofast:</p>
<ul>
<li>C++ -O3: <strong>0.05 s</strong></li>
<li>C++ -O0: 0.4 s</li>
<li>Java: <strong>0.2 s</strong></li>
<li>Python with PyPy: 0.5 s</li>
<li>Python: <strong>12 s</strong></li>
<li>Swift -Ofast: 0.05 s</li>
<li>Swift -O3: <strong>23 s</strong></li>
<li>Swift -O0: 443 s</li>
</ul>
<p>(If you are concerned that the compiler might optimize out the pointless loops entirely, you can change it to e.g. <code>x[i] ^= x[j]</code>, and add a print statement that outputs <code>x[0]</code>. This does not change anything; the timings will be very similar.)</p>
<p>And yes, here the Python implementation was a stupid pure Python implementation with a list of ints and nested for loops. It should be <strong>much</strong> slower than unoptimized Swift. Something seems to be seriously broken with Swift and array indexing.</p>
<hr>
<p><strong>Edit 4:</strong> These issues (as well as some other performance issues) seems to have been fixed in Xcode 6 beta 5.</p>
<p>For sorting, I now have the following timings:</p>
<ul>
<li>clang++ -O3: 0.06 s</li>
<li>swiftc -Ofast: 0.1 s</li>
<li>swiftc -O: 0.1 s</li>
<li>swiftc: 4 s</li>
</ul>
<p>For nested loops:</p>
<ul>
<li>clang++ -O3: 0.06 s</li>
<li>swiftc -Ofast: 0.3 s</li>
<li>swiftc -O: 0.4 s</li>
<li>swiftc: 540 s</li>
</ul>
<p>It seems that there is no reason anymore to use the unsafe <code>-Ofast</code> (a.k.a. <code>-Ounchecked</code>); plain <code>-O</code> produces equally good code.</p> | <p>tl;dr Swift 1.0 is now as fast as C by this benchmark using the default release optimisation level [-O].</p>
<hr>
<p>Here is an in-place quicksort in Swift Beta:</p>
<pre><code>func quicksort_swift(inout a:CInt[], start:Int, end:Int) {
if (end - start < 2){
return
}
var p = a[start + (end - start)/2]
var l = start
var r = end - 1
while (l <= r){
if (a[l] < p){
l += 1
continue
}
if (a[r] > p){
r -= 1
continue
}
var t = a[l]
a[l] = a[r]
a[r] = t
l += 1
r -= 1
}
quicksort_swift(&a, start, r + 1)
quicksort_swift(&a, r + 1, end)
}
</code></pre>
<p>And the same in C:</p>
<pre><code>void quicksort_c(int *a, int n) {
if (n < 2)
return;
int p = a[n / 2];
int *l = a;
int *r = a + n - 1;
while (l <= r) {
if (*l < p) {
l++;
continue;
}
if (*r > p) {
r--;
continue;
}
int t = *l;
*l++ = *r;
*r-- = t;
}
quicksort_c(a, r - a + 1);
quicksort_c(l, a + n - l);
}
</code></pre>
<p>Both work:</p>
<pre><code>var a_swift:CInt[] = [0,5,2,8,1234,-1,2]
var a_c:CInt[] = [0,5,2,8,1234,-1,2]
quicksort_swift(&a_swift, 0, a_swift.count)
quicksort_c(&a_c, CInt(a_c.count))
// [-1, 0, 2, 2, 5, 8, 1234]
// [-1, 0, 2, 2, 5, 8, 1234]
</code></pre>
<p>Both are called in the same program as written.</p>
<pre><code>var x_swift = CInt[](count: n, repeatedValue: 0)
var x_c = CInt[](count: n, repeatedValue: 0)
for var i = 0; i < n; ++i {
x_swift[i] = CInt(random())
x_c[i] = CInt(random())
}
let swift_start:UInt64 = mach_absolute_time();
quicksort_swift(&x_swift, 0, x_swift.count)
let swift_stop:UInt64 = mach_absolute_time();
let c_start:UInt64 = mach_absolute_time();
quicksort_c(&x_c, CInt(x_c.count))
let c_stop:UInt64 = mach_absolute_time();
</code></pre>
<p>This converts the absolute times to seconds:</p>
<pre><code>static const uint64_t NANOS_PER_USEC = 1000ULL;
static const uint64_t NANOS_PER_MSEC = 1000ULL * NANOS_PER_USEC;
static const uint64_t NANOS_PER_SEC = 1000ULL * NANOS_PER_MSEC;
mach_timebase_info_data_t timebase_info;
uint64_t abs_to_nanos(uint64_t abs) {
if ( timebase_info.denom == 0 ) {
(void)mach_timebase_info(&timebase_info);
}
return abs * timebase_info.numer / timebase_info.denom;
}
double abs_to_seconds(uint64_t abs) {
return abs_to_nanos(abs) / (double)NANOS_PER_SEC;
}
</code></pre>
<p>Here is a summary of the compiler's optimazation levels:</p>
<pre><code>[-Onone] no optimizations, the default for debug.
[-O] perform optimizations, the default for release.
[-Ofast] perform optimizations and disable runtime overflow checks and runtime type checks.
</code></pre>
<p>Time in seconds with <strong>[-Onone]</strong> for <strong>n=10_000</strong>:</p>
<pre><code>Swift: 0.895296452
C: 0.001223848
</code></pre>
<p>Here is Swift's builtin sort() for <strong>n=10_000</strong>:</p>
<pre><code>Swift_builtin: 0.77865783
</code></pre>
<p>Here is <strong>[-O]</strong> for <strong>n=10_000</strong>:</p>
<pre><code>Swift: 0.045478346
C: 0.000784666
Swift_builtin: 0.032513488
</code></pre>
<p>As you can see, Swift's performance improved by a factor of 20.</p>
<p>As per <a href="https://stackoverflow.com/questions/24101718/swift-performance-sorting-arrays/24102759#24102759">mweathers' answer</a>, setting <strong>[-Ofast]</strong> makes the real difference, resulting in these times for <strong>n=10_000</strong>:</p>
<pre><code>Swift: 0.000706745
C: 0.000742374
Swift_builtin: 0.000603576
</code></pre>
<p>And for <strong>n=1_000_000</strong>:</p>
<pre><code>Swift: 0.107111846
C: 0.114957179
Swift_sort: 0.092688548
</code></pre>
<p>For comparison, this is with <strong>[-Onone]</strong> for <strong>n=1_000_000</strong>:</p>
<pre><code>Swift: 142.659763258
C: 0.162065333
Swift_sort: 114.095478272
</code></pre>
<p>So Swift with no optimizations was almost 1000x slower than C in this benchmark, at this stage in its development. On the other hand with both compilers set to [-Ofast] Swift actually performed at least as well if not slightly better than C.</p>
<p>It has been pointed out that [-Ofast] changes the semantics of the language, making it potentially unsafe. This is what Apple states in the Xcode 5.0 release notes:</p>
<blockquote>
<p>A new optimization level -Ofast, available in LLVM, enables aggressive optimizations. -Ofast relaxes some conservative restrictions, mostly for floating-point operations, that are safe for most code. It can yield significant high-performance wins from the compiler.</p>
</blockquote>
<p>They all but advocate it. Whether that's wise or not I couldn't say, but from what I can tell it seems reasonable enough to use [-Ofast] in a release if you're not doing high-precision floating point arithmetic and you're confident no integer or array overflows are possible in your program. If you do need high performance <em>and</em> overflow checks / precise arithmetic then choose another language for now.</p>
<p>BETA 3 UPDATE:</p>
<p><strong>n=10_000</strong> with <strong>[-O]</strong>:</p>
<pre><code>Swift: 0.019697268
C: 0.000718064
Swift_sort: 0.002094721
</code></pre>
<p>Swift in general is a bit faster and it looks like Swift's built-in sort has changed quite significantly.</p>
<p><strong>FINAL UPDATE:</strong></p>
<p><strong>[-Onone]</strong>:</p>
<pre><code>Swift: 0.678056695
C: 0.000973914
</code></pre>
<p><strong>[-O]</strong>:</p>
<pre><code>Swift: 0.001158492
C: 0.001192406
</code></pre>
<p><strong>[-Ounchecked]</strong>:</p>
<pre><code>Swift: 0.000827764
C: 0.001078914
</code></pre> | {
"question_id": 24101718,
"question_date": "2014-06-07T23:53:45.487Z",
"question_score": 974,
"tags": "swift|performance|sorting|xcode6|compiler-optimization",
"answer_id": 24102237,
"answer_date": "2014-06-08T01:36:03.343Z",
"answer_score": 478
} |
Please answer the following Stack Overflow question:
Title: How to allow only numeric (0-9) in HTML inputbox using jQuery?
<p>I am creating a web page where I have an input text field in which I want to allow only numeric characters like (0,1,2,3,4,5...9) 0-9.</p>
<p>How can I do this using jQuery?</p> | <p><sup><strong>Note:</strong> This is an updated answer. Comments below refer to an old version which messed around with keycodes.</sup></p>
<h1>jQuery</h1>
<p><strong>Try it yourself <a href="https://jsfiddle.net/KarmaProd/hw8j34f2/4/" rel="noreferrer">on JSFiddle</a>.</strong></p>
<p>There is no native jQuery implementation for this, but you can filter the input values of a text <code><input></code> with the following <code>inputFilter</code> plugin (supports Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, the caret position, different keyboard layouts, validity error message, and <a href="https://caniuse.com/#feat=input-event" rel="noreferrer">all browsers since IE 9</a>):</p>
<pre><code>// Restricts input for the set of matched elements to the given inputFilter function.
(function($) {
$.fn.inputFilter = function(callback, errMsg) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop focusout", function(e) {
if (callback(this.value)) {
// Accepted value
if (["keydown","mousedown","focusout"].indexOf(e.type) >= 0){
$(this).removeClass("input-error");
this.setCustomValidity("");
}
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
// Rejected value - restore the previous one
$(this).addClass("input-error");
this.setCustomValidity(errMsg);
this.reportValidity();
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
// Rejected value - nothing to restore
this.value = "";
}
});
};
}(jQuery));
</code></pre>
<p>You can now use the <code>inputFilter</code> plugin to install an input filter:</p>
<pre><code>$(document).ready(function() {
$("#myTextBox").inputFilter(function(value) {
return /^\d*$/.test(value); // Allow digits only, using a RegExp
},"Only digits allowed");
});
</code></pre>
<p>Apply your preferred style to input-error class. Here's a suggestion:</p>
<pre><code>.input-error{
outline: 1px solid red;
}
</code></pre>
<p>See the <a href="https://jsfiddle.net/KarmaProd/hw8j34f2/4/" rel="noreferrer">JSFiddle demo</a> for more input filter examples. Also note that you still <strong>must do server side validation!</strong></p>
<h1>Pure JavaScript (without jQuery)</h1>
<p>jQuery isn't actually needed for this, you can do the same thing with pure JavaScript as well. See <a href="https://stackoverflow.com/a/469362/1070129">this answer</a>.</p>
<h1>HTML 5</h1>
<p>HTML 5 has a native solution with <code><input type="number"></code> (see the <a href="https://www.w3.org/TR/html/sec-forms.html#number-state-typenumber" rel="noreferrer">specification</a>), but note that browser support varies:</p>
<ul>
<li>Most browsers will only validate the input when submitting the form, and not when typing.</li>
<li><a href="https://caniuse.com/#feat=input-number" rel="noreferrer">Most mobile browsers</a> don't support the <code>step</code>, <code>min</code> and <code>max</code> attributes.</li>
<li>Chrome (version 71.0.3578.98) still allows the user to enter the characters <code>e</code> and <code>E</code> into the field. Also see <a href="https://stackoverflow.com/q/31706611">this question</a>.</li>
<li>Firefox (version 64.0) and Edge (EdgeHTML version 17.17134) still allow the user to enter <em>any</em> text into the field.</li>
</ul>
<p>Try it yourself <a href="http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_type_number" rel="noreferrer">on w3schools.com</a>.</p> | {
"question_id": 995183,
"question_date": "2009-06-15T09:22:07.560Z",
"question_score": 973,
"tags": "jquery|html|validation|numeric",
"answer_id": 995193,
"answer_date": "2009-06-15T09:26:14.757Z",
"answer_score": 1353
} |
Please answer the following Stack Overflow question:
Title: What's the difference between UTF-8 and UTF-8 with BOM?
<p>What's different between UTF-8 and UTF-8 with <a href="http://en.wikipedia.org/wiki/Byte_order_mark" rel="nofollow noreferrer">BOM</a>? Which is better?</p> | <p>The UTF-8 BOM is a sequence of <em>bytes</em> at the start of a text stream (<code>0xEF, 0xBB, 0xBF</code>) that allows the reader to more reliably guess a file as being encoded in UTF-8.</p>
<p>Normally, the <a href="https://en.wikipedia.org/wiki/Byte_order_mark" rel="noreferrer">BOM</a> is used to signal the <a href="https://en.wikipedia.org/wiki/Endianness" rel="noreferrer">endianness</a> of an encoding, but since endianness is irrelevant to UTF-8, the BOM is unnecessary.</p>
<p>According to the <a href="http://www.unicode.org/versions/Unicode5.0.0/ch02.pdf" rel="noreferrer">Unicode standard</a>, the <strong>BOM for UTF-8 files is not recommended</strong>:</p>
<blockquote>
<h2>2.6 Encoding Schemes</h2>
<p>... Use of a BOM is neither required nor recommended for UTF-8, but may be encountered in contexts where UTF-8 data is converted from other encoding forms that use a BOM or where the BOM is used as a UTF-8 signature. See the “Byte Order Mark” subsection in <em><a href="http://www.unicode.org/versions/Unicode5.0.0/ch16.pdf" rel="noreferrer">Section 16.8, Specials</a></em>, for more information.</p>
</blockquote> | {
"question_id": 2223882,
"question_date": "2010-02-08T18:26:21.123Z",
"question_score": 973,
"tags": "unicode|utf-8|character-encoding|byte-order-mark",
"answer_id": 2223926,
"answer_date": "2010-02-08T18:33:26.937Z",
"answer_score": 897
} |
Please answer the following Stack Overflow question:
Title: How do I convert a String to an InputStream in Java?
<p>Given a string:</p>
<pre><code>String exampleString = "example";
</code></pre>
<p>How do I convert it to an <code>InputStream</code>?</p> | <p>Like this:</p>
<pre><code>InputStream stream = new ByteArrayInputStream(exampleString.getBytes(StandardCharsets.UTF_8));
</code></pre>
<p>Note that this assumes that you want an InputStream that is a stream of bytes that represent your original string encoded as <em>UTF-8</em>.</p>
<p>For versions of Java less than 7, replace <code>StandardCharsets.UTF_8</code> with <code>"UTF-8"</code>.</p> | {
"question_id": 782178,
"question_date": "2009-04-23T15:11:23.667Z",
"question_score": 973,
"tags": "java|string|type-conversion|inputstream",
"answer_id": 782183,
"answer_date": "2009-04-23T15:12:04.023Z",
"answer_score": 1553
} |
Please answer the following Stack Overflow question:
Title: Add line break to 'git commit -m' from the command line
<p>I am using Git from the command line and am trying to add a line break to the commit message (using <code>git commit -m ""</code>) without going into Vim.</p>
<p>Is this possible?</p> | <p>Certainly, how it's done depends on your shell. In Bash, you can use single quotes around the message and can just leave the quote open, which will make Bash prompt for another line, until you close the quote. Like this:</p>
<pre><code>git commit -m 'Message
goes
here'
</code></pre>
<p>Alternatively, you can use a "here document" (also known as heredoc):</p>
<pre><code>git commit -F- <<EOF
Message
goes
here
EOF
</code></pre> | {
"question_id": 5064563,
"question_date": "2011-02-21T10:02:42.163Z",
"question_score": 973,
"tags": "git|bash|shell",
"answer_id": 5064653,
"answer_date": "2011-02-21T10:12:01.607Z",
"answer_score": 885
} |
Please answer the following Stack Overflow question:
Title: JSLint is suddenly reporting: Use the function form of "use strict"
<p>I include the statement:</p>
<pre><code>"use strict";
</code></pre>
<p>at the beginning of most of my Javascript files.</p>
<p>JSLint has never before warned about this. But now it is, saying:</p>
<blockquote>
<p>Use the function form of "use strict".</p>
</blockquote>
<p>Does anyone know what the "function form" would be?</p> | <p>Include <code>'use strict';</code> as the first statement in a wrapping function, so it only affects that function. This prevents problems when concatenating scripts that aren't strict.</p>
<p>See Douglas Crockford's latest blog post <a href="http://www.yuiblog.com/blog/2010/12/14/strict-mode-is-coming-to-town/" rel="noreferrer">Strict Mode Is Coming To Town</a>.</p>
<p>Example from that post:</p>
<pre><code>(function () {
'use strict';
// this function is strict...
}());
(function () {
// but this function is sloppy...
}());
</code></pre>
<p><strong>Update:</strong>
In case you don't want to wrap in immediate function (e.g. it is a node module), then you can disable the warning.</p>
<p>For <strong>JSLint</strong> (per <a href="https://stackoverflow.com/a/11375064/2688">Zhami</a>):</p>
<pre><code>/*jslint node: true */
</code></pre>
<p>For <strong>JSHint</strong>:</p>
<pre><code>/*jshint strict:false */
</code></pre>
<p>or (per <a href="https://stackoverflow.com/posts/4462560/revisions">Laith Shadeed</a>)</p>
<pre><code>/* jshint -W097 */
</code></pre>
<p>To disable any arbitrary warning from JSHint, check the map in <a href="https://github.com/jshint/jshint/blob/master/src/messages.js" rel="noreferrer">JSHint source code</a> (details in <a href="http://www.jshint.com/docs/" rel="noreferrer">docs</a>).</p>
<p><strong>Update 2:</strong> <strong>JSHint</strong> supports <code>node:boolean</code> option. See <a href="https://github.com/jshint/jshint/blob/4c2d091b7e50ce2681ee48a104578bb969c189ae/examples/.jshintrc#L79" rel="noreferrer"><code>.jshintrc</code> at github</a>.</p>
<pre><code>/* jshint node: true */
</code></pre> | {
"question_id": 4462478,
"question_date": "2010-12-16T15:36:39.727Z",
"question_score": 973,
"tags": "javascript|jslint",
"answer_id": 4462560,
"answer_date": "2010-12-16T15:44:09.427Z",
"answer_score": 1042
} |
Please answer the following Stack Overflow question:
Title: Auto Scale TextView Text to Fit within Bounds
<p>I'm looking for an optimal way to resize wrapping text in a <code>TextView</code> so that it will fit within its getHeight and getWidth bounds. I'm not simply looking for a way to wrap the text- I want to make sure it both wraps and is small enough to fit entirely on the screen. </p>
<p>I've seen a few cases on StackOverflow where auto resizing was needed, but they are either very special cases with hack solutions, have no solution, or involve re-drawing the <code>TextView</code> recursively until it is small enough (which is memory intense and forces the user to watch the text shrink step-by-step with every recursion). </p>
<p>But I'm sure somebody out there has found a good solution that doesn't involve what I'm doing: writing several heavy routines that parse and measure the text, resize the text, and repeat until a suitably small size has been found. </p>
<p>What routines does <code>TextView</code> use to wrap the text? Couldn't those be somehow used to predict whether text will be small enough?</p>
<p><strong>tl;dr</strong>: is there a best-practice way to auto-resize a <code>TextView</code> to fit, wrapped, in its getHeight and getWidth bounds?</p> | <p>From June 2018 Android officially started supporting this feature for <strong>Android 4.0 (API level 14) and higher.</strong><br>
Check it out at: <a href="https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview" rel="noreferrer">Autosizing TextViews</a></p>
<p><strong>With Android 8.0 (API level 26) and higher</strong>: <br></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
android:autoSizeTextType="uniform"
android:autoSizeMinTextSize="12sp"
android:autoSizeMaxTextSize="100sp"
android:autoSizeStepGranularity="2sp" />
</code></pre>
<p>Programmatically: <br></p>
<pre><code>setAutoSizeTextTypeUniformWithConfiguration(int autoSizeMinTextSize, int autoSizeMaxTextSize,
int autoSizeStepGranularity, int unit)
textView.setAutoSizeTextTypeUniformWithConfiguration(
1, 17, 1, TypedValue.COMPLEX_UNIT_DIP);
</code></pre>
<p><br></p>
<p><strong>Android versions prior to Android 8.0 (API level 26)</strong>: <br></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="200dp"
app:autoSizeTextType="uniform"
app:autoSizeMinTextSize="12sp"
app:autoSizeMaxTextSize="100sp"
app:autoSizeStepGranularity="2sp" />
</LinearLayout>
</code></pre>
<p>Programmatically: <br></p>
<pre><code>TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(
TextView textView, int autoSizeMinTextSize, int autoSizeMaxTextSize, int autoSizeStepGranularity, int unit)
TextViewCompat.setAutoSizeTextTypeUniformWithConfiguration(textView, 1, 17, 1,
TypedValue.COMPLEX_UNIT_DIP);
</code></pre>
<p><em>Attention: <strong>TextView</strong> must have layout_width="<strong>match_parent</strong>" or <strong>absolute size!</em></strong></p> | {
"question_id": 5033012,
"question_date": "2011-02-17T18:31:38.717Z",
"question_score": 972,
"tags": "android|scale|textview|word-wrap",
"answer_id": 52772600,
"answer_date": "2018-10-12T05:06:31.360Z",
"answer_score": 317
} |
Please answer the following Stack Overflow question:
Title: onActivityResult is not being called in Fragment
<p>The activity hosting this fragment has its <code>onActivityResult</code> called when the camera activity returns.</p>
<p>My fragment starts an activity for a result with the intent sent for the camera to take a picture. The picture application loads fine, takes a picture, and returns. The <code>onActivityResult</code> however is never hit. I've set breakpoints, but nothing is triggered. Can a fragment have <code>onActivityResult</code>? I'd think so since it's a provided function. Why isn't this being triggered?</p>
<pre><code>ImageView myImage = (ImageView)inflatedView.findViewById(R.id.image);
myImage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1888);
}
});
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode == 1888 ) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
((ImageView)inflatedView.findViewById(R.id.image)).setImageBitmap(photo);
}
}
</code></pre> | <p>The hosting activity overrides <code>onActivityResult()</code>, but it did not make a call to <code>super.onActivityResult()</code> for unhandled result codes. Apparently, even though the fragment is the one making the <code>startActivityForResult()</code> call, the activity gets the first shot at handling the result. This makes sense when you consider the modularity of fragments. Once I implemented <code>super.onActivityResult()</code> for all unhandled results, the fragment got a shot at handling the result.</p>
<p>And also from @siqing answer:</p>
<p>To get the result in your fragment make sure you call <code>startActivityForResult(intent,111);</code> instead of <code>getActivity().startActivityForResult(intent,111);</code> inside your fragment.</p> | {
"question_id": 6147884,
"question_date": "2011-05-27T04:35:19.070Z",
"question_score": 972,
"tags": "android|android-fragments|android-activity",
"answer_id": 6147919,
"answer_date": "2011-05-27T04:42:16.570Z",
"answer_score": 1343
} |
Please answer the following Stack Overflow question:
Title: typedef struct vs struct definitions
<p>I'm a beginner in C programming, but I was wondering what's the difference between using <code>typedef</code> when defining a structure versus not using <code>typedef</code>. It seems to me like there's really no difference, they accomplish the same goal.</p>
<pre><code>struct myStruct{
int one;
int two;
};
</code></pre>
<p>vs.</p>
<pre><code>typedef struct{
int one;
int two;
}myStruct;
</code></pre> | <p>The common idiom is using both: </p>
<pre><code>typedef struct S {
int x;
} S;
</code></pre>
<p>They are different definitions. To make the discussion clearer I will split the sentence:</p>
<pre><code>struct S {
int x;
};
typedef struct S S;
</code></pre>
<p>In the first line you are defining the identifier <code>S</code> within the struct name space (not in the C++ sense). You can use it and define variables or function arguments of the newly defined type by defining the type of the argument as <code>struct S</code>:</p>
<pre><code>void f( struct S argument ); // struct is required here
</code></pre>
<p>The second line adds a type alias <code>S</code> in the global name space and thus allows you to just write:</p>
<pre><code>void f( S argument ); // struct keyword no longer needed
</code></pre>
<p>Note that since both identifier name spaces are different, defining <code>S</code> both in the structs and global spaces is not an error, as it is not redefining the same identifier, but rather creating a different identifier in a different place.</p>
<p>To make the difference clearer:</p>
<pre><code>typedef struct S {
int x;
} T;
void S() { } // correct
//void T() {} // error: symbol T already defined as an alias to 'struct S'
</code></pre>
<p>You can define a function with the same name of the struct as the identifiers are kept in different spaces, but you cannot define a function with the same name as a <code>typedef</code> as those identifiers collide.</p>
<p>In C++, it is slightly different as the rules to locate a symbol have changed subtly. C++ still keeps the two different identifier spaces, but unlike in C, when you only define the symbol within the class identifier space, you are not required to provide the struct/class keyword:</p>
<pre><code> // C++
struct S {
int x;
}; // S defined as a class
void f( S a ); // correct: struct is optional
</code></pre>
<p>What changes are the search rules, not where the identifiers are defined. The compiler will search the global identifier table and after <code>S</code> has not been found it will search for <code>S</code> within the class identifiers.</p>
<p>The code presented before behaves in the same way:</p>
<pre><code>typedef struct S {
int x;
} T;
void S() {} // correct [*]
//void T() {} // error: symbol T already defined as an alias to 'struct S'
</code></pre>
<p>After the definition of the <code>S</code> function in the second line, the struct <code>S</code> cannot be resolved automatically by the compiler, and to create an object or define an argument of that type you must fall back to including the <code>struct</code> keyword:</p>
<pre><code>// previous code here...
int main() {
S();
struct S s;
}
</code></pre> | {
"question_id": 1675351,
"question_date": "2009-11-04T17:21:57.857Z",
"question_score": 971,
"tags": "c|struct|typedef",
"answer_id": 1675446,
"answer_date": "2009-11-04T17:37:21.703Z",
"answer_score": 1249
} |
Please answer the following Stack Overflow question:
Title: Extract substring in Bash
<p>Given a filename in the form <code>someletters_12345_moreleters.ext</code>, I want to extract the 5 digits and put them into a variable.</p>
<p>So to emphasize the point, I have a filename with x number of characters then a five digit sequence surrounded by a single underscore on either side then another set of x number of characters. I want to take the 5 digit number and put that into a variable.</p>
<p>I am very interested in the number of different ways that this can be accomplished.</p> | <p>Use <a href="http://www.manpagez.com/man/1/cut/" rel="noreferrer">cut</a>:</p>
<pre><code>echo 'someletters_12345_moreleters.ext' | cut -d'_' -f 2
</code></pre>
<p>More generic:</p>
<pre><code>INPUT='someletters_12345_moreleters.ext'
SUBSTRING=$(echo $INPUT| cut -d'_' -f 2)
echo $SUBSTRING
</code></pre> | {
"question_id": 428109,
"question_date": "2009-01-09T13:53:22.793Z",
"question_score": 970,
"tags": "string|bash|shell|substring",
"answer_id": 428118,
"answer_date": "2009-01-09T13:56:14.113Z",
"answer_score": 880
} |
Please answer the following Stack Overflow question:
Title: PostgreSQL error: Fatal: role "username" does not exist
<p>I'm setting up my PostgreSQL 9.1. I can't do anything with PostgreSQL: can't <code>createdb</code>, can't <code>createuser</code>; all operations return the error message</p>
<pre><code>Fatal: role h9uest does not exist
</code></pre>
<p><code>h9uest</code> is my account name, and I <code>sudo apt-get install</code> PostgreSQL 9.1 under this account.<br>
Similar error persists for the <code>root</code> account.</p> | <p>Use the <em>operating system user</em> <code>postgres</code> to create your database - as long as you haven't set up a <em>database</em> role with the necessary privileges that corresponds to your operating system user of the same name (<code>h9uest</code> in your case):</p>
<pre><code>sudo -u postgres -i
</code></pre>
<p>As recommended <a href="https://serverfault.com/q/359856/98376">here</a> or <a href="https://serverfault.com/q/601140/98376">here</a>.</p>
<p>Then try again. Type <code>exit</code> when done with operating as system user <code>postgres</code>.</p>
<p><strong>Or</strong> execute the single command <code>createuser</code> as <code>postgres</code> with <code>sudo</code>, like <a href="https://stackoverflow.com/a/18708583/939860">demonstrated by drees</a> in another answer.</p>
<p>The point is to use the operating system user matching the database role of the same name to be granted access via <a href="https://www.postgresql.org/docs/current/client-authentication.html" rel="noreferrer"><strong><code>ident</code> authentication</strong></a>. <code>postgres</code> is the default operating system user to have initialized the database cluster. <a href="https://www.postgresql.org/docs/current/database-roles.html" rel="noreferrer">The manual:</a> </p>
<blockquote>
<p>In order to bootstrap the database system, a freshly initialized
system always contains one predefined role. This role is always a
“superuser”, and by default (unless altered when running <code>initdb</code>) it
will have the same name as the operating system user that initialized
the database cluster. Customarily, this role will be named <code>postgres</code>.
In order to create more roles you first have to connect as this
initial role.</p>
</blockquote>
<p>I have heard of odd setups with non-standard user names or where the operating system user does not exist. You'd need to adapt your strategy there.</p>
<p>Read about <a href="https://www.postgresql.org/docs/current/user-manag.html" rel="noreferrer">database roles</a> and <a href="https://www.postgresql.org/docs/current/client-authentication.html" rel="noreferrer">client authentication</a> in the manual.</p> | {
"question_id": 11919391,
"question_date": "2012-08-12T03:00:44.830Z",
"question_score": 970,
"tags": "postgresql|authentication",
"answer_id": 11919677,
"answer_date": "2012-08-12T04:13:03.503Z",
"answer_score": 1004
} |
Please answer the following Stack Overflow question:
Title: How to get a JavaScript object's class?
<p>I created a JavaScript object, but how I can determine the class of that object?</p>
<p>I want something similar to Java's <code>.getClass()</code> method. </p> | <p>There's no exact counterpart to Java's <a href="http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#getClass()" rel="noreferrer"><code>getClass()</code></a> in JavaScript. Mostly that's due to JavaScript being a <a href="http://en.wikipedia.org/wiki/Prototype-based_programming" rel="noreferrer">prototype-based language</a>, as opposed to Java being a <a href="http://en.wikipedia.org/wiki/Class-based_programming" rel="noreferrer">class-based</a> one.</p>
<p>Depending on what you need <code>getClass()</code> for, there are several options in JavaScript: </p>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/typeof" rel="noreferrer"><code>typeof</code></a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/instanceof" rel="noreferrer"><code>instanceof</code></a></li>
<li><code>obj.</code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/constructor" rel="noreferrer"><code>constructor</code></a></li>
<li><code>func.</code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/prototype" rel="noreferrer"><code>prototype</code></a>, <code>proto</code>.<a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Object/isPrototypeOf" rel="noreferrer"><code>isPrototypeOf</code></a></li>
</ul>
<p>A few examples:</p>
<pre><code>function Foo() {}
var foo = new Foo();
typeof Foo; // == "function"
typeof foo; // == "object"
foo instanceof Foo; // == true
foo.constructor.name; // == "Foo"
Foo.name // == "Foo"
Foo.prototype.isPrototypeOf(foo); // == true
Foo.prototype.bar = function (x) {return x+x;};
foo.bar(21); // == 42
</code></pre>
<p>Note: if you are compiling your code with Uglify it will change non-global class names. To prevent this, Uglify has a <a href="https://github.com/mishoo/UglifyJS2" rel="noreferrer"><code>--mangle</code></a> param that you can set to false is using <a href="https://github.com/terinjokes/gulp-uglify" rel="noreferrer">gulp</a> or <a href="https://github.com/gruntjs/grunt-contrib-uglify" rel="noreferrer">grunt</a>.</p> | {
"question_id": 1249531,
"question_date": "2009-08-08T18:11:57.207Z",
"question_score": 969,
"tags": "javascript|oop",
"answer_id": 1249554,
"answer_date": "2009-08-08T18:20:09.703Z",
"answer_score": 1309
} |
Please answer the following Stack Overflow question:
Title: GitHub Error Message - Permission denied (publickey)
<p>Anybody seen this error and know what to do?</p>
<p>I'm using the terminal, I'm in the root, the GitHub repository exists and I don't know what to do now.</p>
<pre><code>> git push -u origin master
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
</code></pre> | <p>GitHub isn't able to authenticate you. So, either you aren't setup with an SSH key, because you haven't <a href="https://help.github.com/articles/generating-ssh-keys">set one up on your machine</a>, or your key isn't associated with your GitHub account.</p>
<p>You can also use the HTTPS URL instead of the SSH/git URL to avoid having to deal with SSH keys. This is <a href="https://help.github.com/articles/set-up-git">GitHub's recommended method</a>.</p>
<p>Further, GitHub has a <a href="https://help.github.com/articles/error-permission-denied-publickey">help page specifically for that error message</a>, and explains in more detail everything you could check.</p> | {
"question_id": 12940626,
"question_date": "2012-10-17T18:11:56.357Z",
"question_score": 968,
"tags": "git|github",
"answer_id": 12940681,
"answer_date": "2012-10-17T18:15:18.750Z",
"answer_score": 844
} |
Please answer the following Stack Overflow question:
Title: Why should C++ programmers minimize use of 'new'?
<p>I stumbled upon <strong>Stack Overflow</strong> question <a href="https://stackoverflow.com/q/3428750/211563">Memory leak with std::string when using std::list<std::string></a>, and <a href="https://stackoverflow.com/q/3428750/211563#comment3570156_3428750">one of the comments</a> says this:</p>
<blockquote>
<p>Stop using <code>new</code> so much. I can't see any reason you used new anywhere
you did. You can create objects by value in <strong>C++</strong> and it's one of the
huge advantages to using the language.<br>
You do not have to allocate
everything on the heap.<br>
Stop thinking like a <strong>Java</strong> programmer.</p>
</blockquote>
<p>I'm not really sure what he means by that. </p>
<blockquote>
<p>Why should objects be created by value in <strong>C++</strong> as often as possible, and what difference does it make internally?<br>
Did I misinterpret the answer?</p>
</blockquote> | <p>There are two widely-used memory allocation techniques: automatic allocation and dynamic allocation. Commonly, there is a corresponding region of memory for each: the stack and the heap.</p>
<h3>Stack</h3>
<p>The stack always allocates memory in a sequential fashion. It can do so because it requires you to release the memory in the reverse order (First-In, Last-Out: FILO). This is the memory allocation technique for local variables in many programming languages. It is very, very fast because it requires minimal bookkeeping and the next address to allocate is implicit.</p>
<p>In C++, this is called <em>automatic storage</em> because the storage is claimed automatically at the end of scope. As soon as execution of current code block (delimited using <code>{}</code>) is completed, memory for all variables in that block is automatically collected. This is also the moment where <em>destructors</em> are invoked to clean up resources.</p>
<h3>Heap</h3>
<p>The heap allows for a more flexible memory allocation mode. Bookkeeping is more complex and allocation is slower. Because there is no implicit release point, you must release the memory manually, using <code>delete</code> or <code>delete[]</code> (<code>free</code> in C). However, the absence of an implicit release point is the key to the heap's flexibility.</p>
<h3>Reasons to use dynamic allocation</h3>
<p>Even if using the heap is slower and potentially leads to memory leaks or memory fragmentation, there are perfectly good use cases for dynamic allocation, as it's less limited.</p>
<p>Two key reasons to use dynamic allocation:</p>
<ul>
<li><p>You don't know how much memory you need at compile time. For instance, when reading a text file into a string, you usually don't know what size the file has, so you can't decide how much memory to allocate until you run the program.</p>
</li>
<li><p>You want to allocate memory which will persist after leaving the current block. For instance, you may want to write a function <code>string readfile(string path)</code> that returns the contents of a file. In this case, even if the stack could hold the entire file contents, you could not return from a function and keep the allocated memory block.</p>
</li>
</ul>
<h3>Why dynamic allocation is often unnecessary</h3>
<p>In C++ there's a neat construct called a <em>destructor</em>. This mechanism allows you to manage resources by aligning the lifetime of the resource with the lifetime of a variable. This technique is called <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="noreferrer">RAII</a> and is the distinguishing point of C++. It "wraps" resources into objects. <code>std::string</code> is a perfect example. This snippet:</p>
<pre><code>int main ( int argc, char* argv[] )
{
std::string program(argv[0]);
}
</code></pre>
<p>actually allocates a variable amount of memory. The <code>std::string</code> object allocates memory using the heap and releases it in its destructor. In this case, you did <em>not</em> need to manually manage any resources and still got the benefits of dynamic memory allocation.</p>
<p>In particular, it implies that in this snippet:</p>
<pre><code>int main ( int argc, char* argv[] )
{
std::string * program = new std::string(argv[0]); // Bad!
delete program;
}
</code></pre>
<p>there is unneeded dynamic memory allocation. The program requires more typing (!) and introduces the risk of forgetting to deallocate the memory. It does this with no apparent benefit.</p>
<h3>Why you should use automatic storage as often as possible</h3>
<p>Basically, the last paragraph sums it up. Using automatic storage as often as possible makes your programs:</p>
<ul>
<li>faster to type;</li>
<li>faster when run;</li>
<li>less prone to memory/resource leaks.</li>
</ul>
<h3>Bonus points</h3>
<p>In the referenced question, there are additional concerns. In particular, the following class:</p>
<pre><code>class Line {
public:
Line();
~Line();
std::string* mString;
};
Line::Line() {
mString = new std::string("foo_bar");
}
Line::~Line() {
delete mString;
}
</code></pre>
<p>Is actually a lot more risky to use than the following one:</p>
<pre><code>class Line {
public:
Line();
std::string mString;
};
Line::Line() {
mString = "foo_bar";
// note: there is a cleaner way to write this.
}
</code></pre>
<p>The reason is that <code>std::string</code> properly defines a copy constructor. Consider the following program:</p>
<pre><code>int main ()
{
Line l1;
Line l2 = l1;
}
</code></pre>
<p>Using the original version, this program will likely crash, as it uses <code>delete</code> on the same string twice. Using the modified version, each <code>Line</code> instance will own its own string <em>instance</em>, each with its own memory and both will be released at the end of the program.</p>
<h3>Other notes</h3>
<p>Extensive use of <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="noreferrer">RAII</a> is considered a best practice in C++ because of all the reasons above. However, there is an additional benefit which is not immediately obvious. Basically, it's better than the sum of its parts. The whole mechanism <em>composes</em>. It scales.</p>
<p>If you use the <code>Line</code> class as a building block:</p>
<pre><code> class Table
{
Line borders[4];
};
</code></pre>
<p>Then</p>
<pre><code> int main ()
{
Table table;
}
</code></pre>
<p>allocates four <code>std::string</code> instances, four <code>Line</code> instances, one <code>Table</code> instance and all the string's contents and <em>everything is freed automagically</em>.</p> | {
"question_id": 6500313,
"question_date": "2011-06-28T00:08:14.313Z",
"question_score": 968,
"tags": "c++|memory-management|heap-memory|new-operator|c++-faq",
"answer_id": 6500497,
"answer_date": "2011-06-28T00:47:43.047Z",
"answer_score": 1144
} |
Please answer the following Stack Overflow question:
Title: Traverse a list in reverse order in Python
<p>How do I traverse a list in reverse order in Python? So I can start from <code>collection[len(collection)-1]</code> and end in <code>collection[0]</code>.</p>
<p>I also want to be able to access the loop index.</p> | <p>Use the built-in <a href="https://docs.python.org/library/functions.html#reversed" rel="noreferrer"><code>reversed()</code></a> function:</p>
<pre><code>>>> a = ["foo", "bar", "baz"]
>>> for i in reversed(a):
... print(i)
...
baz
bar
foo
</code></pre>
<p>To also access the original index, use <a href="https://docs.python.org/library/functions.html#enumerate" rel="noreferrer"><code>enumerate()</code></a> on your list before passing it to <code>reversed()</code>:</p>
<pre><code>>>> for i, e in reversed(list(enumerate(a))):
... print(i, e)
...
2 baz
1 bar
0 foo
</code></pre>
<p>Since <code>enumerate()</code> returns a generator and generators can't be reversed, you need to convert it to a <code>list</code> first.</p> | {
"question_id": 529424,
"question_date": "2009-02-09T19:04:58.527Z",
"question_score": 967,
"tags": "python|loops|reverse",
"answer_id": 529427,
"answer_date": "2009-02-09T19:05:54Z",
"answer_score": 1594
} |
Please answer the following Stack Overflow question:
Title: What is base 64 encoding used for?
<p>I've heard people talking about "base 64 encoding" here and there. What is it used for?</p> | <p>When you have some binary data that you want to ship across a network, you generally don't do it by just streaming the bits and bytes over the wire in a raw format. Why? because some media are made for streaming text. You never know -- some protocols may interpret your binary data as control characters (like a modem), or your binary data could be screwed up because the underlying protocol might think that you've entered a special character combination (like how FTP translates line endings). </p>
<p>So to get around this, people encode the binary data into characters. Base64 is one of these types of encodings. </p>
<p><strong>Why 64?</strong><br>
Because you can generally rely on the same 64 characters being present in many character sets, and you can be reasonably confident that your data's going to end up on the other side of the wire uncorrupted.</p> | {
"question_id": 201479,
"question_date": "2008-10-14T14:50:52.350Z",
"question_score": 967,
"tags": "encoding|base64|encode",
"answer_id": 201510,
"answer_date": "2008-10-14T14:56:19.063Z",
"answer_score": 1153
} |
Please answer the following Stack Overflow question:
Title: Is it possible to cherry-pick a commit from another git repository?
<p>I'm working with a git repository that needs a commit from another git repository that knows nothing of the first.</p>
<p>Typically I would cherry-pick using the <code>HEAD@{x}</code> in the reflog, but because this <code>.git</code> knows nothing of this reflog entry (different physical directory), how can I cherry-pick this, or can I?</p>
<p>I'm using <code>git-svn</code>. My first branch is using <code>git-svn</code> of the <code>trunk</code> of a Subversion repo, and the next branch is using <code>git-svn</code> on a Subversion branch.</p> | <p>You'll need to add the other repository as a remote, then fetch its changes. From there you see the commit and you can cherry-pick it.</p>
<p>Like that:</p>
<pre><code>git remote add other https://example.link/repository.git
git fetch other
</code></pre>
<p>Now you have all the information to simply do <a href="https://git-scm.com/docs/git-cherry-pick" rel="noreferrer"><code>git cherry-pick</code></a>.</p>
<p>When done, you may want to remove the remote again, if you don't need it any more, with</p>
<pre><code>git remote remove other
</code></pre>
<p>More info about working with remotes here: <a href="https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes" rel="noreferrer">https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes</a></p> | {
"question_id": 5120038,
"question_date": "2011-02-25T16:47:41.757Z",
"question_score": 967,
"tags": "git|cherry-pick",
"answer_id": 5120074,
"answer_date": "2011-02-25T16:50:46.200Z",
"answer_score": 843
} |
Please answer the following Stack Overflow question:
Title: Resetting remote to a certain commit
<p>I want to discard all changes done after commit <code><commit-hash></code> .
So I did:</p>
<pre><code>git reset --hard <commit-hash>
</code></pre>
<p>Now I want to do the same with my remote. How can I do this? I have done some commits (and pushes) after <code><commit-hash></code> and I just want to discard them all. Is just something went <em>terribly</em> wrong in the way and I don't want to make it worse than it is already. ;(</p>
<p>I basically want to rewind my <code>origin/master</code> to <code><commit-hash></code></p> | <p>Assuming that your branch is called <code>master</code> both here and remotely, and that your remote is called <code>origin</code> you could do:</p>
<pre><code> git reset --hard <commit-hash>
git push -f origin master
</code></pre>
<p>However, you should avoid doing this if anyone else is working with your remote repository and has pulled your changes. In that case, it would be better to <a href="http://www.kernel.org/pub/software/scm/git/docs/git-revert.html" rel="noreferrer">revert</a> the commits that you don't want, then push as normal.</p>
<p><strong>Update:</strong> you've explained below that other people have pulled the changes that you've pushed, so it's <strong>better to create a new commit that reverts all of those changes</strong>. There's a nice explanation of your options for doing this in <a href="https://stackoverflow.com/questions/1463340/revert-multiple-git-commits/1470452#1470452"><strong>this answer from Jakub Narębski</strong></a>. Which one is most convenient depends on how many commits you want to revert, and which method makes most sense to you.</p>
<p>Since from your question it's clear that you have already used <code>git reset --hard</code> to reset your <code>master</code> branch, you may need to start by using <code>git reset --hard ORIG_HEAD</code> to move your branch back to where it was before. (As always with <code>git reset --hard</code>, make sure that <code>git status</code> is clean, that you're on the right branch and that you're aware of <code>git reflog</code> as a tool to recover apparently lost commits.) You should also check that <code>ORIG_HEAD</code> points to the right commit, with <code>git show ORIG_HEAD</code>.</p>
<p><strong>Troubleshooting:</strong></p>
<p>If you get a message like "<em>! [remote rejected] a60f7d85 -> master (pre-receive hook declined)</em>" </p>
<p>then you have to allow branch history rewriting for the specific branch. In BitBucket for example it said "Rewriting branch history is not allowed". There is a checkbox named <code>Allow rewriting branch history</code> which you have to check.</p> | {
"question_id": 5816688,
"question_date": "2011-04-28T09:46:48.217Z",
"question_score": 966,
"tags": "git",
"answer_id": 5816761,
"answer_date": "2011-04-28T09:54:37.607Z",
"answer_score": 1703
} |
Please answer the following Stack Overflow question:
Title: How do emulators work and how are they written?
<p>How do emulators work? When I see NES/SNES or C64 emulators, it astounds me. </p>
<p><img src="https://i.stack.imgur.com/3BsOH.png" alt="http://www.tommowalker.co.uk/snemzelda.png"></p>
<p>Do you have to emulate the processor of those machines by interpreting its particular assembly instructions? What else goes into it? How are they typically designed?</p>
<p>Can you give any advice for someone interested in writing an emulator (particularly a game system)?</p> | <p>Emulation is a multi-faceted area. Here are the basic ideas and functional components. I'm going to break it into pieces and then fill in the details via edits. Many of the things I'm going to describe will require knowledge of the inner workings of processors -- assembly knowledge is necessary. If I'm a bit too vague on certain things, please ask questions so I can continue to improve this answer.</p>
<h2>Basic idea:</h2>
<p>Emulation works by handling the behavior of the processor and the individual components. You build each individual piece of the system and then connect the pieces much like wires do in hardware.</p>
<h2>Processor emulation:</h2>
<p>There are three ways of handling processor emulation:</p>
<ul>
<li>Interpretation</li>
<li>Dynamic recompilation</li>
<li>Static recompilation</li>
</ul>
<p>With all of these paths, you have the same overall goal: execute a piece of code to modify processor state and interact with 'hardware'. Processor state is a conglomeration of the processor registers, interrupt handlers, etc for a given processor target. For the 6502, you'd have a number of 8-bit integers representing registers: <code>A</code>, <code>X</code>, <code>Y</code>, <code>P</code>, and <code>S</code>; you'd also have a 16-bit <code>PC</code> register.</p>
<p>With interpretation, you start at the <code>IP</code> (instruction pointer -- also called <code>PC</code>, program counter) and read the instruction from memory. Your code parses this instruction and uses this information to alter processor state as specified by your processor. The core problem with interpretation is that it's <em>very</em> slow; each time you handle a given instruction, you have to decode it and perform the requisite operation.</p>
<p>With dynamic recompilation, you iterate over the code much like interpretation, but instead of just executing opcodes, you build up a list of operations. Once you reach a branch instruction, you compile this list of operations to machine code for your host platform, then you cache this compiled code and execute it. Then when you hit a given instruction group again, you only have to execute the code from the cache. (BTW, most people don't actually make a list of instructions but compile them to machine code on the fly -- this makes it more difficult to optimize, but that's out of the scope of this answer, unless enough people are interested)</p>
<p>With static recompilation, you do the same as in dynamic recompilation, but you follow branches. You end up building a chunk of code that represents all of the code in the program, which can then be executed with no further interference. This would be a great mechanism if it weren't for the following problems:</p>
<ul>
<li>Code that isn't in the program to begin with (e.g. compressed, encrypted, generated/modified at runtime, etc) won't be recompiled, so it won't run</li>
<li>It's been proven that finding all the code in a given binary is equivalent to the <a href="http://en.wikipedia.org/wiki/Halting_problem" rel="noreferrer">Halting problem</a></li>
</ul>
<p>These combine to make static recompilation completely infeasible in 99% of cases. For more information, Michael Steil has done some great research into static recompilation -- the best I've seen.</p>
<p>The other side to processor emulation is the way in which you interact with hardware. This really has two sides:</p>
<ul>
<li>Processor timing</li>
<li>Interrupt handling</li>
</ul>
<h2>Processor timing:</h2>
<p>Certain platforms -- especially older consoles like the NES, SNES, etc -- require your emulator to have strict timing to be completely compatible. With the NES, you have the PPU (pixel processing unit) which requires that the CPU put pixels into its memory at precise moments. If you use interpretation, you can easily count cycles and emulate proper timing; with dynamic/static recompilation, things are a /lot/ more complex.</p>
<h2>Interrupt handling:</h2>
<p>Interrupts are the primary mechanism that the CPU communicates with hardware. Generally, your hardware components will tell the CPU what interrupts it cares about. This is pretty straightforward -- when your code throws a given interrupt, you look at the interrupt handler table and call the proper callback.</p>
<h2>Hardware emulation:</h2>
<p>There are two sides to emulating a given hardware device:</p>
<ul>
<li>Emulating the functionality of the device</li>
<li>Emulating the actual device interfaces</li>
</ul>
<p>Take the case of a hard-drive. The functionality is emulated by creating the backing storage, read/write/format routines, etc. This part is generally very straightforward.</p>
<p>The actual interface of the device is a bit more complex. This is generally some combination of memory mapped registers (e.g. parts of memory that the device watches for changes to do signaling) and interrupts. For a hard-drive, you may have a memory mapped area where you place read commands, writes, etc, then read this data back.</p>
<p>I'd go into more detail, but there are a million ways you can go with it. If you have any specific questions here, feel free to ask and I'll add the info.</p>
<h2>Resources:</h2>
<p>I think I've given a pretty good intro here, but there are a <strong>ton</strong> of additional areas. I'm more than happy to help with any questions; I've been very vague in most of this simply due to the immense complexity.</p>
<h3>Obligatory Wikipedia links:</h3>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Emulator" rel="noreferrer">Emulator</a></li>
<li><a href="http://en.wikipedia.org/wiki/Dynamic_recompilation" rel="noreferrer">Dynamic recompilation</a></li>
</ul>
<h3>General emulation resources:</h3>
<ul>
<li><a href="http://www.zophar.net/" rel="noreferrer">Zophar</a> -- This is where I got my start with emulation, first downloading emulators and eventually plundering their immense archives of documentation. This is the absolute best resource you can possibly have.</li>
<li><a href="http://ngemu.com/" rel="noreferrer">NGEmu</a> -- Not many direct resources, but their forums are unbeatable.</li>
<li><a href="http://www.romhacking.net/" rel="noreferrer">RomHacking.net</a> -- The documents section contains resources regarding machine architecture for popular consoles</li>
</ul>
<h3>Emulator projects to reference:</h3>
<ul>
<li><a href="http://sourceforge.net/projects/ironbabel" rel="noreferrer">IronBabel</a> -- This is an emulation platform for .NET, written in Nemerle and recompiles code to C# on the fly. Disclaimer: This is my project, so pardon the shameless plug.</li>
<li><a href="http://byuu.org/bsnes/" rel="noreferrer">BSnes</a> -- An awesome SNES emulator with the goal of cycle-perfect accuracy.</li>
<li><a href="http://www.mamedev.org/" rel="noreferrer">MAME</a> -- <strong>The</strong> arcade emulator. Great reference.</li>
<li><a href="http://6502asm.com/" rel="noreferrer">6502asm.com</a> -- This is a JavaScript 6502 emulator with a cool little forum.</li>
<li><a href="http://ironbabel.googlepages.com/6502.html" rel="noreferrer">dynarec'd 6502asm</a> -- This is a little hack I did over a day or two. I took the existing emulator from 6502asm.com and changed it to dynamically recompile the code to JavaScript for massive speed increases.</li>
</ul>
<h3>Processor recompilation references:</h3>
<ul>
<li>The research into static recompilation done by Michael Steil (referenced above) culminated in <a href="http://www.weihenstephan.org/%7Emichaste/down/steil-recompilation.pdf" rel="noreferrer">this paper</a> and you can find source and such <a href="http://www.pagetable.com/?p=35" rel="noreferrer">here</a>.</li>
</ul>
<h2>Addendum:</h2>
<p>It's been well over a year since this answer was submitted and with all the attention it's been getting, I figured it's time to update some things.</p>
<p>Perhaps the most exciting thing in emulation right now is <a href="http://www.libcpu.org/wiki/Main_Page" rel="noreferrer">libcpu</a>, started by the aforementioned Michael Steil. It's a library intended to support a large number of CPU cores, which use LLVM for recompilation (static and dynamic!). It's got huge potential, and I think it'll do great things for emulation.</p>
<p><a href="http://emudocs.org/" rel="noreferrer">emu-docs</a> has also been brought to my attention, which houses a great repository of system documentation, which is very useful for emulation purposes. I haven't spent much time there, but it looks like they have a lot of great resources.</p>
<p>I'm glad this post has been helpful, and I'm hoping I can get off my arse and finish up my book on the subject by the end of the year/early next year.</p> | {
"question_id": 448673,
"question_date": "2009-01-15T22:10:15.827Z",
"question_score": 966,
"tags": "emulation|c64",
"answer_id": 448689,
"answer_date": "2009-01-15T22:13:48.723Z",
"answer_score": 1121
} |
Please answer the following Stack Overflow question:
Title: How to list containers in Docker
<p>There's a command to list images, <code>docker images</code>, but there doesn't seem to be a corresponding <code>docker containers</code>.</p>
<p>Other than becoming root and looking into <code>/var/lib/docker</code> there doesn't seem a way to do that. Am I missing something? Is that something one isn't supposed to do?</p> | <p>To show only <strong>running containers</strong> use the given command:</p>
<pre><code>docker ps
</code></pre>
<p>To show <strong>all containers</strong> use the given command:</p>
<pre><code>docker ps -a
</code></pre>
<p>To show the <strong>latest created container</strong> (includes all states) use the given command:</p>
<pre><code>docker ps -l
</code></pre>
<p>To show <strong>n last created containers</strong> (includes all states) use the given command:</p>
<pre><code>docker ps -n=-1
</code></pre>
<p>To display <strong>total file sizes</strong> use the given command:</p>
<pre><code>docker ps -s
</code></pre>
<p>The content presented above is from <a href="https://docs.docker.com/v1.11/engine/reference/commandline/ps/" rel="noreferrer">docker.com</a>.</p>
<p>In the new version of Docker, commands are updated, and some management commands are added:</p>
<pre><code>docker container ls
</code></pre>
<p>It is used to list all the running containers.</p>
<pre><code>docker container ls -a
</code></pre>
<p>And then, if you want to clean them all,</p>
<pre><code>docker rm $(docker ps -aq)
</code></pre>
<p>It is used to list all the containers created irrespective of its state.</p>
<p>And to stop all the Docker containers (force)</p>
<pre><code>docker rm -f $(docker ps -a -q)
</code></pre>
<p>Here the container is the management command.</p> | {
"question_id": 16840409,
"question_date": "2013-05-30T15:41:46.910Z",
"question_score": 965,
"tags": "docker",
"answer_id": 16842203,
"answer_date": "2013-05-30T17:15:11.927Z",
"answer_score": 1806
} |
Please answer the following Stack Overflow question:
Title: How to get the browser viewport dimensions?
<p>I want to provide my visitors the ability to see images in high quality, is there any way I can detect the window size?</p>
<p>Or better yet, the viewport size of the browser with JavaScript? See green area here:</p>
<p><a href="https://i.stack.imgur.com/zYrB7.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/zYrB7.jpg" alt=""></a></p> | <h2><b>Cross-browser</b> <a href="http://dev.w3.org/csswg/mediaqueries/#width" rel="noreferrer"><code>@media (width)</code></a> and <a href="http://dev.w3.org/csswg/mediaqueries/#height" rel="noreferrer"><code>@media (height)</code></a> values </h2>
<pre class="lang-js prettyprint-override"><code>const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)
</code></pre>
<h2><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/innerWidth" rel="noreferrer"><code>window.innerWidth</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/innerHeight" rel="noreferrer"><code>window.innerHeight</code></a></h2>
<ul>
<li>gets <a href="http://www.w3.org/TR/CSS2/visuren.html#viewport" rel="noreferrer">CSS viewport</a> <code>@media (width)</code> and <code>@media (height)</code> which include scrollbars</li>
<li><code>initial-scale</code> and zoom <a href="https://github.com/ryanve/verge/issues/13" rel="noreferrer">variations</a> may cause mobile values to <b>wrongly</b> scale down to what PPK calls the <a href="http://www.quirksmode.org/mobile/viewports2.html" rel="noreferrer">visual viewport</a> and be smaller than the <code>@media</code> values</li>
<li>zoom may cause values to be 1px off due to native rounding</li>
<li><code>undefined</code> in IE8-</li>
</ul>
<h2><a href="https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements#What.27s_the_size_of_the_displayed_content.3F" rel="noreferrer"><code>document.documentElement.clientWidth</code></a> and <code>.clientHeight</code></h2>
<ul>
<li>equals CSS viewport width <strong>minus</strong> scrollbar width</li>
<li>matches <code>@media (width)</code> and <code>@media (height)</code> when there is <strong>no</strong> scrollbar</li>
<li><a href="https://github.com/jquery/jquery/blob/1.9.1/src/dimensions.js#L12-L17" rel="noreferrer">same as</a> <code>jQuery(window).width()</code> which <a href="https://api.jquery.com/width/" rel="noreferrer">jQuery</a> <em>calls</em> the browser viewport</li>
<li><a href="http://www.quirksmode.org/mobile/tableViewport.html" rel="noreferrer">available cross-browser</a></li>
<li><a href="https://github.com/ryanve/verge/issues/22#issuecomment-341944009" rel="noreferrer">inaccurate if doctype is missing</a></li>
</ul>
<hr />
<h2>Resources</h2>
<ul>
<li><a href="http://ryanve.com/lab/dimensions/" rel="noreferrer">Live outputs for various dimensions</a></li>
<li><a href="http://github.com/ryanve/verge" rel="noreferrer"><b>verge</b></a> uses cross-browser viewport techniques</li>
<li><a href="http://github.com/ryanve/actual" rel="noreferrer"><b>actual</b></a> uses <code>matchMedia</code> to obtain precise dimensions in any unit</li>
</ul> | {
"question_id": 1248081,
"question_date": "2009-08-08T05:54:41.810Z",
"question_score": 965,
"tags": "javascript|cross-browser|viewport",
"answer_id": 8876069,
"answer_date": "2012-01-16T05:23:11.690Z",
"answer_score": 1599
} |
Please answer the following Stack Overflow question:
Title: How do I use optional parameters in Java?
<p>What specification supports optional parameters?</p> | <p>There are several ways to simulate optional parameters in Java:</p>
<ol>
<li><p><strong>Method overloading.</strong></p>
<p>void foo(String a, Integer b) {
//...
}</p>
<p>void foo(String a) {
foo(a, 0); // here, 0 is a default value for b
}</p>
<p>foo("a", 2);
foo("a");</p>
</li>
</ol>
<p>One of the limitations of this approach is that it doesn't work if you have two optional parameters of the same type and any of them can be omitted.</p>
<ol>
<li><strong>Varargs.</strong></li>
</ol>
<p>a) All optional parameters are of the same type:</p>
<pre><code> void foo(String a, Integer... b) {
Integer b1 = b.length > 0 ? b[0] : 0;
Integer b2 = b.length > 1 ? b[1] : 0;
//...
}
foo("a");
foo("a", 1, 2);
</code></pre>
<p>b) Types of optional parameters may be different:</p>
<pre><code> void foo(String a, Object... b) {
Integer b1 = 0;
String b2 = "";
if (b.length > 0) {
if (!(b[0] instanceof Integer)) {
throw new IllegalArgumentException("...");
}
b1 = (Integer)b[0];
}
if (b.length > 1) {
if (!(b[1] instanceof String)) {
throw new IllegalArgumentException("...");
}
b2 = (String)b[1];
//...
}
//...
}
foo("a");
foo("a", 1);
foo("a", 1, "b2");
</code></pre>
<p>The main drawback of this approach is that if optional parameters are of different types you lose static type checking. Furthermore, if each parameter has the different meaning you need some way to distinguish them.</p>
<ol>
<li><p><strong>Nulls.</strong> To address the limitations of the previous approaches you can allow null values and then analyze each parameter in a method body:</p>
<p>void foo(String a, Integer b, Integer c) {
b = b != null ? b : 0;
c = c != null ? c : 0;
//...
}</p>
<p>foo("a", null, 2);</p>
</li>
</ol>
<p>Now all arguments values must be provided, but the default ones may be null.</p>
<ol>
<li><p><strong>Optional class.</strong> This approach is similar to nulls, but uses Java 8 Optional class for parameters that have a default value:</p>
<p>void foo(String a, Optional bOpt) {
Integer b = bOpt.isPresent() ? bOpt.get() : 0;
//...
}</p>
<p>foo("a", Optional.of(2));
foo("a", Optional.absent());</p>
<p>Optional makes a method contract explicit for a caller, however, one may find such signature too verbose.</p>
<p>Update: Java 8 includes the class <code>java.util.Optional</code> out-of-the-box, so there is no need to use guava for this particular reason in Java 8. The method name is a bit different though.</p>
</li>
<li><p><strong>Builder pattern.</strong> The builder pattern is used for constructors and is implemented by introducing a separate Builder class:</p>
<pre><code>class Foo {
private final String a;
private final Integer b;
Foo(String a, Integer b) {
this.a = a;
this.b = b;
}
//...
}
class FooBuilder {
private String a = "";
private Integer b = 0;
FooBuilder setA(String a) {
this.a = a;
return this;
}
FooBuilder setB(Integer b) {
this.b = b;
return this;
}
Foo build() {
return new Foo(a, b);
}
}
Foo foo = new FooBuilder().setA("a").build();
</code></pre>
</li>
<li><p><strong>Maps.</strong> When the number of parameters is too large and for most of the default values are usually used, you can pass method arguments as a map of their names/values:</p>
<p>void foo(Map<String, Object> parameters) {
String a = "";
Integer b = 0;
if (parameters.containsKey("a")) {
if (!(parameters.get("a") instanceof Integer)) {
throw new IllegalArgumentException("...");
}
a = (Integer)parameters.get("a");
}
if (parameters.containsKey("b")) {
//...
}
//...
}</p>
<p>foo(ImmutableMap.<String, Object>of(
"a", "a",
"b", 2,
"d", "value"));</p>
<p>In Java 9, this approach became easier:</p>
<pre><code>@SuppressWarnings("unchecked")
static <T> T getParm(Map<String, Object> map, String key, T defaultValue) {
return (map.containsKey(key)) ? (T) map.get(key) : defaultValue;
}
void foo(Map<String, Object> parameters) {
String a = getParm(parameters, "a", "");
int b = getParm(parameters, "b", 0);
// d = ...
}
foo(Map.of("a","a", "b",2, "d","value"));
</code></pre>
</li>
</ol>
<p>Please note that you can combine any of these approaches to achieve a desirable result.</p> | {
"question_id": 965690,
"question_date": "2009-06-08T16:12:29.980Z",
"question_score": 964,
"tags": "java|optional-parameters",
"answer_id": 12994104,
"answer_date": "2012-10-21T01:16:11.193Z",
"answer_score": 1848
} |
Please answer the following Stack Overflow question:
Title: Importing modules from parent folder
<p>I am running Python 2.5.</p>
<p>This is my folder tree:</p>
<pre><code>ptdraft/
nib.py
simulations/
life/
life.py
</code></pre>
<p>(I also have <code>__init__.py</code> in each folder, omitted here for readability)</p>
<p>How do I import the <code>nib</code> module from inside the <code>life</code> module? I am hoping it is possible to do without tinkering with sys.path.</p>
<p>Note: The main module being run is in the <code>ptdraft</code> folder.</p> | <p>It seems that the problem is not related to the module being in a parent directory or anything like that.</p>
<p>You need to add the directory that contains <code>ptdraft</code> to PYTHONPATH</p>
<p>You said that <code>import nib</code> worked with you, that probably means that you added <code>ptdraft</code> itself (not its parent) to PYTHONPATH.</p> | {
"question_id": 714063,
"question_date": "2009-04-03T14:08:02.190Z",
"question_score": 964,
"tags": "python|module|path|directory|python-import",
"answer_id": 714070,
"answer_date": "2009-04-03T14:09:23.840Z",
"answer_score": 152
} |
Please answer the following Stack Overflow question:
Title: Why use pip over easy_install?
<p>A <a href="http://twitter.com/jperras/statuses/18160589493" rel="noreferrer">tweet</a> reads: </p>
<blockquote>
<p>Don't use easy_install, unless you
like stabbing yourself in the face.
Use pip.</p>
</blockquote>
<p>Why use pip over easy_install? Doesn't the <a href="http://mail.python.org/pipermail/catalog-sig/2010-June/002985.html" rel="noreferrer">fault lie with PyPI and package authors mostly</a>? If an author uploads crap source tarball (eg: missing files, no setup.py) to PyPI, then both pip and easy_install will fail. Other than cosmetic differences, why do Python people (like in the above tweet) seem to <strong>strongly</strong> favor pip over easy_install?</p>
<p>(Let's assume that we're talking about easy_install from the Distribute package, that is maintained by the community)</p> | <p>Many of the answers here are out of date for 2015 (although <a href="https://stackoverflow.com/a/3220572/908494">the initially accepted one from Daniel Roseman</a> is not). Here's the current state of things:</p>
<ul>
<li>Binary packages are now distributed as wheels (<code>.whl</code> files)—not just on PyPI, but in third-party repositories like <a href="http://www.lfd.uci.edu/~gohlke/pythonlibs/" rel="noreferrer">Christoph Gohlke's Extension Packages for Windows</a>. <code>pip</code> can handle wheels; <code>easy_install</code> cannot.</li>
<li>Virtual environments (which come built-in with 3.4, or can be added to 2.6+/3.1+ with <a href="https://pypi.python.org/pypi/virtualenv" rel="noreferrer"><code>virtualenv</code></a>) have become a very important and prominent tool (and recommended in <a href="https://docs.python.org/3/installing/index.html" rel="noreferrer">the official docs</a>); they include <code>pip</code> out of the box, but don't even work properly with <code>easy_install</code>.</li>
<li>The <code>distribute</code> package that included <code>easy_install</code> is no longer maintained. Its improvements over <code>setuptools</code> got merged back into <code>setuptools</code>. Trying to install <code>distribute</code> will just install <code>setuptools</code> instead.</li>
<li><code>easy_install</code> itself is only quasi-maintained.</li>
<li>All of the cases where <code>pip</code> used to be inferior to <code>easy_install</code>—installing from an unpacked source tree, from a DVCS repo, etc.—are long-gone; you can <code>pip install .</code>, <code>pip install git+https://</code>.</li>
<li><code>pip</code> comes with the official Python 2.7 and 3.4+ packages from python.org, and a <code>pip</code> bootstrap is included by default if you build from source.</li>
<li>The various incomplete bits of documentation on installing, using, and building packages have been replaced by the <a href="https://packaging.python.org/" rel="noreferrer">Python Packaging User Guide</a>. Python's own documentation on <a href="https://docs.python.org/3/installing/index.html" rel="noreferrer">Installing Python Modules</a> now defers to this user guide, and explicitly calls out <code>pip</code> as "the preferred installer program".</li>
<li>Other new features have been added to <code>pip</code> over the years that will never be in <code>easy_install</code>. For example, <code>pip</code> makes it easy to clone your site-packages by building a requirements file and then installing it with a single command on each side. Or to convert your requirements file to a local repo to use for in-house development. And so on.</li>
</ul>
<p>The only good reason that I know of to use <code>easy_install</code> in 2015 is the special case of using Apple's pre-installed Python versions with OS X 10.5-10.8. Since 10.5, Apple has included <code>easy_install</code>, but as of 10.10 they still don't include <code>pip</code>. With 10.9+, you should still just use <code>get-pip.py</code>, but for 10.5-10.8, this has some problems, so it's easier to <code>sudo easy_install pip</code>. (In general, <code>easy_install pip</code> is a bad idea; it's only for OS X 10.5-10.8 that you want to do this.) Also, 10.5-10.8 include <code>readline</code> in a way that <code>easy_install</code> knows how to kludge around but <code>pip</code> doesn't, so you also want to <code>sudo easy_install readline</code> if you want to upgrade that.</p> | {
"question_id": 3220404,
"question_date": "2010-07-10T18:35:54.937Z",
"question_score": 964,
"tags": "python|pip|setuptools|easy-install|pypi",
"answer_id": 30408520,
"answer_date": "2015-05-23T03:10:30.550Z",
"answer_score": 316
} |
Please answer the following Stack Overflow question:
Title: Convert InputStream to byte array in Java
<p>How do I read an entire <code>InputStream</code> into a byte array?</p> | <p>You can use Apache <a href="http://commons.apache.org/io/" rel="noreferrer">Commons IO</a> to handle this and similar tasks.</p>
<p>The <code>IOUtils</code> type has a static method to read an <code>InputStream</code> and return a <code>byte[]</code>.</p>
<pre><code>InputStream is;
byte[] bytes = IOUtils.toByteArray(is);
</code></pre>
<p>Internally this creates a <code>ByteArrayOutputStream</code> and copies the bytes to the output, then calls <code>toByteArray()</code>. It handles large files by copying the bytes in blocks of 4KiB.</p> | {
"question_id": 1264709,
"question_date": "2009-08-12T07:27:22.193Z",
"question_score": 963,
"tags": "java|bytearray|inputstream",
"answer_id": 1264756,
"answer_date": "2009-08-12T07:35:54.517Z",
"answer_score": 1257
} |
Please answer the following Stack Overflow question:
Title: How do I clone a single branch in Git?
<p>I have a local Git repository in <code>~/local_repo</code>. It has a few branches:</p>
<pre><code>$ git branch
* master
rails
c
c++
</code></pre>
<p>To clone the local repository, I do:</p>
<pre><code>$ git clone ~/local_repo new_repo
Initialized empty Git repository in /home/username/new_repo/.git/
</code></pre>
<p>The <code>new_repo</code> master branch points to the <code>local_repo</code> master branch, and I can push / pull.</p>
<p>But I am unable to clone another branch. I want to only pull the branch I want (e.g. <code>rails</code>), so that the new repository has a <code>master</code> branch that pushes to and pulls from <code>local_repo</code>'s <code>rails</code> branch, by default. How do I accomplish this, or perhaps something similar with <code>local_repo</code> tracking the master <code>local_repo</code>?</p> | <p>Note: the <strong><a href="https://lkml.org/lkml/2012/3/28/418" rel="noreferrer">git1.7.10</a> (April 2012)</strong> actually allows you to <strong>clone only one branch</strong>:</p>
<pre class="lang-bash prettyprint-override"><code># clone only the remote primary HEAD (default: origin/master)
git clone <url> --single-branch
# as in:
git clone <url> --branch <branch> --single-branch [<folder>]
</code></pre>
<p>(<code><url></code> is the URL if the remote repository, and does not reference itself the branch cloned)</p>
<p>You can see it in <a href="https://github.com/git/git/blob/master/t/t5500-fetch-pack.sh" rel="noreferrer"><code>t5500-fetch-pack.sh</code></a>:</p>
<pre class="lang-bash prettyprint-override"><code>test_expect_success 'single branch clone' '
git clone --single-branch "file://$(pwd)/." singlebranch
'
</code></pre>
<p><a href="https://stackoverflow.com/users/229753/tobu">Tobu</a> <a href="https://stackoverflow.com/questions/1778088/how-to-clone-a-single-branch-in-git/9920956?noredirect=1#comment27508922_9920956">comments</a> that:</p>
<blockquote>
<p><strong>This is implicit when doing a shallow clone.<br />
This makes <code>git clone --depth 1</code> the easiest way to save bandwidth.</strong></p>
</blockquote>
<p>And since Git 1.9.0 (February 2014), shallow clones support data transfer (push/pull), so that option is even more useful now.<br />
See more at "<a href="https://stackoverflow.com/a/21217267/6309">Is <code>git clone --depth 1</code> (shallow clone) more useful than it makes out?</a>".</p>
<hr />
<p>"Undoing" a shallow clone is detailed at "<a href="https://stackoverflow.com/a/17937889/6309">Convert shallow clone to full clone</a>" (git 1.8.3+)</p>
<pre class="lang-bash prettyprint-override"><code># unshallow the current branch
git fetch --unshallow
# for getting back all the branches (see Peter Cordes' comment)
git config remote.origin.fetch refs/heads/*:refs/remotes/origin/*
git fetch --unshallow
</code></pre>
<p>As <a href="https://stackoverflow.com/users/1308967/chris">Chris</a> comments:</p>
<blockquote>
<p>the magic line for getting missing branches to reverse <code>--single-branch</code> is (git v2.1.4):</p>
</blockquote>
<pre class="lang-bash prettyprint-override"><code>git config remote.origin.fetch +refs/heads/*:refs/remotes/origin/*
git fetch --unshallow
</code></pre>
<hr />
<p>With Git 2.26 (Q1 2020), "<code>git clone --recurse-submodules --single-branch</code>" <strong>now uses the same single-branch option when cloning the submodules</strong>.</p>
<p>See <a href="https://github.com/git/git/commit/132f600b060c2db7fd3d450dfadb6779a61c648a" rel="noreferrer">commit 132f600</a>, <a href="https://github.com/git/git/commit/47319576f112b60ecd85930d162cd7656132fd0d" rel="noreferrer">commit 4731957</a> (21 Feb 2020) by <a href="https://github.com/nasamuffin" rel="noreferrer">Emily Shaffer (<code>nasamuffin</code>)</a>.<br />
<sup>(Merged by <a href="https://github.com/gitster" rel="noreferrer">Junio C Hamano -- <code>gitster</code> --</a> in <a href="https://github.com/git/git/commit/b22db265d6bde72391c8d47700dc781a3ea2ae41" rel="noreferrer">commit b22db26</a>, 05 Mar 2020)</sup></p>
<blockquote>
<h2><a href="https://github.com/git/git/commit/132f600b060c2db7fd3d450dfadb6779a61c648a" rel="noreferrer"><code>clone</code></a>: pass --single-branch during --recurse-submodules</h2>
<p><sup>Signed-off-by: Emily Shaffer</sup><br />
<sup>Acked-by: Jeff King</sup></p>
<p>Previously, performing "<code>git clone --recurse-submodules --single-branch</code>" resulted in submodules cloning all branches even though the superproject cloned only one branch.</p>
<p>Pipe <code>--single-branch</code> through the submodule helper framework to make it to '<code>clone</code>' later on.</p>
</blockquote> | {
"question_id": 1778088,
"question_date": "2009-11-22T07:21:19.420Z",
"question_score": 962,
"tags": "git|branch|git-clone",
"answer_id": 9920956,
"answer_date": "2012-03-29T07:34:01.897Z",
"answer_score": 1049
} |
Please answer the following Stack Overflow question:
Title: Best way to repeat a character in C#
<p>What is the best way to generate a string of <code>\t</code>'s in C#</p>
<p>I am learning C# and experimenting with different ways of saying the same thing.</p>
<p><code>Tabs(uint t)</code> is a function that returns a <code>string</code> with <code>t</code> amount of <code>\t</code>'s</p>
<p>For example <code>Tabs(3)</code> returns <code>"\t\t\t"</code></p>
<p>Which of these three ways of implementing <code>Tabs(uint numTabs)</code> is best?</p>
<p>Of course that depends on what "best" means.</p>
<ol>
<li><p>The LINQ version is only two lines, which is nice. But are the calls to Repeat and Aggregate unnecessarily time/resource consuming?</p>
</li>
<li><p>The <code>StringBuilder</code> version is very clear but is the <code>StringBuilder</code> class somehow slower?</p>
</li>
<li><p>The <code>string</code> version is basic, which means it is easy to understand.</p>
</li>
<li><p>Does it not matter at all? Are they all equal?</p>
</li>
</ol>
<p>These are all questions to help me get a better feel for C#.</p>
<pre><code>private string Tabs(uint numTabs)
{
IEnumerable<string> tabs = Enumerable.Repeat("\t", (int) numTabs);
return (numTabs > 0) ? tabs.Aggregate((sum, next) => sum + next) : "";
}
private string Tabs(uint numTabs)
{
StringBuilder sb = new StringBuilder();
for (uint i = 0; i < numTabs; i++)
sb.Append("\t");
return sb.ToString();
}
private string Tabs(uint numTabs)
{
string output = "";
for (uint i = 0; i < numTabs; i++)
{
output += '\t';
}
return output;
}
</code></pre> | <p>What about this:</p>
<pre><code>string tabs = new string('\t', n);
</code></pre>
<p>Where <code>n</code> is the number of times you want to repeat the string.</p>
<p>Or better:</p>
<pre><code>static string Tabs(int n)
{
return new string('\t', n);
}
</code></pre> | {
"question_id": 411752,
"question_date": "2009-01-04T21:56:59.597Z",
"question_score": 962,
"tags": "c#|.net|string",
"answer_id": 411762,
"answer_date": "2009-01-04T22:00:39.060Z",
"answer_score": 1777
} |
Please answer the following Stack Overflow question:
Title: What is std::move(), and when should it be used?
<ol>
<li>What is it?</li>
<li>What does it do?</li>
<li>When should it be used?</li>
</ol>
<p>Good links are appreciated.</p> | <p><a href="https://en.wikipedia.org/wiki/C%2B%2B11#Rvalue_references_and_move_constructors" rel="noreferrer">Wikipedia Page on C++11 R-value references and move constructors</a></p>
<ol>
<li>In C++11, in addition to copy constructors, objects can have move constructors.<br>
(And in addition to copy assignment operators, they have move assignment operators.)</li>
<li>The move constructor is used instead of the copy constructor, if the object has type "rvalue-reference" (<code>Type &&</code>).</li>
<li><code>std::move()</code> is a cast that produces an rvalue-reference to an object, to enable moving from it.</li>
</ol>
<p>It's a new C++ way to avoid copies. For example, using a move constructor, a <code>std::vector</code> could just copy its internal pointer to data to the new object, leaving the moved object in an moved from state, therefore not copying all the data. This would be C++-valid.</p>
<p>Try googling for move semantics, rvalue, perfect forwarding.</p> | {
"question_id": 3413470,
"question_date": "2010-08-05T09:42:46.203Z",
"question_score": 962,
"tags": "c++|c++11|move-semantics|c++-faq|stdmove",
"answer_id": 3413547,
"answer_date": "2010-08-05T09:52:16.637Z",
"answer_score": 396
} |
Please answer the following Stack Overflow question:
Title: __proto__ VS. prototype in JavaScript
<blockquote>
<p>This figure again shows that every object has a prototype. Constructor
function Foo also has its own <code>__proto__</code> which is Function.prototype,
and which in turn also references via its <code>__proto__</code> property again to
the Object.prototype. Thus, repeat, Foo.prototype is just an explicit
property of Foo which refers to the prototype of b and c objects.</p>
</blockquote>
<pre><code>var b = new Foo(20);
var c = new Foo(30);
</code></pre>
<p>What are the differences between <code>__proto__</code> and <code>prototype</code>?</p>
<p><img src="https://i.stack.imgur.com/UfXRZ.png" alt="enter image description here" /></p>
<p>The figure was taken from <a href="http://dmitrysoshnikov.com/ecmascript/javascript-the-core/" rel="noreferrer">dmitrysoshnikov.com</a>.</p>
<p><em>Note: there is now <a href="http://dmitrysoshnikov.com/ecmascript/javascript-the-core-2nd-edition/" rel="noreferrer">a 2nd edition (2017)</a> to the above 2010 article.</em></p> | <p><code>__proto__</code> is the actual object that is used in the lookup chain to resolve methods, etc. <code>prototype</code> is the object that is used to build <code>__proto__</code> when you create an object with <code>new</code>:</p>
<pre><code>( new Foo ).__proto__ === Foo.prototype
( new Foo ).prototype === undefined
</code></pre> | {
"question_id": 9959727,
"question_date": "2012-03-31T21:13:13.973Z",
"question_score": 962,
"tags": "javascript|prototype|javascript-objects|prototypal-inheritance",
"answer_id": 9959753,
"answer_date": "2012-03-31T21:16:59.023Z",
"answer_score": 937
} |
Please answer the following Stack Overflow question:
Title: Should CSS always precede JavaScript?
<p>In countless places online I have seen the recommendation to include CSS prior to JavaScript. The reasoning is generally, <a href="https://stackoverflow.com/questions/6005827/what-can-i-do-to-decrease-load-times-of-html-pages/6005832#6005832">of this form</a>:</p>
<blockquote>
<p>When it comes to ordering your CSS and JavaScript, you want your CSS
to come first. The reason is that the rendering thread has all the
style information it needs to render the page. If the JavaScript
includes come first, the JavaScript engine has to parse it all before
continuing on to the next set of resources. This means the rendering
thread can't completely show the page, since it doesn't have all the
styles it needs.</p>
</blockquote>
<p>My actual testing reveals something quite different:</p>
<h3>My test harness</h3>
<p>I use the following <a href="https://en.wikipedia.org/wiki/Ruby_%28programming_language%29" rel="nofollow noreferrer">Ruby</a> script to generate specific delays for various resources:</p>
<pre><code>require 'rubygems'
require 'eventmachine'
require 'evma_httpserver'
require 'date'
class Handler < EventMachine::Connection
include EventMachine::HttpServer
def process_http_request
resp = EventMachine::DelegatedHttpResponse.new( self )
return unless @http_query_string
path = @http_path_info
array = @http_query_string.split("&").map{|s| s.split("=")}.flatten
parsed = Hash[*array]
delay = parsed["delay"].to_i / 1000.0
jsdelay = parsed["jsdelay"].to_i
delay = 5 if (delay > 5)
jsdelay = 5000 if (jsdelay > 5000)
delay = 0 if (delay < 0)
jsdelay = 0 if (jsdelay < 0)
# Block which fulfills the request
operation = proc do
sleep delay
if path.match(/.js$/)
resp.status = 200
resp.headers["Content-Type"] = "text/javascript"
resp.content = "(function(){
var start = new Date();
while(new Date() - start < #{jsdelay}){}
})();"
end
if path.match(/.css$/)
resp.status = 200
resp.headers["Content-Type"] = "text/css"
resp.content = "body {font-size: 50px;}"
end
end
# Callback block to execute once the request is fulfilled
callback = proc do |res|
resp.send_response
end
# Let the thread pool (20 Ruby threads) handle request
EM.defer(operation, callback)
end
end
EventMachine::run {
EventMachine::start_server("0.0.0.0", 8081, Handler)
puts "Listening..."
}
</code></pre>
<p>The above mini server allows me to set arbitrary delays for JavaScript files (both server and client) and arbitrary CSS delays. For example, <code>http://10.0.0.50:8081/test.css?delay=500</code> gives me a 500 ms delay transferring the CSS.</p>
<p>I use the following page to test.</p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>test</title>
<script type='text/javascript'>
var startTime = new Date();
</script>
<link href="http://10.0.0.50:8081/test.css?delay=500" type="text/css" rel="stylesheet">
<script type="text/javascript" src="http://10.0.0.50:8081/test2.js?delay=400&amp;jsdelay=1000"></script>
</head>
<body>
<p>
Elapsed time is:
<script type='text/javascript'>
document.write(new Date() - startTime);
</script>
</p>
</body>
</html>
</code></pre>
<p>When I include the CSS first, the page takes 1.5 seconds to render:</p>
<p><img src="https://i.stack.imgur.com/ZDgrs.png" alt="CSS first" /></p>
<p>When I include the JavaScript first, the page takes 1.4 seconds to render:</p>
<p><img src="https://i.stack.imgur.com/5o5SG.png" alt="JavaScript first" /></p>
<p>I get similar results in Chrome, Firefox and Internet Explorer. In <a href="https://en.wikipedia.org/wiki/Opera_%28web_browser%29" rel="nofollow noreferrer">Opera</a>, however, the ordering simply does not matter.</p>
<p>What appears to be happening is that the JavaScript interpreter refuses to start until all the CSS is downloaded. So, it seems that having JavaScript includes first is more efficient as the JavaScript thread gets more run time.</p>
<p>Am I missing something? Is the recommendation to place CSS includes prior to JavaScript includes not correct?</p>
<p><sub>It is clear that we could add async or use setTimeout to free up the render thread or put the JavaScript code in the footer, or use a JavaScript loader. The point here is about ordering of essential JavaScript bits and CSS bits in the head.</sub></p> | <p>This is a very interesting question. I've always put my CSS <code><link href="..."></code>s before my JavaScript <code><script src="..."></code>s because "I read one time that it's better." So, you're right; it's high time we do some actual research!</p>
<p>I set up my own test harness in <a href="https://en.wikipedia.org/wiki/Node.js" rel="nofollow noreferrer">Node.js</a> (code below). Basically, I:</p>
<ul>
<li>Made sure there was no HTTP caching so the browser would have to do a full download each time a page is loaded.</li>
<li>To simulate reality, I included jQuery and the <a href="http://html5boilerplate.com/" rel="nofollow noreferrer">H5BP</a> CSS (so there's a decent amount of script/CSS to parse)</li>
<li>Set up two pages - one with CSS before script, one with CSS after script.</li>
<li>Recorded how long it took for the external script in the <strong><code><head></code></strong> to execute</li>
<li>Recorded how long it took for the inline script in the <strong><code><body></code></strong> to execute, which is analogous to <code>DOMReady</code>.</li>
<li>Delayed sending CSS and/or script to the browser by 500 ms.</li>
<li>Ran the test 20 times in the three major browsers.</li>
</ul>
<h1>Results</h1>
<p>First, with the CSS file delayed by 500 ms (the unit is milliseconds):</p>
<pre class="lang-none prettyprint-override"><code> Browser: Chrome 18 | IE 9 | Firefox 9
CSS: first last | first last | first last
=======================================================
Header Exec | | |
Average | 583 36 | 559 42 | 565 49
St Dev | 15 12 | 9 7 | 13 6
------------|--------------|--------------|------------
Body Exec | | |
Average | 584 521 | 559 513 | 565 519
St Dev | 15 9 | 9 5 | 13 7
</code></pre>
<p>Next, I set jQuery to delay by 500 ms instead of the CSS:</p>
<pre class="lang-none prettyprint-override"><code> Browser: Chrome 18 | IE 9 | Firefox 9
CSS: first last | first last | first last
=======================================================
Header Exec | | |
Average | 597 556 | 562 559 | 564 564
St Dev | 14 12 | 11 7 | 8 8
------------|--------------|--------------|------------
Body Exec | | |
Average | 598 557 | 563 560 | 564 565
St Dev | 14 12 | 10 7 | 8 8
</code></pre>
<p>Finally, I set <strong>both</strong> jQuery and the CSS to delay by 500 ms:</p>
<pre class="lang-none prettyprint-override"><code> Browser: Chrome 18 | IE 9 | Firefox 9
CSS: first last | first last | first last
=======================================================
Header Exec | | |
Average | 620 560 | 577 577 | 571 567
St Dev | 16 11 | 19 9 | 9 10
------------|--------------|--------------|------------
Body Exec | | |
Average | 623 561 | 578 580 | 571 568
St Dev | 18 11 | 19 9 | 9 10
</code></pre>
<h1>Conclusions</h1>
<p>First, it's important to note that I'm operating under the assumption that you have scripts located in the <code><head></code> of your document (as opposed to the end of the <code><body></code>). There are various arguments regarding why you might link to your scripts in the <code><head></code> versus the end of the document, but that's outside the scope of this answer. This is strictly about whether <code><script></code>s should go before <code><link></code>s in the <code><head></code>.</p>
<p><strong>In modern DESKTOP browsers,</strong> it looks like linking to CSS first <strong>never</strong> provides a performance gain. Putting CSS after script gets you a trivial amount of gain when both CSS and script are delayed, but gives you large gains when CSS is delayed. (Shown by the <code>last</code> columns in the first set of results.)</p>
<p>Given that linking to CSS last does not seem to hurt performance but <em>can</em> provide gains under certain circumstances, <strong>you should link to external style sheets <em>after</em> you link to external scripts <em>only on desktop browsers</em></strong> if the performance of old browsers is not a concern. <strong>Read on for the mobile situation.</strong></p>
<h1>Why?</h1>
<p>Historically, when a browser encountered a <code><script></code> tag pointing to an external resource, the browser would <strong>stop</strong> parsing the HTML, retrieve the script, execute it, then continue parsing the HTML. In contrast, if the browser encountered a <code><link></code> for an external style sheet, it would <em>continue</em> parsing the HTML while it fetched the CSS file (in parallel).</p>
<p>Hence, the widely-repeated advice to put style sheets first – they would download first, and the first script to download could be loaded in parallel.</p>
<p>However, modern browsers (including all of the browsers I tested with above) have implemented <a href="https://www.google.com/search?q=speculative+parsing" rel="nofollow noreferrer"><em>speculative parsing</em></a>, where the browser "looks ahead" in the HTML and begins downloading resources <em>before</em> scripts download and execute.</p>
<p>In old browsers without speculative parsing, putting scripts first will affect performance since they will not download in parallel.</p>
<h2>Browser Support</h2>
<p>Speculative parsing was first implemented in: (along with the percentage of worldwide desktop browser users using this version or greater as of Jan 2012)</p>
<ul>
<li>Chrome 1 (<a href="https://en.wikipedia.org/wiki/WebKit" rel="nofollow noreferrer">WebKit</a> 525) (100%)</li>
<li><a href="https://en.wikipedia.org/wiki/Internet_Explorer_8" rel="nofollow noreferrer">Internet Explorer 8</a> (75%)</li>
<li>Firefox 3.5 (96%)</li>
<li><a href="https://en.wikipedia.org/wiki/Safari_%28web_browser%29" rel="nofollow noreferrer">Safari</a> 4 (99%)</li>
<li><a href="https://en.wikipedia.org/wiki/Opera_%28web_browser%29" rel="nofollow noreferrer">Opera</a> 11.60 (85%)</li>
</ul>
<p>In total, roughly 85% of desktop browsers in use today support speculative loading. Putting scripts before CSS will have a performance penalty on 15% of users <em>globally</em>; your mileage may vary based on your site's specific audience. (And remember that number is shrinking.)</p>
<p>On mobile browsers, it's a little harder to get definitive numbers simply due to how heterogeneous the mobile browser and OS landscape is. Since speculative rendering was implemented in WebKit 525 (released Mar 2008), and just about every worthwhile mobile browser is based on WebKit, we can conclude that "most" mobile browsers <em>should</em> support it. According to <a href="http://www.quirksmode.org/webkit.html" rel="nofollow noreferrer">quirksmode</a>, iOS 2.2/Android 1.0 use WebKit 525. I have no idea what Windows Phone looks like.</p>
<p><strong>However,</strong> I ran the test on my Android 4 device, and while I saw numbers similar to the desktop results, I hooked it up to the fantastic new <a href="http://code.google.com/chrome/mobile/docs/debugging.html" rel="nofollow noreferrer">remote debugger</a> in Chrome for Android, and <em>Network</em> tab showed that the browser was actually waiting to download the CSS until the JavaScript code completely loaded – in other words, <strong>even the newest version of WebKit for Android does not appear to support speculative parsing.</strong> I suspect it might be turned off due to the CPU, memory, and/or network constraints inherent to mobile devices.</p>
<h1>Code</h1>
<p>Forgive the sloppiness – this was Q&D.</p>
<h3>File <em>app.js</em></h3>
<pre><code>var express = require('express')
, app = express.createServer()
, fs = require('fs');
app.listen(90);
var file={};
fs.readdirSync('.').forEach(function(f) {
console.log(f)
file[f] = fs.readFileSync(f);
if (f != 'jquery.js' && f != 'style.css') app.get('/' + f, function(req,res) {
res.contentType(f);
res.send(file[f]);
});
});
app.get('/jquery.js', function(req,res) {
setTimeout(function() {
res.contentType('text/javascript');
res.send(file['jquery.js']);
}, 500);
});
app.get('/style.css', function(req,res) {
setTimeout(function() {
res.contentType('text/css');
res.send(file['style.css']);
}, 500);
});
var headresults={
css: [],
js: []
}, bodyresults={
css: [],
js: []
}
app.post('/result/:type/:time/:exec', function(req,res) {
headresults[req.params.type].push(parseInt(req.params.time, 10));
bodyresults[req.params.type].push(parseInt(req.params.exec, 10));
res.end();
});
app.get('/result/:type', function(req,res) {
var o = '';
headresults[req.params.type].forEach(function(i) {
o+='\n' + i;
});
o+='\n';
bodyresults[req.params.type].forEach(function(i) {
o+='\n' + i;
});
res.send(o);
});
</code></pre>
<h3>File <em>css.html</em></h3>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>CSS first</title>
<script>var start = Date.now();</script>
<link rel="stylesheet" href="style.css">
<script src="jquery.js"></script>
<script src="test.js"></script>
</head>
<body>
<script>document.write(jsload - start);bodyexec=Date.now()</script>
</body>
</html>
</code></pre>
<h3>File <em>js.html</em></h3>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>CSS first</title>
<script>var start = Date.now();</script>
<script src="jquery.js"></script>
<script src="test.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script>document.write(jsload - start);bodyexec=Date.now()</script>
</body>
</html>
</code></pre>
<h3>File <em>test.js</em></h3>
<pre><code>var jsload = Date.now();
$(function() {
$.post('/result' + location.pathname.replace('.html','') + '/' + (jsload - start) + '/' + (bodyexec - start));
});
</code></pre>
<p><a href="https://en.wikipedia.org/wiki/JQuery" rel="nofollow noreferrer">jQuery</a> was <a href="http://code.jquery.com/jquery-1.7.1.min.js" rel="nofollow noreferrer">jquery-1.7.1.min.js</a></p> | {
"question_id": 9271276,
"question_date": "2012-02-14T03:24:54.340Z",
"question_score": 962,
"tags": "javascript|css|performance",
"answer_id": 9272730,
"answer_date": "2012-02-14T06:37:04.170Z",
"answer_score": 746
} |
Please answer the following Stack Overflow question:
Title: git recover deleted file where no commit was made after the delete
<p>I deleted some files. </p>
<p>I did NOT commit yet. </p>
<p>I want to reset my workspace to recover the files. </p>
<p>I did a <code>git checkout .</code>.</p>
<p>But the deleted files are still missing.</p>
<p>And <code>git status</code> shows:</p>
<pre><code># On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# deleted: cc.properties
# deleted: store/README
# deleted: store/cc.properties
#
</code></pre>
<p>Why doesn't <code>git checkout .</code> reset the workspace to <code>HEAD</code>?</p> | <p>The output tells you what you need to do. <code>git reset HEAD cc.properties</code> etc. </p>
<p>This will unstage the rm operation. After that, running a <code>git status</code> again will tell you that you need to do a <code>git checkout -- cc.properties</code> to get the file back. </p>
<p>Update:
I have this in my config file</p>
<pre><code>$ git config alias.unstage
reset HEAD
</code></pre>
<p>which I usually use to unstage stuff.</p> | {
"question_id": 11956710,
"question_date": "2012-08-14T16:27:38.177Z",
"question_score": 961,
"tags": "git",
"answer_id": 11956744,
"answer_date": "2012-08-14T16:29:32.557Z",
"answer_score": 872
} |
Please answer the following Stack Overflow question:
Title: What is the difference between a symbolic link and a hard link?
<p>Recently I was asked this during a job interview. I was honest and said I knew how a symbolic link behaves and how to create one, but do not understand the use of a hard link and how it differs from a symbolic one.</p> | <p>Underneath the file system, files are represented by inodes. (Or is it multiple inodes? Not sure.)<br></p>
<p>A file in the file system is basically a link to an inode.<br>
A hard link, then, just creates another file with a link to the same underlying inode.</p>
<p>When you delete a file, it removes one link to the underlying inode. The inode is only deleted (or deletable/over-writable) when all links to the inode have been deleted.</p>
<p>A symbolic link is a link to another name in the file system.</p>
<p>Once a hard link has been made the link is to the inode. Deleting, renaming, or moving the original file will not affect the hard link as it links to the underlying inode. Any changes to the data on the inode is reflected in all files that refer to that inode.</p>
<p>Note: Hard links are only valid within the same File System. Symbolic links can span file systems as they are simply the name of another file.</p> | {
"question_id": 185899,
"question_date": "2008-10-09T04:05:41.840Z",
"question_score": 961,
"tags": "unix|symlink|hardlink",
"answer_id": 185903,
"answer_date": "2008-10-09T04:07:48.293Z",
"answer_score": 962
} |
Please answer the following Stack Overflow question:
Title: When and how should I use a ThreadLocal variable?
<p>When should I use a <a href="https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html" rel="noreferrer"><code>ThreadLocal</code></a> variable?</p>
<p>How is it used?</p> | <p>One possible (and common) use is when you have some object that is not thread-safe, but you want to avoid <a href="https://docs.oracle.com/javase/tutorial/essential/concurrency/sync.html" rel="noreferrer">synchronizing</a> access to that object (I'm looking at you, <a href="https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html" rel="noreferrer">SimpleDateFormat</a>). Instead, give each thread its own instance of the object.</p>
<p>For example:</p>
<pre><code>public class Foo
{
// SimpleDateFormat is not thread-safe, so give one to each thread
private static final ThreadLocal<SimpleDateFormat> formatter = new ThreadLocal<SimpleDateFormat>(){
@Override
protected SimpleDateFormat initialValue()
{
return new SimpleDateFormat("yyyyMMdd HHmm");
}
};
public String formatIt(Date date)
{
return formatter.get().format(date);
}
}
</code></pre>
<p><a href="https://docs.oracle.com/javase/8/docs/api/java/lang/ThreadLocal.html" rel="noreferrer">Documentation</a>.</p> | {
"question_id": 817856,
"question_date": "2009-05-03T19:59:20.760Z",
"question_score": 961,
"tags": "java|multithreading|concurrency|thread-local|thread-confinement",
"answer_id": 817926,
"answer_date": "2009-05-03T20:26:17.993Z",
"answer_score": 904
} |
Please answer the following Stack Overflow question:
Title: Big O, how do you calculate/approximate it?
<p>Most people with a degree in CS will certainly know what <a href="http://www.nist.gov/dads/HTML/bigOnotation.html" rel="noreferrer">Big O stands for</a>.
It helps us to measure how well an algorithm scales. </p>
<p>But I'm curious, how do <em>you</em> calculate or approximate the complexity of your algorithms?</p> | <p>I'll do my best to explain it here on simple terms, but be warned that this topic takes my students a couple of months to finally grasp. You can find more information on the Chapter 2 of the <a href="https://rads.stackoverflow.com/amzn/click/com/0321370139" rel="noreferrer" rel="nofollow noreferrer">Data Structures and Algorithms in Java</a> book.</p>
<hr>
<p>There is no <a href="http://en.wikipedia.org/wiki/Halting_problem" rel="noreferrer">mechanical procedure</a> that can be used to get the BigOh.</p>
<p>As a "cookbook", to obtain the <a href="http://en.wikipedia.org/wiki/Big_Oh_notation" rel="noreferrer">BigOh</a> from a piece of code you first need to realize that you are creating a math formula to count how many steps of computations get executed given an input of some size.</p>
<p>The purpose is simple: to compare algorithms from a theoretical point of view, without the need to execute the code. The lesser the number of steps, the faster the algorithm.</p>
<p>For example, let's say you have this piece of code:</p>
<pre><code>int sum(int* data, int N) {
int result = 0; // 1
for (int i = 0; i < N; i++) { // 2
result += data[i]; // 3
}
return result; // 4
}
</code></pre>
<p>This function returns the sum of all the elements of the array, and we want to create a formula to count the <a href="http://en.wikipedia.org/wiki/Computational_complexity_theory" rel="noreferrer">computational complexity</a> of that function:</p>
<pre><code>Number_Of_Steps = f(N)
</code></pre>
<p>So we have <code>f(N)</code>, a function to count the number of computational steps. The input of the function is the size of the structure to process. It means that this function is called such as:</p>
<pre><code>Number_Of_Steps = f(data.length)
</code></pre>
<p>The parameter <code>N</code> takes the <code>data.length</code> value. Now we need the actual definition of the function <code>f()</code>. This is done from the source code, in which each interesting line is numbered from 1 to 4.</p>
<p>There are many ways to calculate the BigOh. From this point forward we are going to assume that every sentence that doesn't depend on the size of the input data takes a constant <code>C</code> number computational steps.</p>
<p>We are going to add the individual number of steps of the function, and neither the local variable declaration nor the return statement depends on the size of the <code>data</code> array.</p>
<p>That means that lines 1 and 4 takes C amount of steps each, and the function is somewhat like this:</p>
<pre><code>f(N) = C + ??? + C
</code></pre>
<p>The next part is to define the value of the <code>for</code> statement. Remember that we are counting the number of computational steps, meaning that the body of the <code>for</code> statement gets executed <code>N</code> times. That's the same as adding <code>C</code>, <code>N</code> times:</p>
<pre><code>f(N) = C + (C + C + ... + C) + C = C + N * C + C
</code></pre>
<p>There is no mechanical rule to count how many times the body of the <code>for</code> gets executed, you need to count it by looking at what does the code do. To simplify the calculations, we are ignoring the variable initialization, condition and increment parts of the <code>for</code> statement.</p>
<p>To get the actual BigOh we need the <a href="http://en.wikipedia.org/wiki/Asymptotic_analysis" rel="noreferrer">Asymptotic analysis</a> of the function. This is roughly done like this:</p>
<ol>
<li>Take away all the constants <code>C</code>.</li>
<li>From <code>f()</code> get the <a href="http://en.wikipedia.org/wiki/Polynomial" rel="noreferrer">polynomium</a> in its <code>standard form</code>.</li>
<li>Divide the terms of the polynomium and sort them by the rate of growth.</li>
<li>Keep the one that grows bigger when <code>N</code> approaches <code>infinity</code>.</li>
</ol>
<p>Our <code>f()</code> has two terms:</p>
<pre><code>f(N) = 2 * C * N ^ 0 + 1 * C * N ^ 1
</code></pre>
<p>Taking away all the <code>C</code> constants and redundant parts:</p>
<pre><code>f(N) = 1 + N ^ 1
</code></pre>
<p>Since the last term is the one which grows bigger when <code>f()</code> approaches infinity (think on <a href="http://en.wikipedia.org/wiki/Limit_%28mathematics%29" rel="noreferrer">limits</a>) this is the BigOh argument, and the <code>sum()</code> function has a BigOh of:</p>
<pre><code>O(N)
</code></pre>
<hr>
<p>There are a few tricks to solve some tricky ones: use <a href="http://en.wikipedia.org/wiki/Summation" rel="noreferrer">summations</a> whenever you can.</p>
<p>As an example, this code can be easily solved using summations:</p>
<pre><code>for (i = 0; i < 2*n; i += 2) { // 1
for (j=n; j > i; j--) { // 2
foo(); // 3
}
}
</code></pre>
<p>The first thing you needed to be asked is the order of execution of <code>foo()</code>. While the usual is to be <code>O(1)</code>, you need to ask your professors about it. <code>O(1)</code> means (almost, mostly) constant <code>C</code>, independent of the size <code>N</code>.</p>
<p>The <code>for</code> statement on the sentence number one is tricky. While the index ends at <code>2 * N</code>, the increment is done by two. That means that the first <code>for</code> gets executed only <code>N</code> steps, and we need to divide the count by two.</p>
<pre><code>f(N) = Summation(i from 1 to 2 * N / 2)( ... ) =
= Summation(i from 1 to N)( ... )
</code></pre>
<p>The sentence number <em>two</em> is even trickier since it depends on the value of <code>i</code>. Take a look: the index i takes the values: 0, 2, 4, 6, 8, ..., 2 * N, and the second <code>for</code> get executed: N times the first one, N - 2 the second, N - 4 the third... up to the N / 2 stage, on which the second <code>for</code> never gets executed.</p>
<p>On formula, that means:</p>
<pre><code>f(N) = Summation(i from 1 to N)( Summation(j = ???)( ) )
</code></pre>
<p>Again, we are counting <strong>the number of steps</strong>. And by definition, every summation should always start at one, and end at a number bigger-or-equal than one.</p>
<pre><code>f(N) = Summation(i from 1 to N)( Summation(j = 1 to (N - (i - 1) * 2)( C ) )
</code></pre>
<p>(We are assuming that <code>foo()</code> is <code>O(1)</code> and takes <code>C</code> steps.)</p>
<p>We have a problem here: when <code>i</code> takes the value <code>N / 2 + 1</code> upwards, the inner Summation ends at a negative number! That's impossible and wrong. We need to split the summation in two, being the pivotal point the moment <code>i</code> takes <code>N / 2 + 1</code>.</p>
<pre><code>f(N) = Summation(i from 1 to N / 2)( Summation(j = 1 to (N - (i - 1) * 2)) * ( C ) ) + Summation(i from 1 to N / 2) * ( C )
</code></pre>
<p>Since the pivotal moment <code>i > N / 2</code>, the inner <code>for</code> won't get executed, and we are assuming a constant C execution complexity on its body.</p>
<p>Now the summations can be simplified using some identity rules:</p>
<ol>
<li>Summation(w from 1 to N)( C ) = N * C</li>
<li>Summation(w from 1 to N)( A (+/-) B ) = Summation(w from 1 to N)( A ) (+/-) Summation(w from 1 to N)( B )</li>
<li>Summation(w from 1 to N)( w * C ) = C * Summation(w from 1 to N)( w ) (C is a constant, independent of <code>w</code>)</li>
<li>Summation(w from 1 to N)( w ) = (N * (N + 1)) / 2</li>
</ol>
<p>Applying some algebra:</p>
<pre><code>f(N) = Summation(i from 1 to N / 2)( (N - (i - 1) * 2) * ( C ) ) + (N / 2)( C )
f(N) = C * Summation(i from 1 to N / 2)( (N - (i - 1) * 2)) + (N / 2)( C )
f(N) = C * (Summation(i from 1 to N / 2)( N ) - Summation(i from 1 to N / 2)( (i - 1) * 2)) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2)( i - 1 )) + (N / 2)( C )
=> Summation(i from 1 to N / 2)( i - 1 ) = Summation(i from 1 to N / 2 - 1)( i )
f(N) = C * (( N ^ 2 / 2 ) - 2 * Summation(i from 1 to N / 2 - 1)( i )) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N / 2 - 1) * (N / 2 - 1 + 1) / 2) ) + (N / 2)( C )
=> (N / 2 - 1) * (N / 2 - 1 + 1) / 2 =
(N / 2 - 1) * (N / 2) / 2 =
((N ^ 2 / 4) - (N / 2)) / 2 =
(N ^ 2 / 8) - (N / 4)
f(N) = C * (( N ^ 2 / 2 ) - 2 * ( (N ^ 2 / 8) - (N / 4) )) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - ( (N ^ 2 / 4) - (N / 2) )) + (N / 2)( C )
f(N) = C * (( N ^ 2 / 2 ) - (N ^ 2 / 4) + (N / 2)) + (N / 2)( C )
f(N) = C * ( N ^ 2 / 4 ) + C * (N / 2) + C * (N / 2)
f(N) = C * ( N ^ 2 / 4 ) + 2 * C * (N / 2)
f(N) = C * ( N ^ 2 / 4 ) + C * N
f(N) = C * 1/4 * N ^ 2 + C * N
</code></pre>
<p>And the BigOh is:</p>
<pre><code>O(N²)
</code></pre> | {
"question_id": 3255,
"question_date": "2008-08-06T10:18:16.067Z",
"question_score": 960,
"tags": "algorithm|optimization|complexity-theory|big-o|performance",
"answer_id": 4852666,
"answer_date": "2011-01-31T15:33:54.120Z",
"answer_score": 1535
} |
Please answer the following Stack Overflow question:
Title: Proper use of 'yield return'
<p>The <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/yield" rel="noreferrer">yield</a> keyword is one of those <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/" rel="noreferrer">keywords</a> in C# that continues to mystify me, and I've never been confident that I'm using it correctly.</p>
<p>Of the following two pieces of code, which is the preferred and why?</p>
<p><strong>Version 1:</strong> Using yield return</p>
<pre><code>public static IEnumerable<Product> GetAllProducts()
{
using (AdventureWorksEntities db = new AdventureWorksEntities())
{
var products = from product in db.Product
select product;
foreach (Product product in products)
{
yield return product;
}
}
}
</code></pre>
<p><strong>Version 2:</strong> Return the list</p>
<pre><code>public static IEnumerable<Product> GetAllProducts()
{
using (AdventureWorksEntities db = new AdventureWorksEntities())
{
var products = from product in db.Product
select product;
return products.ToList<Product>();
}
}
</code></pre> | <p>I tend to use yield-return when I calculate the next item in the list (or even the next group of items). </p>
<p>Using your Version 2, you must have the complete list before returning.
By using yield-return, you really only need to have the next item before returning.</p>
<p>Among other things, this helps spread the computational cost of complex calculations over a larger time-frame. For example, if the list is hooked up to a GUI and the user never goes to the last page, you never calculate the final items in the list. </p>
<p>Another case where yield-return is preferable is if the IEnumerable represents an infinite set. Consider the list of Prime Numbers, or an infinite list of random numbers. You can never return the full IEnumerable at once, so you use yield-return to return the list incrementally.</p>
<p>In your particular example, you have the full list of products, so I'd use Version 2.</p> | {
"question_id": 410026,
"question_date": "2009-01-03T22:43:35.353Z",
"question_score": 960,
"tags": "c#|yield-return",
"answer_id": 410058,
"answer_date": "2009-01-03T23:01:41.247Z",
"answer_score": 849
} |
Please answer the following Stack Overflow question:
Title: How can I get last characters of a string
<p>I have </p>
<pre><code>var id="ctl03_Tabs1";
</code></pre>
<p>Using JavaScript, how might I get the last five characters or last character?</p> | <p><strong>EDIT: As others have pointed out, use <code>slice(-5)</code> instead of <code>substr</code>.</strong> However, see the <code>.split().pop()</code> solution at the bottom of this answer for another approach.</p>
<p><em>Original answer:</em></p>
<p>You'll want to use the Javascript string method <code>.substr()</code> combined with the <code>.length</code> property.</p>
<pre><code>var id = "ctl03_Tabs1";
var lastFive = id.substr(id.length - 5); // => "Tabs1"
var lastChar = id.substr(id.length - 1); // => "1"
</code></pre>
<p>This gets the characters starting at id.length - 5 and, since the second argument for .substr() is omitted, continues to the end of the string.</p>
<p>You can also use the <code>.slice()</code> method as others have pointed out below.</p>
<p>If you're simply looking to find the characters after the underscore, you could use this:</p>
<pre><code>var tabId = id.split("_").pop(); // => "Tabs1"
</code></pre>
<p>This splits the string into an array on the underscore and then "pops" the last element off the array (which is the string you want).</p> | {
"question_id": 5873810,
"question_date": "2011-05-03T18:12:18.463Z",
"question_score": 959,
"tags": "javascript",
"answer_id": 5873890,
"answer_date": "2011-05-03T18:19:26.253Z",
"answer_score": 1334
} |
Please answer the following Stack Overflow question:
Title: How do I remove duplicates from a list, while preserving order?
<p>How do I remove duplicates from a list, while preserving order? Using a set to remove duplicates destroys the original order.
Is there a built-in or a Pythonic idiom?</p>
<p>Related question: <a href="https://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so-t">In Python, what is the fastest algorithm for removing duplicates from a list so that all elements are unique <em>while preserving order</em>?</a></p> | <p>Here you have some alternatives: <a href="http://www.peterbe.com/plog/uniqifiers-benchmark" rel="noreferrer">http://www.peterbe.com/plog/uniqifiers-benchmark</a></p>
<p>Fastest one:</p>
<pre><code>def f7(seq):
seen = set()
seen_add = seen.add
return [x for x in seq if not (x in seen or seen_add(x))]
</code></pre>
<p>Why assign <code>seen.add</code> to <code>seen_add</code> instead of just calling <code>seen.add</code>? Python is a dynamic language, and resolving <code>seen.add</code> each iteration is more costly than resolving a local variable. <code>seen.add</code> could have changed between iterations, and the runtime isn't smart enough to rule that out. To play it safe, it has to check the object each time.</p>
<p>If you plan on using this function a lot on the same dataset, perhaps you would be better off with an ordered set: <a href="http://code.activestate.com/recipes/528878/" rel="noreferrer">http://code.activestate.com/recipes/528878/</a></p>
<p><em>O</em>(1) insertion, deletion and member-check per operation.</p>
<p>(Small additional note: <code>seen.add()</code> always returns <code>None</code>, so the <em><code>or</code></em> above is there only as a way to attempt a set update, and not as an integral part of the logical test.)</p> | {
"question_id": 480214,
"question_date": "2009-01-26T15:43:58.483Z",
"question_score": 959,
"tags": "python|list|duplicates|unique",
"answer_id": 480227,
"answer_date": "2009-01-26T15:47:01.490Z",
"answer_score": 874
} |
Please answer the following Stack Overflow question:
Title: What is the difference between ( for... in ) and ( for... of ) statements?
<p>I know what is a <code>for... in</code> loop (it iterates over the keys), but I have heard about <code>for... of</code> for the first time (it iterates over values).</p>
<p>I am confused about <code>for... of</code> loop.</p>
<pre class="lang-js prettyprint-override"><code>var arr = [3, 5, 7];
arr.foo = "hello";
for (var i in arr) {
console.log(i); // logs "0", "1", "2", "foo"
}
for (var i of arr) {
console.log(i); // logs "3", "5", "7"
// it doesn't log "3", "5", "7", "hello"
}
</code></pre>
<p>I understand that <code>for... of</code> iterates over property values. Then why doesn't it log <code>"3", "5", "7", "hello"</code> instead of <code>"3", "5", "7"</code>?</p>
<p>Unlike <code>for... in</code> loop, which iterates over each key (<code>"0", "1", "2", "foo"</code>) and also iterates over the <code>foo</code> key, the <code>for... of</code> <em>does not</em> iterate over the value of <code>foo</code> property, i.e., <code>"hello"</code>. Why it is like that?</p>
<p>Here I console <code>for... of</code> loop. It should log <code>"3", "5", "7","hello"</code> but it logs <code>"3", "5", "7"</code>. Why?</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement" rel="noreferrer">Example Link</a></p> | <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in" rel="noreferrer"><code>for in</code></a> loops over enumerable property names of an object.</p>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of" rel="noreferrer"><code>for of</code></a> (new in ES6) does use an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols" rel="noreferrer">object-specific <em>iterator</em></a> and loops over the values generated by that.</p>
<p>In your example, the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator" rel="noreferrer">array iterator</a> does yield all the values in the array (ignoring non-index properties).</p> | {
"question_id": 29285897,
"question_date": "2015-03-26T18:14:02.893Z",
"question_score": 959,
"tags": "javascript|arrays|for-loop|object",
"answer_id": 29286412,
"answer_date": "2015-03-26T18:41:12.060Z",
"answer_score": 659
} |
Please answer the following Stack Overflow question:
Title: Move branch pointer to different commit without checkout
<p>To move the branch pointer of a checked out branch, one can use the <code>git reset --hard</code> command. But how to move the branch pointer of a not-checked out branch to point at a different commit (keeping all other stuff like tracked remote branch)?</p> | <p>You can do it for arbitrary refs. This is how to move a branch pointer:</p>
<pre><code>git update-ref -m "reset: Reset <branch> to <new commit>" refs/heads/<branch> <commit>
</code></pre>
<p>where <code>-m</code> adds a message to the reflog for the branch.</p>
<p>The general form is</p>
<pre><code>git update-ref -m "reset: Reset <branch> to <new commit>" <ref> <commit>
</code></pre>
<p>You can pick nits about the reflog message if you like - I believe the <code>branch -f</code> one is different from the <code>reset --hard</code> one, and this isn't exactly either of them.</p> | {
"question_id": 5471174,
"question_date": "2011-03-29T10:37:03.653Z",
"question_score": 959,
"tags": "git|git-branch",
"answer_id": 8206536,
"answer_date": "2011-11-21T02:06:00.387Z",
"answer_score": 626
} |
Please answer the following Stack Overflow question:
Title: When is a CDATA section necessary within a script tag?
<p>Are <strong>CDATA</strong> tags ever necessary in script tags and if so when?</p>
<p>In other words, when and where is this:</p>
<pre><code><script type="text/javascript">
//<![CDATA[
...code...
//]]>
</script>
</code></pre>
<p>preferable to this:</p>
<pre><code><script type="text/javascript">
...code...
</script>
</code></pre> | <p>A CDATA section is required if you need your document to parse as XML (e.g. when an XHTML page is interpreted as XML) <em>and you want to be able to write literal <code>i<10</code> and <code>a && b</code> instead of <code>i&lt;10</code> and <code>a &amp;&amp; b</code></em>, as XHTML will parse the JavaScript code as parsed character data as opposed to character data by default. This is not an issue with scripts that are stored in external source files, but for any inline JavaScript in XHTML you will <em>probably</em> want to use a CDATA section.</p>
<p>Note that many XHTML pages were never intended to be parsed as XML in which case this will not be an issue.</p>
<p>For a good writeup on the subject, see <a href="https://web.archive.org/web/20140304083226/http://javascript.about.com/library/blxhtml.htm" rel="noreferrer">https://web.archive.org/web/20140304083226/http://javascript.about.com/library/blxhtml.htm</a></p> | {
"question_id": 66837,
"question_date": "2008-09-15T20:52:14.700Z",
"question_score": 959,
"tags": "javascript|html|xhtml|cdata",
"answer_id": 66865,
"answer_date": "2008-09-15T20:54:44.943Z",
"answer_score": 602
} |
Please answer the following Stack Overflow question:
Title: Failed to load the JNI shared Library (JDK)
<p>When I try opening <a href="http://www.eclipse.org/">Eclipse</a>, a pop-up dialog states:</p>
<blockquote>
<p>Failed to load the JNI shared library "C:/JDK/bin/client/jvm.dll"`.</p>
</blockquote>
<p>Following this, Eclipse force closes.</p>
<p>Here's a few points I'd like to make: </p>
<ul>
<li>I checked to see if anything exists at that path. It does exist. </li>
<li>My Eclipse and <a href="http://www.oracle.com/technetwork/java/javase/overview/index.html">Java SE Development Kit</a> are both 64-bit. I checked my system, and it can handle 64-bit. </li>
<li>I've searched for this problem on Google and on Stack Overflow, and the only answer I found was to download the 32-bit versions of JDK and Eclipse.</li>
</ul>
<p>Downloading the 32-bit versions is something I only want to do as a very last resort.<br>
What would be suggested to solve this issue?</p> | <p>You need a <code>64-bit</code> trio: </p>
<ul>
<li><code>64-bit</code> <strong>OS</strong></li>
<li><code>64-bit</code> <strong>Java</strong> </li>
<li><code>64-bit</code> <strong>Eclipse</strong></li>
</ul> | {
"question_id": 7352493,
"question_date": "2011-09-08T18:02:15.777Z",
"question_score": 958,
"tags": "java|windows|eclipse|java-native-interface",
"answer_id": 7385128,
"answer_date": "2011-09-12T08:29:31.490Z",
"answer_score": 863
} |
Please answer the following Stack Overflow question:
Title: BehaviorSubject vs Observable?
<p>I'm looking into Angular RxJs patterns and I don't understand the difference between a <code>BehaviorSubject</code> and an <code>Observable</code>.</p>
<p>From my understanding, a <code>BehaviorSubject</code> is a value that can change over time (can be subscribed to and subscribers can receive updated results). This seems to be the exact same purpose of an <code>Observable</code>. </p>
<p>When would you use an <code>Observable</code> vs a <code>BehaviorSubject</code>? Are there benefits to using a <code>BehaviorSubject</code> over an <code>Observable</code> or vice versa?</p> | <p><strong>BehaviorSubject</strong> is a type of subject, a subject is a special type of observable so you can subscribe to messages like any other observable. The unique features of BehaviorSubject are:</p>
<ul>
<li>It needs an initial value as it must always return a value on subscription even if it hasn't received a <code>next()</code></li>
<li>Upon subscription, it returns the last value of the subject. A regular observable only triggers when it receives an <code>onnext</code></li>
<li>at any point, you can retrieve the last value of the subject in a non-observable code using the <code>getValue()</code> method.</li>
</ul>
<p>Unique features of a subject compared to an observable are:</p>
<ul>
<li>It is an observer in addition to being an observable so you can also send values to a subject in addition to subscribing to it.</li>
</ul>
<p>In addition, you can get an observable from behavior subject using the <code>asObservable()</code> method on <code>BehaviorSubject</code>.</p>
<p><strong>Observable</strong> is a Generic, and <code>BehaviorSubject</code> is technically a sub-type of Observable because BehaviorSubject is an observable with specific qualities.</p>
<p>Example with <strong>BehaviorSubject</strong>:</p>
<pre class="lang-ts prettyprint-override"><code>// Behavior Subject
// a is an initial value. if there is a subscription
// after this, it would get "a" value immediately
let bSubject = new BehaviorSubject("a");
bSubject.next("b");
bSubject.subscribe(value => {
console.log("Subscription got", value); // Subscription got b,
// ^ This would not happen
// for a generic observable
// or generic subject by default
});
bSubject.next("c"); // Subscription got c
bSubject.next("d"); // Subscription got d
</code></pre>
<p>Example 2 with regular subject:</p>
<pre class="lang-ts prettyprint-override"><code>// Regular Subject
let subject = new Subject();
subject.next("b");
subject.subscribe(value => {
console.log("Subscription got", value); // Subscription won't get
// anything at this point
});
subject.next("c"); // Subscription got c
subject.next("d"); // Subscription got d
</code></pre>
<p>An observable can be created from both <code>Subject</code> and <code>BehaviorSubject</code> using <code>subject.asObservable()</code>.</p>
<p>The only difference being you can't send values to an observable using <code>next()</code> method.</p>
<p>In Angular services, I would use <code>BehaviorSubject</code> for a data service as an angular service often initializes before component and behavior subject ensures that the component consuming the service receives the last updated data even if there are no new updates since the component's subscription to this data.</p> | {
"question_id": 39494058,
"question_date": "2016-09-14T15:14:44.443Z",
"question_score": 958,
"tags": "javascript|angular|rxjs|behaviorsubject|rxjs-observables",
"answer_id": 40231605,
"answer_date": "2016-10-25T04:53:19.367Z",
"answer_score": 1329
} |
Please answer the following Stack Overflow question:
Title: How do I force my .NET application to run as administrator?
<p>Once my program is installed on a client machine, how do I force my program to run as an administrator on <strong>Windows 7?</strong></p> | <p>You'll want to modify the manifest that gets embedded in the program. This works on Visual Studio 2008 and higher: Project + Add New Item, select "Application Manifest File". Change the <code><requestedExecutionLevel></code> element to:</p>
<pre><code> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</code></pre>
<p>The user gets the <a href="http://en.wikipedia.org/wiki/User_Account_Control" rel="noreferrer">UAC</a> prompt when they start the program. Use wisely; their patience can wear out quickly.</p> | {
"question_id": 2818179,
"question_date": "2010-05-12T11:09:50.023Z",
"question_score": 958,
"tags": "c#|.net|windows-7|administrator|elevated-privileges",
"answer_id": 2818776,
"answer_date": "2010-05-12T12:35:40.357Z",
"answer_score": 1239
} |
Please answer the following Stack Overflow question:
Title: Angular/RxJS When should I unsubscribe from `Subscription`
<p>When should I store the <code>Subscription</code> instances and invoke <code>unsubscribe()</code> during the <code>ngOnDestroy</code> life cycle and when can I simply ignore them?</p>
<p>Saving all subscriptions introduces a lot of mess into component code.</p>
<p><a href="https://angular.io/docs/ts/latest/guide/server-communication.html" rel="noreferrer">HTTP Client Guide</a> ignore subscriptions like this:</p>
<pre class="lang-js prettyprint-override"><code>getHeroes() {
this.heroService.getHeroes()
.subscribe(
heroes => this.heroes = heroes,
error => this.errorMessage = <any>error);
}
</code></pre>
<p>In the same time <a href="https://angular.io/docs/ts/latest/guide/router.html" rel="noreferrer">Route & Navigation Guide</a> says that:</p>
<blockquote>
<p>Eventually, we'll navigate somewhere else. The router will remove this component from the DOM and destroy it. We need to clean up after ourselves before that happens. Specifically, we must unsubscribe before Angular destroys the component. Failure to do so could create a memory leak.</p>
<p>We unsubscribe from our <code>Observable</code> in the <code>ngOnDestroy</code> method.</p>
</blockquote>
<pre class="lang-js prettyprint-override"><code>private sub: any;
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
let id = +params['id']; // (+) converts string 'id' to a number
this.service.getHero(id).then(hero => this.hero = hero);
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
</code></pre> | <p><strong>TL;DR</strong></p>
<p>For this question there are two kinds of Observables - <strong>finite</strong> value and <strong>infinite</strong> value.</p>
<p><code>http</code> Observables produce <strong>finite</strong> (1) values and something like a DOM event listener Observable produces <strong>infinite</strong> values.</p>
<p>If you manually call <code>subscribe</code> (not using async pipe), then <code>unsubscribe</code> from <strong>infinite</strong> Observables.</p>
<p>Don't worry about <strong>finite</strong> ones, RxJs will take care of them.</p>
<hr />
<p>Sources:</p>
<ol>
<li><p>I tracked down an answer from Rob Wormald in Angular's Gitter <a href="https://gitter.im/angular/angular?at=5681e8fa3c68940269251fa5" rel="noreferrer">here</a>.</p>
<p>He states (I reorganized for clarity and emphasis is mine):</p>
<blockquote>
<p>if its <strong>a single-value-sequence</strong> (like an http request)
the <strong>manual cleanup is unnecessary</strong> (assuming you subscribe in the controller manually)</p>
<p>i should say "if its a <strong>sequence that completes</strong>" (of which single value sequences, a la http, are one)</p>
<p><strong>if its an infinite sequence</strong>, <strong>you should unsubscribe</strong> which the async pipe does for you</p>
</blockquote>
<p>Also he mentions in <a href="https://youtu.be/UHI0AzD_WfY?t=26m42s" rel="noreferrer">this YouTube video</a> on Observables that <em>"they clean up after themselves..."</em> in the context of Observables that <em>complete</em> (like Promises, which always complete because they are always producing one value and ending - we never worried about unsubscribing from Promises to make sure they clean up XHR event listeners, right?)</p>
</li>
<li><p>Also in the <a href="https://angular-training-guide.rangle.io/observables/disposing_subscriptions_and_releasing_resources" rel="noreferrer">Rangle guide to Angular 2</a> it reads</p>
<blockquote>
<p>In most cases we will not need to explicitly call the <code>unsubscribe</code> method unless we want to cancel early or our <code>Observable</code> has a longer lifespan than our subscription. The default behavior of <code>Observable</code> operators is to dispose of the subscription as soon as <code>.complete()</code> or <code>.error()</code> messages are published. Keep in mind that RxJS was designed to be used in a "fire and forget" fashion most of the time.</p>
</blockquote>
<p>When does the phrase <em>"our <code>Observable</code> has a longer lifespan than our subscription"</em> apply?</p>
<p>It applies when a subscription is created inside a component which is destroyed before (or not 'long' before) the Observable completes.</p>
<p>I read this as meaning if we subscribe to an <code>http</code> request or an Observable that emits 10 values and our component is destroyed before that <code>http</code> request returns or the 10 values have been emitted, we are still OK!</p>
<p>When the request does return or the 10th value is finally emitted the Observable will complete and all resources will be cleaned up.</p>
</li>
<li><p>If we look at <a href="https://angular-training-guide.rangle.io/routing/routeparams" rel="noreferrer">this example</a> from the same Rangle guide we can see that the subscription to <code>route.params</code> does require an <code>unsubscribe()</code> because we don't know when those <code>params</code> will stop changing (emitting new values).</p>
<p>The component could be destroyed by navigating away in which case the route params will likely still be changing (they could technically change until the app ends) and the resources allocated in subscription would still be allocated because there hasn't been a <em>completion</em>.</p>
</li>
<li><p>In <a href="https://youtu.be/WWR9nxVx1ec?t=20m32s" rel="noreferrer">this video</a> from NgEurope Rob Wormald also says you do not need to unsubscribe from Router Observables. He also mentions the <code>http</code> service and <code>ActivatedRoute.params</code> in <a href="https://youtu.be/VLGCCpOWFFw?t=33m37s" rel="noreferrer">this video</a> from November 2016.</p>
</li>
<li><p>The Angular tutorial, <a href="https://v2.angular.io/docs/ts/latest/tutorial/toh-pt5.html" rel="noreferrer">the Routing chapter</a> now states the following:</p>
<blockquote>
<p>The <code>Router</code> manages the observables it provides and localizes the subscriptions. The subscriptions are cleaned up when the component is destroyed, protecting against memory leaks, so we don't need to unsubscribe from the route <code>params</code> <code>Observable</code>.</p>
</blockquote>
<p>Here's a <a href="https://github.com/angular/angular.io/issues/3003#issuecomment-268429065" rel="noreferrer">discussion</a> on the GitHub Issues for the Angular docs regarding Router Observables where Ward Bell mentions that clarification for all of this is in the works.</p>
</li>
</ol>
<hr />
<p>I spoke with Ward Bell about this question at NGConf (I even showed him this answer which he said was correct) but he told me the docs team for Angular had a solution to this question that is unpublished (though they are working on getting it approved). He also told me I could update my SO answer with the forthcoming official recommendation.</p>
<p>The solution we should all use going forward is to add a <code>private ngUnsubscribe = new Subject<void>();</code> field to all components that have <code>.subscribe()</code> calls to Observables within their class code.</p>
<p>We then call <code>this.ngUnsubscribe.next(); this.ngUnsubscribe.complete();</code> in our <code>ngOnDestroy()</code> methods.</p>
<p>The secret sauce (as noted already by <a href="https://stackoverflow.com/a/42695571/939634">@metamaker</a>) is to call <code>takeUntil(this.ngUnsubscribe)</code> before each of our <code>.subscribe()</code> calls which will guarantee all subscriptions will be cleaned up when the component is destroyed.</p>
<p>Example:</p>
<pre class="lang-js prettyprint-override"><code>import { Component, OnDestroy, OnInit } from '@angular/core';
// RxJs 6.x+ import paths
import { filter, startWith, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { BookService } from '../books.service';
@Component({
selector: 'app-books',
templateUrl: './books.component.html'
})
export class BooksComponent implements OnDestroy, OnInit {
private ngUnsubscribe = new Subject<void>();
constructor(private booksService: BookService) { }
ngOnInit() {
this.booksService.getBooks()
.pipe(
startWith([]),
filter(books => books.length > 0),
takeUntil(this.ngUnsubscribe)
)
.subscribe(books => console.log(books));
this.booksService.getArchivedBooks()
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe(archivedBooks => console.log(archivedBooks));
}
ngOnDestroy() {
this.ngUnsubscribe.next();
this.ngUnsubscribe.complete();
}
}
</code></pre>
<p><strong>Note:</strong> It's important to add the <code>takeUntil</code> operator as the last one to prevent leaks with intermediate Observables in the operator chain.</p>
<hr />
<p>More recently, in an episode of <a href="https://devchat.tv/adv-in-angular/aia-199-rxjs-with-ben-lesh-tracy-lee-and-jay-phelps/" rel="noreferrer">Adventures in Angular</a> Ben Lesh and Ward Bell discuss the issues around how/when to unsubscribe in a component. The discussion starts at about 1:05:30.</p>
<p>Ward mentions <em>"right now there's an awful takeUntil dance that takes a lot of machinery"</em> and Shai Reznik mentions <em>"Angular handles some of the subscriptions like http and routing"</em>.</p>
<p>In response Ben mentions that there are discussions right now to allow Observables to hook into the Angular component lifecycle events and Ward suggests an Observable of lifecycle events that a component could subscribe to as a way of knowing when to complete Observables maintained as component internal state.</p>
<p>That said, we mostly need solutions now so here are some other resources.</p>
<ol>
<li><p>A recommendation for the <code>takeUntil()</code> pattern from RxJs core team member Nicholas Jamieson and a TSLint rule to help enforce it: <a href="https://ncjamieson.com/avoiding-takeuntil-leaks/" rel="noreferrer">https://ncjamieson.com/avoiding-takeuntil-leaks/</a></p>
</li>
<li><p>Lightweight npm package that exposes an Observable operator that takes a component instance (<code>this</code>) as a parameter and automatically unsubscribes during <code>ngOnDestroy</code>: <a href="https://github.com/NetanelBasal/ngx-take-until-destroy" rel="noreferrer">https://github.com/NetanelBasal/ngx-take-until-destroy</a></p>
</li>
<li><p>Another variation of the above with slightly better ergonomics if you are not doing AOT builds (but we should all be doing AOT now): <a href="https://github.com/smnbbrv/ngx-rx-collector" rel="noreferrer">https://github.com/smnbbrv/ngx-rx-collector</a></p>
</li>
<li><p>Custom directive <code>*ngSubscribe</code> that works like async pipe but creates an embedded view in your template so you can refer to the 'unwrapped' value throughout your template: <a href="https://netbasal.com/diy-subscription-handling-directive-in-angular-c8f6e762697f" rel="noreferrer">https://netbasal.com/diy-subscription-handling-directive-in-angular-c8f6e762697f</a></p>
</li>
</ol>
<p>I mention in a comment to Nicholas' blog that over-use of <code>takeUntil()</code> could be a sign that your component is trying to do too much and that separating your existing components into <strong>Feature</strong> and <strong>Presentational</strong> components should be considered. You can then <code>| async</code> the Observable from the Feature component into an <code>Input</code> of the Presentational component, which means no subscriptions are necessary anywhere. Read more about this approach <a href="https://blog.angular-university.io/angular-2-smart-components-vs-presentation-components-whats-the-difference-when-to-use-each-and-why/" rel="noreferrer">here</a>.</p> | {
"question_id": 38008334,
"question_date": "2016-06-24T07:52:45.577Z",
"question_score": 958,
"tags": "angular|rxjs|observable|subscription|angular-component-life-cycle",
"answer_id": 41177163,
"answer_date": "2016-12-16T04:11:32.177Z",
"answer_score": 1223
} |
Please answer the following Stack Overflow question:
Title: How does Trello access the user's clipboard?
<p>When you hover over a card in <a href="http://en.wikipedia.org/wiki/Trello">Trello</a> and press <kbd>Ctrl</kbd>+<kbd>C</kbd>, the URL of this card is copied to the clipboard. How do they do this?</p>
<p>As far as I can tell, there is no Flash movie involved. I've got <a href="http://en.wikipedia.org/wiki/Flashblock">Flashblock</a> installed, and the Firefox network tab shows no Flash movie loaded. (That's the usual method, for example, by ZeroClipboard.)</p>
<p>How do they achieve this magic?</p>
<p>(Right at this moment I think I had an epiphany: You cannot select text on the page, so I assume they have an invisible element, where they create a text selection via JavaScript code, and <kbd>Ctrl</kbd>+<kbd>C</kbd> triggers the browser's default behaviour, copying that invisible node's text value.)</p> | <p><strong>Disclosure:</strong> <a href="https://trello.com/daniel" rel="noreferrer">I wrote the code that Trello uses</a>; the code below is the actual source code Trello uses to accomplish the clipboard trick.</p>
<hr />
<p>We don't actually "access the user's clipboard", instead we help the user out a bit by selecting something useful when they press <kbd>Ctrl</kbd>+<kbd>C</kbd>.</p>
<p>Sounds like you've figured it out; we take advantage of the fact that when you want to hit <kbd>Ctrl</kbd>+<kbd>C</kbd>, you have to hit the <kbd>Ctrl</kbd> key first. When the <kbd>Ctrl</kbd> key is pressed, we pop in a textarea that contains the text we want to end up on the clipboard, and select all the text in it, so the selection is all set when the <kbd>C</kbd> key is hit. (Then we hide the textarea when the <kbd>Ctrl</kbd> key comes up.)</p>
<p>Specifically, Trello does this:</p>
<pre><code>TrelloClipboard = new class
constructor: ->
@value = ""
$(document).keydown (e) =>
# Only do this if there's something to be put on the clipboard, and it
# looks like they're starting a copy shortcut
if !@value || !(e.ctrlKey || e.metaKey)
return
if $(e.target).is("input:visible,textarea:visible")
return
# Abort if it looks like they've selected some text (maybe they're trying
# to copy out a bit of the description or something)
if window.getSelection?()?.toString()
return
if document.selection?.createRange().text
return
_.defer =>
$clipboardContainer = $("#clipboard-container")
$clipboardContainer.empty().show()
$("<textarea id='clipboard'></textarea>")
.val(@value)
.appendTo($clipboardContainer)
.focus()
.select()
$(document).keyup (e) ->
if $(e.target).is("#clipboard")
$("#clipboard-container").empty().hide()
set: (@value) ->
</code></pre>
<p>In the DOM we've got:</p>
<pre><code><div id="clipboard-container"><textarea id="clipboard"></textarea></div>
</code></pre>
<p>CSS for the clipboard stuff:</p>
<pre><code>#clipboard-container {
position: fixed;
left: 0px;
top: 0px;
width: 0px;
height: 0px;
z-index: 100;
display: none;
opacity: 0;
}
#clipboard {
width: 1px;
height: 1px;
padding: 0px;
}
</code></pre>
<p>... and the CSS makes it so you can't actually see the textarea when it pops in ... but it's "visible" enough to copy from.</p>
<p>When you hover over a card, it calls</p>
<pre><code>TrelloClipboard.set(cardUrl)
</code></pre>
<p>... so then the clipboard helper knows what to select when the <kbd>Ctrl</kbd> key is pressed.</p> | {
"question_id": 17527870,
"question_date": "2013-07-08T13:26:56.077Z",
"question_score": 958,
"tags": "javascript|coffeescript|clipboard|trello",
"answer_id": 17528590,
"answer_date": "2013-07-08T14:00:57.590Z",
"answer_score": 1562
} |
Please answer the following Stack Overflow question:
Title: Exploring Docker container's file system
<p>I've noticed with docker that I need to understand what's happening inside a container or what files exist in there. One example is downloading images from the docker index - you don't have a clue what the image contains so it's impossible to start the application.</p>
<p>What would be ideal is to be able to ssh into them or equivalent. Is there a tool to do this, or is my conceptualisation of docker wrong in thinking I should be able to do this.</p> | <p>Here are a couple different methods...</p>
<h3>A) Use docker exec <em>(easiest)</em></h3>
<p>Docker version 1.3 or newer supports the command <code>exec</code> that behave similar to <code>nsenter</code>. This command can run new process in already running container (container must have PID 1 process running already). You can run <code>/bin/bash</code> to explore container state:</p>
<pre><code>docker exec -t -i mycontainer /bin/bash
</code></pre>
<p>see <a href="https://docs.docker.com/engine/reference/commandline/exec/" rel="noreferrer">Docker command line documentation</a></p>
<h3>B) Use Snapshotting</h3>
<p>You can evaluate container filesystem this way:</p>
<pre><code># find ID of your running container:
docker ps
# create image (snapshot) from container filesystem
docker commit 12345678904b5 mysnapshot
# explore this filesystem using bash (for example)
docker run -t -i mysnapshot /bin/bash
</code></pre>
<p>This way, you can evaluate filesystem of the running container in the precise time moment. Container is still running, no future changes are included.</p>
<p>You can later delete snapshot using (filesystem of the running container is not affected!):</p>
<pre><code>docker rmi mysnapshot
</code></pre>
<h3>C) Use ssh</h3>
<p>If you need continuous access, you can install sshd to your container and run the sshd daemon:</p>
<pre><code> docker run -d -p 22 mysnapshot /usr/sbin/sshd -D
# you need to find out which port to connect:
docker ps
</code></pre>
<p>This way, you can run your app using ssh (connect and execute what you want).</p>
<h3>D) Use nsenter</h3>
<p>Use <code>nsenter</code>, see <a href="https://web.archive.org/web/20160305150559/http://blog.docker.com/2014/06/why-you-dont-need-to-run-sshd-in-docker/" rel="noreferrer">Why you don't need to run SSHd in your Docker containers</a></p>
<blockquote>
<p><em>The short version is: with nsenter, you can get a shell into an
existing container, even if that container doesn’t run SSH or any kind
of special-purpose daemon</em></p>
</blockquote> | {
"question_id": 20813486,
"question_date": "2013-12-28T10:29:02.460Z",
"question_score": 957,
"tags": "linux|docker|filesystems",
"answer_id": 20816397,
"answer_date": "2013-12-28T15:56:08.553Z",
"answer_score": 1009
} |
Please answer the following Stack Overflow question:
Title: Why is it bad style to `rescue Exception => e` in Ruby?
<p>Ryan Davis’s <a href="http://www.zenspider.com/ruby/quickref.html#general-tips" rel="noreferrer">Ruby QuickRef</a> says (without explanation):</p>
<blockquote>
<p>Don’t rescue Exception. EVER. or I will stab you.</p>
</blockquote>
<p>Why not? What’s the right thing to do?</p> | <p><strong>TL;DR</strong>: Use <code>StandardError</code> instead for general exception catching. When the original exception is re-raised (e.g. when rescuing to log the exception only), rescuing <code>Exception</code> is probably okay.</p>
<hr>
<p><code>Exception</code> is the root of <a href="http://rubylearning.com/images/exception.jpg" rel="noreferrer">Ruby's exception hierarchy</a>, so when you <code>rescue Exception</code> you rescue from <em>everything</em>, including subclasses such as <code>SyntaxError</code>, <code>LoadError</code>, and <code>Interrupt</code>.</p>
<p>Rescuing <code>Interrupt</code> prevents the user from using <kbd>CTRL</kbd><kbd>C</kbd> to exit the program.</p>
<p>Rescuing <code>SignalException</code> prevents the program from responding correctly to signals. It will be unkillable except by <code>kill -9</code>.</p>
<p>Rescuing <code>SyntaxError</code> means that <code>eval</code>s that fail will do so silently.</p>
<p>All of these can be shown by running this program, and trying to <kbd>CTRL</kbd><kbd>C</kbd> or <code>kill</code> it:</p>
<pre><code>loop do
begin
sleep 1
eval "djsakru3924r9eiuorwju3498 += 5u84fior8u8t4ruyf8ihiure"
rescue Exception
puts "I refuse to fail or be stopped!"
end
end
</code></pre>
<p>Rescuing from <code>Exception</code> isn't even the default. Doing</p>
<pre><code>begin
# iceberg!
rescue
# lifeboats
end
</code></pre>
<p>does not rescue from <code>Exception</code>, it rescues from <code>StandardError</code>. You should generally specify something more specific than the default <code>StandardError</code>, but rescuing from <code>Exception</code> <em>broadens</em> the scope rather than narrowing it, and can have catastrophic results and make bug-hunting extremely difficult.</p>
<hr>
<p>If you have a situation where you do want to rescue from <code>StandardError</code> and you need a variable with the exception, you can use this form:</p>
<pre><code>begin
# iceberg!
rescue => e
# lifeboats
end
</code></pre>
<p>which is equivalent to:</p>
<pre><code>begin
# iceberg!
rescue StandardError => e
# lifeboats
end
</code></pre>
<hr>
<p>One of the few common cases where it’s sane to rescue from <code>Exception</code> is for logging/reporting purposes, in which case you should immediately re-raise the exception:</p>
<pre><code>begin
# iceberg?
rescue Exception => e
# do some logging
raise # not enough lifeboats ;)
end
</code></pre> | {
"question_id": 10048173,
"question_date": "2012-04-06T19:17:47.960Z",
"question_score": 957,
"tags": "ruby|exception-handling",
"answer_id": 10048406,
"answer_date": "2012-04-06T19:38:01.770Z",
"answer_score": 1440
} |
Please answer the following Stack Overflow question:
Title: vertical-align with Bootstrap 3
<p>I'm using Twitter Bootstrap 3, and I have problems when I want to align vertically two <code>div</code>, for example — <a href="http://jsfiddle.net/corinem/CQstd/">JSFiddle link</a>:</p>
<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<div class="row">
<div class="col-xs-5">
<div style="height:5em;border:1px solid #000">Big</div>
</div>
<div class="col-xs-5">
<div style="height:3em;border:1px solid #F00">Small</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p>The grid system in Bootstrap uses <code>float: left</code>, not <code>display:inline-block</code>, so the property <code>vertical-align</code> doesn't work. I tried using <code>margin-top</code> to fix it, but I think this is not a good solution for the responsive design.</p> | <blockquote>
<p>This answer presents a hack, but I would highly recommend you to use flexbox (as stated in <a href="https://stackoverflow.com/a/25517025/1238019">@Haschem answer</a>), since it's now supported everywhere.</p>
</blockquote>
<blockquote>
<p><strong>Demos link:</strong> <br/>
- <a href="https://www.bootply.com/jTZdTJGVzq" rel="noreferrer">Bootstrap 3</a> <br/>
- <a href="http://www.bootply.com/IXiEbZlLvP" rel="noreferrer">Bootstrap 4 alpha 6</a> <br/></p>
</blockquote>
<p>You still can use a custom class when you need it:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>.vcenter {
display: inline-block;
vertical-align: middle;
float: none;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
<div class="col-xs-5 col-md-3 col-lg-1 vcenter">
<div style="height:10em;border:1px solid #000">Big</div>
</div><!--
--><div class="col-xs-5 col-md-7 col-lg-9 vcenter">
<div style="height:3em;border:1px solid #F00">Small</div>
</div>
</div></code></pre>
</div>
</div>
</p>
<p><strong><a href="http://www.bootply.com/dFP81frbHk" rel="noreferrer">Bootply</a></strong></p>
<p>Using <code>inline-block</code> adds extra space between blocks if you let a real space in your code (like <code>...</div> </div>...</code>). This extra space breaks our grid if column sizes add up to 12:</p>
<pre><code><div class="row">
<div class="col-xs-6 col-md-4 col-lg-2 vcenter">
<div style="height:10em;border:1px solid #000">Big</div>
</div>
<div class="col-xs-6 col-md-8 col-lg-10 vcenter">
<div style="height:3em;border:1px solid #F00">Small</div>
</div>
</div>
</code></pre>
<p>Here, we've got extra spaces between <code><div class="[...] col-lg-2"></code> and <code><div class="[...] col-lg-10"></code> (a carriage return and 2 tabs/8 spaces). And so...</p>
<p><img src="https://i.stack.imgur.com/2Yzby.png" alt="Enter image description here"></p>
<p>Let's kick this extra space!!</p>
<pre><code><div class="row">
<div class="col-xs-6 col-md-4 col-lg-2 vcenter">
<div style="height:10em;border:1px solid #000">Big</div>
</div><!--
--><div class="col-xs-6 col-md-8 col-lg-10 vcenter">
<div style="height:3em;border:1px solid #F00">Small</div>
</div>
</div>
</code></pre>
<p><img src="https://i.stack.imgur.com/XZTJj.png" alt="Enter image description here"></p>
<p>Notice the <em>seemingly</em> useless comments <code><!-- ... --></code>? They are <strong>important</strong> -- without them, the whitespace between the <code><div></code> elements will take up space in the layout, breaking the grid system.</p>
<p><em>Note: the Bootply has been updated</em></p> | {
"question_id": 20547819,
"question_date": "2013-12-12T15:43:23.717Z",
"question_score": 956,
"tags": "html|css|twitter-bootstrap|twitter-bootstrap-3",
"answer_id": 20548578,
"answer_date": "2013-12-12T16:17:03.590Z",
"answer_score": 963
} |
Please answer the following Stack Overflow question:
Title: How to get full path of a file?
<p>Is there an easy way I can print the full path of <code>file.txt</code> ?</p>
<pre><code>file.txt = /nfs/an/disks/jj/home/dir/file.txt
</code></pre>
<p>The <code><command></code> </p>
<pre><code>dir> <command> file.txt
</code></pre>
<p>should print</p>
<pre><code>/nfs/an/disks/jj/home/dir/file.txt
</code></pre> | <p>Use <a href="http://man7.org/linux/man-pages/man1/readlink.1.html" rel="noreferrer"><strong>readlink</strong></a>:</p>
<pre><code>readlink -f file.txt
</code></pre> | {
"question_id": 5265702,
"question_date": "2011-03-10T20:45:28.027Z",
"question_score": 956,
"tags": "linux|file|unix|path",
"answer_id": 5265775,
"answer_date": "2011-03-10T20:52:03.423Z",
"answer_score": 1551
} |
Please answer the following Stack Overflow question:
Title: .gitignore and "The following untracked working tree files would be overwritten by checkout"
<p>So I added a folder to my .gitignore file.</p>
<p>Once I do a <code>git status</code> it tells me</p>
<pre><code># On branch latest
nothing to commit (working directory clean)
</code></pre>
<p>However, when I try to change branches I get the following:</p>
<pre><code>My-MacBook-Pro:webapp marcamillion$ git checkout develop
error: The following untracked working tree files would be overwritten by checkout:
public/system/images/9/thumb/red-stripe.jpg
public/system/images/9/original/red-stripe.jpg
public/system/images/8/thumb/red-stripe-red.jpg
public/system/images/8/original/red-stripe-red.jpg
public/system/images/8/original/00-louis_c.k.-chewed_up-cover-2008.jpg
public/system/images/7/thumb/red-stripe-dark.jpg
public/system/images/7/original/red-stripe-dark.jpg
public/system/images/7/original/DSC07833.JPG
public/system/images/6/thumb/red-stripe-bw.jpg
public/system/images/6/original/website-logo.png
public/system/images/6/original/red-stripe-bw.jpg
public/system/images/5/thumb/Guy_Waving_Jamaican_Flag.jpg
public/system/images/5/original/logocompv-colored-squares-100px.png
public/system/images/5/original/Guy_Waving_Jamaican_Flag.jpg
public/system/images/4/thumb/DSC_0001.JPG
public/system/images/4/original/logo.png
public/system/images/4/original/DSC_0001.JPG
public/system/images/4/original/2-up.jpg
public/system/images/3/thumb/logo2.gif
public/system/images/3/original/logo2.gif
public/system/images/3/original/Guy_Waving_Jamaican_Flag.jpg
public/system/images/3/original/11002000962.jpg
public/system/images/2/thumb/Profile Pic.jpg
public/system/images/2/original/Profile Pic.jpg
public/system/images/2/original/02 Login Screen.jpg
public/system/images/1/original/Argentina-2010-World-Cup.jpg
Please move or remove them before you can switch branches.
Aborting
</code></pre>
<p>This is what my .gitignore file looks like:</p>
<pre><code>.bundle
.DS_Store
db/*.sqlite3
log/*.log
tmp/**/*
public/system/images/*
public/system/avatars/*
</code></pre>
<p>How do I get this working so I can switch branches without deleting those files?</p>
<p>If I make a change, will it affect those files? In other words, if I came back to this branch afterwards would everything be perfect as up to my latest commit?</p>
<p>I don't want to lose those files, I just don't want them tracked.</p> | <p>It seems like you want the files ignored but they have already been commited. .gitignore has no effect on files that are already in the repo so they need to be removed with <code>git rm --cached</code>. The <code>--cached</code> will prevent it from having any effect on your working copy and it will just mark as removed the next time you commit. After the files are removed from the repo then the .gitignore will prevent them from being added again.</p>
<p>But you have another problem with your .gitignore, you are excessively using wildcards and its causing it to match less than you expect it to. Instead lets change the .gitignore and try this.</p>
<pre><code>.bundle
.DS_Store
db/*.sqlite3
log/*.log
tmp/
public/system/images/
public/system/avatars/
</code></pre> | {
"question_id": 4858047,
"question_date": "2011-02-01T01:39:44.790Z",
"question_score": 956,
"tags": "git|git-merge|gitignore",
"answer_id": 4858141,
"answer_date": "2011-02-01T01:59:22.480Z",
"answer_score": 283
} |
Please answer the following Stack Overflow question:
Title: Update Git branches from master
<p>I'm new to Git, and now I'm in this situation:</p>
<ul>
<li>I have four branches (master, b1, b2, and b3).</li>
<li>After I worked on b1-b3, I realized I have something to change on branch master that should be in all other branches.</li>
<li>I changed what I needed in <code>master</code> and... here is my problem:</li>
</ul>
<p>How do I update all other branches with <code>master</code> branch code?</p> | <p>You have two options:</p>
<p>The first is a merge, but this creates an extra commit for the merge. </p>
<p>Checkout each branch:</p>
<pre><code>git checkout b1
</code></pre>
<p>Then merge:</p>
<pre><code>git merge origin/master
</code></pre>
<p>Then push:</p>
<pre><code>git push origin b1
</code></pre>
<p>Alternatively, you can do a rebase:</p>
<pre><code>git fetch
git rebase origin/master
</code></pre> | {
"question_id": 3876977,
"question_date": "2010-10-06T21:18:19.547Z",
"question_score": 956,
"tags": "git|git-branch",
"answer_id": 3877000,
"answer_date": "2010-10-06T21:21:02.023Z",
"answer_score": 904
} |
Please answer the following Stack Overflow question:
Title: Is an entity body allowed for an HTTP DELETE request?
<p>When issuing an HTTP DELETE request, the request URI should completely identify the resource to delete. However, is it allowable to add extra meta-data as part of the entity body of the request?</p> | <p><a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html" rel="noreferrer">The spec</a> does not explicitly forbid or discourage it, so I would tend to say it is allowed.</p>
<p>Microsoft sees it the same way (I can hear murmuring in the audience), they state in the MSDN article about the <a href="https://web.archive.org/web/20090213142728/http://msdn.microsoft.com:80/en-us/library/cc716657.aspx" rel="noreferrer">DELETE Method of ADO.NET Data Services Framework</a>:</p>
<blockquote>
<p>If a DELETE request includes an entity body, the body is ignored [...]</p>
</blockquote>
<p>Additionally here is what <a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html" rel="noreferrer">RFC2616</a> (HTTP 1.1) has to say in regard to requests:</p>
<ul>
<li>an <em>entity-body</em> is only present when a <em>message-body</em> is present (section 7.2)</li>
<li>the presence of a <em>message-body</em> is signaled by the inclusion of a <code>Content-Length</code> or <code>Transfer-Encoding</code> header (section 4.3)</li>
<li>a <em>message-body</em> must not be included when the specification of the request method does not allow sending an <em>entity-body</em> (section 4.3)</li>
<li>an <em>entity-body</em> is explicitly forbidden in TRACE requests only, all other request types are unrestricted (section 9, and 9.8 specifically)</li>
</ul>
<p>For responses, this has been defined:</p>
<ul>
<li>whether a <em>message-body</em> is included depends on both request method <em>and</em> response status (section 4.3)</li>
<li>a <em>message-body</em> is explicitly forbidden in responses to HEAD requests (section 9, and 9.4 specifically)</li>
<li>a <em>message-body</em> is explicitly forbidden in 1xx (informational), 204 (no content), and 304 (not modified) responses (section 4.3)</li>
<li>all other responses include a message-body, though it may be of zero length (section 4.3)</li>
</ul> | {
"question_id": 299628,
"question_date": "2008-11-18T18:14:26.727Z",
"question_score": 956,
"tags": "http|rest",
"answer_id": 299696,
"answer_date": "2008-11-18T18:36:11.877Z",
"answer_score": 757
} |
Please answer the following Stack Overflow question:
Title: Understanding unique keys for array children in React.js
<p>I'm building a React component that accepts a JSON data source and creates a sortable table.<br>
Each of the dynamic data rows has a unique key assigned to it but I'm still getting an error of: </p>
<blockquote>
<p>Each child in an array should have a unique "key" prop.<br>
Check the render method of TableComponent.</p>
</blockquote>
<p>My <code>TableComponent</code> render method returns:</p>
<pre><code><table>
<thead key="thead">
<TableHeader columns={columnNames}/>
</thead>
<tbody key="tbody">
{ rows }
</tbody>
</table>
</code></pre>
<p>The <code>TableHeader</code> component is a single row and also has a unique key assigned to it.</p>
<p>Each <code>row</code> in <code>rows</code> is built from a component with a unique key:</p>
<pre><code><TableRowItem key={item.id} data={item} columns={columnNames}/>
</code></pre>
<p>And the <code>TableRowItem</code> looks like this:</p>
<pre><code>var TableRowItem = React.createClass({
render: function() {
var td = function() {
return this.props.columns.map(function(c) {
return <td key={this.props.data[c]}>{this.props.data[c]}</td>;
}, this);
}.bind(this);
return (
<tr>{ td(this.props.item) }</tr>
)
}
});
</code></pre>
<p>What is causing the unique key prop error? </p> | <p>You should add a key to each child <strong>as well as each element inside children</strong>.</p>
<p>This way React can handle the minimal DOM change.</p>
<p>In your code, each <code><TableRowItem key={item.id} data={item} columns={columnNames}/></code> is trying to render some children inside them without a key.</p>
<p>Check <a href="http://jsfiddle.net/1khqfLgr/2/" rel="noreferrer">this example</a>.</p>
<p>Try removing the <code>key={i}</code> from the <code><b></b></code> element inside the div's (and check the console).</p>
<p>In the sample, if we don't give a key to the <code><b></code> element and we want to update <strong>only</strong> the <code>object.city</code>, React needs to re-render the whole row vs just the element.</p>
<p>Here is the code:</p>
<pre><code>var data = [{name:'Jhon', age:28, city:'HO'},
{name:'Onhj', age:82, city:'HN'},
{name:'Nohj', age:41, city:'IT'}
];
var Hello = React.createClass({
render: function() {
var _data = this.props.info;
console.log(_data);
return(
<div>
{_data.map(function(object, i){
return <div className={"row"} key={i}>
{[ object.name ,
// remove the key
<b className="fosfo" key={i}> {object.city} </b> ,
object.age
]}
</div>;
})}
</div>
);
}
});
React.render(<Hello info={data} />, document.body);
</code></pre>
<hr />
<h2><strong><a href="https://stackoverflow.com/a/43892905/2325522">The answer posted by @Chris at the bottom</a> goes into much more detail than this answer.</strong></h2>
<p>React documentation on the importance of keys in reconciliation: <a href="https://facebook.github.io/react/docs/reconciliation.html#keys" rel="noreferrer">Keys</a></p> | {
"question_id": 28329382,
"question_date": "2015-02-04T19:06:11.667Z",
"question_score": 955,
"tags": "javascript|reactjs",
"answer_id": 28329550,
"answer_date": "2015-02-04T19:16:47.797Z",
"answer_score": 866
} |
Please answer the following Stack Overflow question:
Title: How do I use a decimal step value for range()?
<p>How do I iterate between 0 and 1 by a step of 0.1?</p>
<p>This says that the step argument cannot be zero:</p>
<pre><code>for i in range(0, 1, 0.1):
print(i)
</code></pre> | <p>Rather than using a decimal step directly, it's much safer to express this in terms of how many points you want. Otherwise, floating-point rounding error is likely to give you a wrong result.</p>
<p>Use the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.linspace.html" rel="noreferrer"><code>linspace</code></a> function from the <a href="http://en.wikipedia.org/wiki/NumPy" rel="noreferrer">NumPy</a> library (which isn't part of the standard library but is relatively easy to obtain). <code>linspace</code> takes a number of points to return, and also lets you specify whether or not to include the right endpoint:</p>
<pre><code>>>> np.linspace(0,1,11)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ])
>>> np.linspace(0,1,10,endpoint=False)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
</code></pre>
<p>If you really want to use a floating-point step value, use <code>numpy.arange</code>:</p>
<pre><code>>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
</code></pre>
<p>Floating-point rounding error <em>will</em> cause problems, though. Here's a simple case where rounding error causes <code>arange</code> to produce a length-4 array when it should only produce 3 numbers:</p>
<pre><code>>>> numpy.arange(1, 1.3, 0.1)
array([1. , 1.1, 1.2, 1.3])
</code></pre> | {
"question_id": 477486,
"question_date": "2009-01-25T10:20:43.140Z",
"question_score": 955,
"tags": "python|floating-point|range",
"answer_id": 477635,
"answer_date": "2009-01-25T12:26:08.160Z",
"answer_score": 1157
} |
Please answer the following Stack Overflow question:
Title: How do I write a correct micro-benchmark in Java?
<p>How do you write (and run) a correct micro-benchmark in Java?</p>
<p>I'm looking for some code samples and comments illustrating various things to think about.</p>
<p>Example: Should the benchmark measure time/iteration or iterations/time, and why?</p>
<p>Related: <a href="https://stackoverflow.com/questions/410437/is-stopwatch-benchmarking-acceptable">Is stopwatch benchmarking acceptable?</a></p> | <p>Tips about writing micro benchmarks <a href="https://wiki.openjdk.java.net/display/HotSpot/Main" rel="noreferrer">from the creators of Java HotSpot</a>:</p>
<p><strong>Rule 0:</strong> Read a reputable paper on JVMs and micro-benchmarking. A good one is <a href="http://www.ibm.com/developerworks/java/library/j-jtp02225" rel="noreferrer">Brian Goetz, 2005</a>. Do not expect too much from micro-benchmarks; they measure only a limited range of JVM performance characteristics.</p>
<p><strong>Rule 1:</strong> Always include a warmup phase which runs your test kernel all the way through, enough to trigger all initializations and compilations before timing phase(s). (Fewer iterations is OK on the warmup phase. The rule of thumb is several tens of thousands of inner loop iterations.)</p>
<p><strong>Rule 2:</strong> Always run with <code>-XX:+PrintCompilation</code>, <code>-verbose:gc</code>, etc., so you can verify that the compiler and other parts of the JVM are not doing unexpected work during your timing phase.</p>
<p><strong>Rule 2.1:</strong> Print messages at the beginning and end of timing and warmup phases, so you can verify that there is no output from Rule 2 during the timing phase.</p>
<p><strong>Rule 3:</strong> Be aware of the difference between <code>-client</code> and <code>-server</code>, and OSR and regular compilations. The <code>-XX:+PrintCompilation</code> flag reports OSR compilations with an at-sign to denote the non-initial entry point, for example: <code>Trouble$1::run @ 2 (41 bytes)</code>. Prefer server to client, and regular to OSR, if you are after best performance.</p>
<p><strong>Rule 4:</strong> Be aware of initialization effects. Do not print for the first time during your timing phase, since printing loads and initializes classes. Do not load new classes outside of the warmup phase (or final reporting phase), unless you are testing class loading specifically (and in that case load only the test classes). Rule 2 is your first line of defense against such effects.</p>
<p><strong>Rule 5:</strong> Be aware of deoptimization and recompilation effects. Do not take any code path for the first time in the timing phase, because the compiler may junk and recompile the code, based on an earlier optimistic assumption that the path was not going to be used at all. Rule 2 is your first line of defense against such effects.</p>
<p><strong>Rule 6:</strong> Use appropriate tools to read the compiler's mind, and expect to be surprised by the code it produces. Inspect the code yourself before forming theories about what makes something faster or slower.</p>
<p><strong>Rule 7:</strong> Reduce noise in your measurements. Run your benchmark on a quiet machine, and run it several times, discarding outliers. Use <code>-Xbatch</code> to serialize the compiler with the application, and consider setting <code>-XX:CICompilerCount=1</code> to prevent the compiler from running in parallel with itself. Try your best to reduce GC overhead, set <code>Xmx</code>(large enough) equals <code>Xms</code> and use <a href="http://openjdk.java.net/jeps/318" rel="noreferrer"><code>UseEpsilonGC</code></a> if it is available.</p>
<p><strong>Rule 8:</strong> Use a library for your benchmark as it is probably more efficient and was already debugged for this sole purpose. Such as <a href="http://openjdk.java.net/projects/code-tools/jmh/" rel="noreferrer">JMH</a>, <a href="https://github.com/google/caliper" rel="noreferrer">Caliper</a> or <a href="http://cseweb.ucsd.edu/users/wgg/JavaProf/javaprof.html" rel="noreferrer">Bill and Paul's Excellent UCSD Benchmarks for Java</a>. </p> | {
"question_id": 504103,
"question_date": "2009-02-02T17:39:41.690Z",
"question_score": 955,
"tags": "java|jvm|benchmarking|jvm-hotspot|microbenchmark",
"answer_id": 513259,
"answer_date": "2009-02-04T20:49:28.043Z",
"answer_score": 850
} |
Please answer the following Stack Overflow question:
Title: "Cross origin requests are only supported for HTTP." error when loading a local file
<p>I'm trying to load a 3D model into Three.js with <code>JSONLoader</code>, and that 3D model is in the same directory as the entire website.</p>
<p>I'm getting the <code>"Cross origin requests are only supported for HTTP."</code> error, but I don't know what's causing it nor how to fix it.</p> | <p>My crystal ball says that you are loading the model using either <code>file://</code> or <code>C:/</code>, which stays true to the error message as they are not <code>http://</code></p>
<p>So you can either install a webserver in your local PC or upload the model somewhere else and use <code>jsonp</code> and change the url to <code>http://example.com/path/to/model</code></p>
<p>Origin is defined in <a href="https://www.rfc-editor.org/rfc/rfc6454" rel="noreferrer">RFC-6454</a> as</p>
<pre><code> ...they have the same
scheme, host, and port. (See Section 4 for full details.)
</code></pre>
<p>So even though your file originates from the same host (<code>localhost</code>), but as long as the scheme is different (<code>http</code> / <code>file</code>), they are treated as different origin.</p> | {
"question_id": 10752055,
"question_date": "2012-05-25T09:41:19.753Z",
"question_score": 954,
"tags": "javascript|file|http|three.js|cors",
"answer_id": 10752078,
"answer_date": "2012-05-25T09:42:55.293Z",
"answer_score": 895
} |
Please answer the following Stack Overflow question:
Title: Downloading an entire S3 bucket?
<p>I noticed that there does not seem to be an option to download an entire <code>s3</code> bucket from the AWS Management Console.</p>
<p>Is there an easy way to grab everything in one of my buckets? I was thinking about making the root folder public, using <code>wget</code> to grab it all, and then making it private again but I don't know if there's an easier way.</p> | <h2>AWS CLI</h2>
<p>See the "<a href="http://docs.aws.amazon.com/cli/latest/index.html" rel="noreferrer">AWS CLI Command Reference</a>" for more information.</p>
<p>AWS recently released their Command Line Tools, which work much like boto and can be installed using </p>
<pre><code>sudo easy_install awscli
</code></pre>
<p>or </p>
<pre><code>sudo pip install awscli
</code></pre>
<p>Once installed, you can then simply run:</p>
<pre><code>aws s3 sync s3://<source_bucket> <local_destination>
</code></pre>
<p>For example:</p>
<pre><code>aws s3 sync s3://mybucket .
</code></pre>
<p>will download all the objects in <code>mybucket</code> to the current directory.</p>
<p>And will output:</p>
<pre><code>download: s3://mybucket/test.txt to test.txt
download: s3://mybucket/test2.txt to test2.txt
</code></pre>
<p>This will download all of your files using a one-way sync. It will <em>not</em> delete any existing files in your current directory unless you specify <a href="http://docs.aws.amazon.com/cli/latest/reference/s3/sync.html" rel="noreferrer"> <code>--delete</code></a>, and it won't change or delete any files on S3.</p>
<p>You can also do S3 bucket to S3 bucket, or local to S3 bucket sync. </p>
<p>Check out the <a href="http://docs.aws.amazon.com/cli/latest/reference/s3/sync.html" rel="noreferrer">documentation and other examples</a>.</p>
<p>Whereas the above example is how to download a full bucket, you can also download a folder recursively by performing</p>
<pre><code>aws s3 cp s3://BUCKETNAME/PATH/TO/FOLDER LocalFolderName --recursive
</code></pre>
<p>This will instruct the CLI to download all files and folder keys recursively within the <code>PATH/TO/FOLDER</code> directory within the <code>BUCKETNAME</code> bucket. </p> | {
"question_id": 8659382,
"question_date": "2011-12-28T17:49:04.603Z",
"question_score": 954,
"tags": "amazon-web-services|amazon-s3|aws-cli",
"answer_id": 18762381,
"answer_date": "2013-09-12T10:57:41.257Z",
"answer_score": 1750
} |
Please answer the following Stack Overflow question:
Title: Function vs. Stored Procedure in SQL Server
<p>I've been learning Functions and Stored Procedure for quite a while but I don't know why and when I should use a function or a stored procedure. They look same to me, maybe because I am kinda newbie about that.</p>
<p>Can some one tell me why?</p> | <p>Functions are computed values and cannot perform permanent environmental changes to <code>SQL Server</code> (i.e., no <code>INSERT</code> or <code>UPDATE</code> statements allowed).</p>
<p>A function can be used inline in <code>SQL</code> statements if it returns a scalar value or can be joined upon if it returns a result set.</p>
<p><em>A point worth noting from comments, which summarize the answer. Thanks to @Sean K Anderson:</em></p>
<blockquote>
<p>Functions follow the computer-science definition in that they MUST return a value and cannot alter the data they receive as parameters
(the arguments). Functions are not allowed to change anything, must
have at least one parameter, and they must return a value. Stored
procs do not have to have a parameter, can change database objects,
and do not have to return a value.</p>
</blockquote> | {
"question_id": 1179758,
"question_date": "2009-07-24T19:40:06.827Z",
"question_score": 953,
"tags": "sql|sql-server|tsql|stored-procedures|sql-function",
"answer_id": 1179778,
"answer_date": "2009-07-24T19:42:14.013Z",
"answer_score": 802
} |
Please answer the following Stack Overflow question:
Title: What does %w(array) mean?
<p>I'm looking at the documentation for FileUtils. </p>
<p>I'm confused by the following line:</p>
<pre><code>FileUtils.cp %w(cgi.rb complex.rb date.rb), '/usr/lib/ruby/1.6'
</code></pre>
<p>What does the <code>%w</code> mean? Can you point me to the documentation? </p> | <p><code>%w(foo bar)</code> is a shortcut for <code>["foo", "bar"]</code>. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them. You can find a list of ways of writing literals in <a href="http://www.zenspider.com/ruby/quickref.html#types" rel="noreferrer">zenspider's quickref</a>.</p> | {
"question_id": 1274675,
"question_date": "2009-08-13T21:23:47.170Z",
"question_score": 952,
"tags": "ruby|arrays|string|notation",
"answer_id": 1274703,
"answer_date": "2009-08-13T21:28:14.213Z",
"answer_score": 1387
} |
Please answer the following Stack Overflow question:
Title: Git: How to solve Permission denied (publickey) error when using Git?
<p>I'm on Mac Snow Leopard and I just installed <code>git</code>.</p>
<p>I just tried </p>
<pre><code>git clone [email protected]:cakebook.git
</code></pre>
<p>but that gives me this error:</p>
<pre><code>Initialized empty Git repository in `/Users/username/Documents/cakebook/.git/`
Permission denied (publickey).
fatal: The remote end hung up unexpectedly
</code></pre>
<p>What am I missing?<br>
I've also tried doing <code>ssh-keygen</code> with no passphase but still same error.</p> | <p><strong>If the user has not generated a ssh public/private key pair set before</strong></p>
<p>This info is working on theChaw but can be applied to all other git repositories which support SSH pubkey authentications. (See [gitolite][1], gitlab or github for example.)</p>
<blockquote>
<p>First start by setting up your own public/private key pair set. This
can use either DSA or RSA, so basically any key you setup will work.
On most systems you can use ssh-keygen.</p>
</blockquote>
<blockquote>
<ul>
<li>First you'll want to cd into your .ssh directory. Open up the terminal and run:</li>
</ul>
<blockquote>
<p><code>cd ~/.ssh && ssh-keygen</code></p>
</blockquote>
<ul>
<li>Next you need to copy this to your clipboard.</li>
<li>On OS X run: <code>cat id_rsa.pub | pbcopy</code></li>
<li>On Linux run: <code>cat id_rsa.pub | xclip</code></li>
<li>On Windows (via Cygwin/Git Bash) run: <code>cat id_rsa.pub | clip</code></li>
<li>On Windows (Powershell) run: <code>Get-Content id_rsa.pub | Set-Clipboard</code> (Thx to @orion elenzil)</li>
<li>Add your key to your account via the website.</li>
<li>Finally setup your .gitconfig.</li>
<li><code>git config --global user.name "bob"</code></li>
<li><code>git config --global user.email bob@...</code>
(don't forget to restart your command line to make sure the config is reloaded)</li>
</ul>
<p>That's it you should be good to clone and checkout.</p>
</blockquote>
<p>Further information can be found at <a href="https://help.github.com/articles/generating-ssh-keys" rel="noreferrer">https://help.github.com/articles/generating-ssh-keys</a> (thanks to @Lee Whitney)
[1]: <a href="https://github.com/sitaramc/gitolite" rel="noreferrer">https://github.com/sitaramc/gitolite</a></p>
<p>-</p>
<p><strong>If the user has generated a ssh public/private key pair set before</strong></p>
<ul>
<li>check which key have been authorized on your github or gitlab account settings</li>
<li>determine which corresponding private key must be associated from your local computer</li>
</ul>
<p><code>eval $(ssh-agent -s)</code></p>
<ul>
<li>define where the keys are located</li>
</ul>
<p><code>ssh-add ~/.ssh/id_rsa</code></p> | {
"question_id": 2643502,
"question_date": "2010-04-15T07:46:34.483Z",
"question_score": 951,
"tags": "git|ssh|ssh-keys|public-key",
"answer_id": 2643584,
"answer_date": "2010-04-15T07:59:05.930Z",
"answer_score": 1117
} |
Please answer the following Stack Overflow question:
Title: Python integer incrementing with ++
<p>I've always laughed to myself when I've looked back at my VB6 days and thought, "What modern language doesn't allow incrementing with double plus signs?":</p>
<pre><code>number++
</code></pre>
<p>To my surprise, I can't find anything about this in the Python docs. Must I really subject myself to <code>number = number + 1</code>? Don't people use the <code>++</code> / <code>--</code> notation?</p> | <p>Python doesn't support <code>++</code>, but you can do:</p>
<pre><code>number += 1
</code></pre> | {
"question_id": 2632677,
"question_date": "2010-04-13T19:45:14.257Z",
"question_score": 951,
"tags": "python|syntax|increment",
"answer_id": 2632687,
"answer_date": "2010-04-13T19:46:57.307Z",
"answer_score": 1658
} |
Please answer the following Stack Overflow question:
Title: How to use glob() to find files recursively?
<p>This is what I have:</p>
<pre><code>glob(os.path.join('src','*.c'))
</code></pre>
<p>but I want to search the subfolders of src. Something like this would work:</p>
<pre><code>glob(os.path.join('src','*.c'))
glob(os.path.join('src','*','*.c'))
glob(os.path.join('src','*','*','*.c'))
glob(os.path.join('src','*','*','*','*.c'))
</code></pre>
<p>But this is obviously limited and clunky.</p> | <p><strong>pathlib.Path.rglob</strong></p>
<p>Use <a href="https://docs.python.org/3/library/pathlib.html#pathlib.Path.rglob" rel="noreferrer"><code>pathlib.Path.rglob</code></a> from the the <a href="https://docs.python.org/3/library/pathlib.html" rel="noreferrer"><code>pathlib</code></a> module, which was introduced in Python 3.5.</p>
<pre><code>from pathlib import Path
for path in Path('src').rglob('*.c'):
print(path.name)
</code></pre>
<p>If you don't want to use pathlib, use can use <a href="https://docs.python.org/3/library/glob.html#glob.glob" rel="noreferrer"><code>glob.glob('**/*.c')</code></a>, but don't forget to pass in the <code>recursive</code> keyword parameter and it will use inordinate amount of time on large directories.</p>
<p>For cases where matching files beginning with a dot (<code>.</code>); like files in the current directory or hidden files on Unix based system, use the <a href="https://docs.python.org/2/library/os.html#os.walk" rel="noreferrer"><code>os.walk</code></a> solution below.</p>
<p><strong>os.walk</strong></p>
<p>For older Python versions, use <a href="https://docs.python.org/2/library/os.html#os.walk" rel="noreferrer"><code>os.walk</code></a> to recursively walk a directory and <a href="https://docs.python.org/2/library/fnmatch.html#fnmatch.filter" rel="noreferrer"><code>fnmatch.filter</code></a> to match against a simple expression:</p>
<pre><code>import fnmatch
import os
matches = []
for root, dirnames, filenames in os.walk('src'):
for filename in fnmatch.filter(filenames, '*.c'):
matches.append(os.path.join(root, filename))
</code></pre> | {
"question_id": 2186525,
"question_date": "2010-02-02T18:19:50.217Z",
"question_score": 950,
"tags": "python|path|filesystems|glob|fnmatch",
"answer_id": 2186565,
"answer_date": "2010-02-02T18:26:54.480Z",
"answer_score": 1677
} |
Please answer the following Stack Overflow question:
Title: What file uses .md extension and how should I edit them?
<p>On GitHub, several projects have <code>README.md</code> files. It seems like a simple format file to express text and pictures. </p>
<p>I guess there is an editor or syntax explanation somewhere.</p>
<p>Where can I find an introduction to <code>.md</code> files?</p> | <p>Markdown is a plain-text file format. The extensions <code>.md</code> and <code>.markdown</code> are just text files written in <a href="https://en.wikipedia.org/wiki/Markdown" rel="noreferrer">Markdown</a> syntax. If you have a <code>Readme.md</code> in your repo, GitHub will show the contents on the home page of your repo. Read the documentation:</p>
<ul>
<li><a href="http://daringfireball.net/projects/markdown/" rel="noreferrer">Standard Markdown</a></li>
<li><a href="http://github.github.com/github-flavored-markdown/" rel="noreferrer">GitHub Flavored Markdown</a></li>
</ul>
<p>You can edit the <code>Readme.md</code> file in GitHub itself. Click on Readme.md, you will find an edit button. You can preview your changes and even commit them from there.</p>
<p>Since it is a text file, Notepad or Notepad++ (Windows), TextEdit (Mac) or any other text editor can be used to edit and modify it. Specialized editors exist that automatically parse the markdown as you type it and generate a preview, while others apply various syntax coloring and decorations to the displayed text. In both cases though, the saved file is still a readable text file.</p>
<p>If you want to create an <code>md</code> file with preview and if you prefer not to install any special editors, you can use online editors like <a href="https://dillinger.io" rel="noreferrer">dillinger.io</a> and <a href="https://stackedit.io" rel="noreferrer">stackedit.io</a>. They provide live preview. You can also export your files to <a href="https://drive.google.com" rel="noreferrer">Google Drive</a> or <a href="https://dropbox.com" rel="noreferrer">Dropbox</a>.</p> | {
"question_id": 5922882,
"question_date": "2011-05-07T17:42:24.437Z",
"question_score": 950,
"tags": "markdown|file-extension",
"answer_id": 5922899,
"answer_date": "2011-05-07T17:45:08.767Z",
"answer_score": 786
} |
Please answer the following Stack Overflow question:
Title: How do I generate a stream from a string?
<p>I need to write a unit test for a method that takes a stream which comes from a text file. I would like to do do something like this:</p>
<pre><code>Stream s = GenerateStreamFromString("a,b \n c,d");
</code></pre> | <pre><code>public static Stream GenerateStreamFromString(string s)
{
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
</code></pre>
<p>Don't forget to use Using:</p>
<pre><code>using (var stream = GenerateStreamFromString("a,b \n c,d"))
{
// ... Do stuff to stream
}
</code></pre>
<hr>
<p>About the <code>StreamWriter</code> not being disposed. <code>StreamWriter</code> is just a wrapper around the base stream, and doesn't use any resources that need to be disposed. The <code>Dispose</code> method will close the underlying <code>Stream</code> that <code>StreamWriter</code> is writing to. In this case that is the <code>MemoryStream</code> we want to return.</p>
<p>In .NET 4.5 there is now an overload for <code>StreamWriter</code> that keeps the underlying stream open after the writer is disposed of, but this code does the same thing and works with other versions of .NET too.</p>
<p>See <a href="https://stackoverflow.com/questions/2666888/is-there-any-way-to-close-a-streamwriter-without-closing-its-basestream">Is there any way to close a StreamWriter without closing its BaseStream?</a></p> | {
"question_id": 1879395,
"question_date": "2009-12-10T08:14:34.120Z",
"question_score": 950,
"tags": "c#|unit-testing|string|stream",
"answer_id": 1879470,
"answer_date": "2009-12-10T08:28:04.087Z",
"answer_score": 1175
} |
Please answer the following Stack Overflow question:
Title: Parsing boolean values with argparse
<p>I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example:</p>
<pre><code>my_program --my_boolean_flag False
</code></pre>
<p>However, the following test code does not do what I would like:</p>
<pre><code>import argparse
parser = argparse.ArgumentParser(description="My parser")
parser.add_argument("--my_bool", type=bool)
cmd_line = ["--my_bool", "False"]
parsed_args = parser.parse(cmd_line)
</code></pre>
<p>Sadly, <code>parsed_args.my_bool</code> evaluates to <code>True</code>. This is the case even when I change <code>cmd_line</code> to be <code>["--my_bool", ""]</code>, which is surprising, since <code>bool("")</code> evalutates to <code>False</code>.</p>
<p>How can I get argparse to parse <code>"False"</code>, <code>"F"</code>, and their lower-case variants to be <code>False</code>?</p> | <p>This is actually outdated. For Python 3.7+, <a href="https://docs.python.org/3/library/argparse.html" rel="noreferrer">Argparse now supports boolean args</a> (search BooleanOptionalAction).</p>
<p>The implementation looks like this:</p>
<pre><code>import argparse
ap = argparse.ArgumentParser()
# List of args
ap.add_argument('--foo', default=True, type=bool, help='Some helpful text that is not bar. Default = True')
# Importable object
args = ap.parse_args()
</code></pre>
<p>One other thing to mention: this will block all entries other than True and False for the argument via argparse.ArgumentTypeError. You can create a custom error class for this if you want to try to change this for any reason.</p> | {
"question_id": 15008758,
"question_date": "2013-02-21T17:37:16.093Z",
"question_score": 950,
"tags": "python|boolean|argparse|command-line-arguments",
"answer_id": 68867708,
"answer_date": "2021-08-20T20:22:47.640Z",
"answer_score": 12
} |
Please answer the following Stack Overflow question:
Title: Javascript call() & apply() vs bind()?
<p>I already know that <code>apply</code> and <code>call</code> are similar functions which set <code>this</code> (context of a function).</p>
<p>The difference is with the way we send the arguments (manual vs array)</p>
<p><strong>Question:</strong></p>
<p>But when should I use the <code>bind()</code> method ?</p>
<pre><code>var obj = {
x: 81,
getX: function() {
return this.x;
}
};
alert(obj.getX.bind(obj)());
alert(obj.getX.call(obj));
alert(obj.getX.apply(obj));
</code></pre>
<p><a href="http://jsbin.com/awewof/1/edit" rel="noreferrer">jsbin</a></p> | <p>I created this comparison between function objects, function calls, <code>call/apply</code> and <code>bind</code> a while ago:</p>
<p><a href="https://i.stack.imgur.com/WHlX0.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/WHlX0.jpg" alt="enter image description here"></a></p>
<p><code>.bind</code> allows you to set the <code>this</code> value <em>now</em> while allowing you to execute the function <em>in the future</em>, because it returns a new function object.</p> | {
"question_id": 15455009,
"question_date": "2013-03-16T21:40:08.157Z",
"question_score": 950,
"tags": "javascript|arrays|function|this",
"answer_id": 54562241,
"answer_date": "2019-02-06T20:42:05.967Z",
"answer_score": 259
} |
Please answer the following Stack Overflow question:
Title: How do I list all cron jobs for all users?
<p>Is there a command or an existing script that will let me view all of a *NIX system's scheduled cron jobs at once? I'd like it to include all of the user crontabs, as well as <code>/etc/crontab</code>, and whatever's in <code>/etc/cron.d</code>. It would also be nice to see the specific commands run by <code>run-parts</code> in <code>/etc/crontab</code>.</p>
<p>Ideally, I'd like the output in a nice column form and ordered in some meaningful way.</p>
<p>I could then merge these listings from multiple servers to view the overall "schedule of events."</p>
<p>I was about to write such a script myself, but if someone's already gone to the trouble...</p> | <p>I ended up writing a script (I'm trying to teach myself the finer points of bash scripting, so that's why you don't see something like Perl here). It's not exactly a simple affair, but it does most of what I need. It uses Kyle's suggestion for looking up individual users' crontabs, but also deals with <code>/etc/crontab</code> (including the scripts launched by <code>run-parts</code> in <code>/etc/cron.hourly</code>, <code>/etc/cron.daily</code>, etc.) and the jobs in the <code>/etc/cron.d</code> directory. It takes all of those and merges them into a display something like the following:</p>
<pre><code>mi h d m w user command
09,39 * * * * root [ -d /var/lib/php5 ] && find /var/lib/php5/ -type f -cmin +$(/usr/lib/php5/maxlifetime) -print0 | xargs -r -0 rm
47 */8 * * * root rsync -axE --delete --ignore-errors / /mirror/ >/dev/null
17 1 * * * root /etc/cron.daily/apt
17 1 * * * root /etc/cron.daily/aptitude
17 1 * * * root /etc/cron.daily/find
17 1 * * * root /etc/cron.daily/logrotate
17 1 * * * root /etc/cron.daily/man-db
17 1 * * * root /etc/cron.daily/ntp
17 1 * * * root /etc/cron.daily/standard
17 1 * * * root /etc/cron.daily/sysklogd
27 2 * * 7 root /etc/cron.weekly/man-db
27 2 * * 7 root /etc/cron.weekly/sysklogd
13 3 * * * archiver /usr/local/bin/offsite-backup 2>&1
32 3 1 * * root /etc/cron.monthly/standard
36 4 * * * yukon /home/yukon/bin/do-daily-stuff
5 5 * * * archiver /usr/local/bin/update-logs >/dev/null
</code></pre>
<p>Note that it shows the user, and more-or-less sorts by hour and minute so that I can see the daily schedule.</p>
<p>So far, I've tested it on Ubuntu, Debian, and Red Hat AS.</p>
<pre class="lang-sh prettyprint-override"><code>#!/bin/bash
# System-wide crontab file and cron job directory. Change these for your system.
CRONTAB='/etc/crontab'
CRONDIR='/etc/cron.d'
# Single tab character. Annoyingly necessary.
tab=$(echo -en "\t")
# Given a stream of crontab lines, exclude non-cron job lines, replace
# whitespace characters with a single space, and remove any spaces from the
# beginning of each line.
function clean_cron_lines() {
while read line ; do
echo "${line}" |
egrep --invert-match '^($|\s*#|\s*[[:alnum:]_]+=)' |
sed --regexp-extended "s/\s+/ /g" |
sed --regexp-extended "s/^ //"
done;
}
# Given a stream of cleaned crontab lines, echo any that don't include the
# run-parts command, and for those that do, show each job file in the run-parts
# directory as if it were scheduled explicitly.
function lookup_run_parts() {
while read line ; do
match=$(echo "${line}" | egrep -o 'run-parts (-{1,2}\S+ )*\S+')
if [[ -z "${match}" ]] ; then
echo "${line}"
else
cron_fields=$(echo "${line}" | cut -f1-6 -d' ')
cron_job_dir=$(echo "${match}" | awk '{print $NF}')
if [[ -d "${cron_job_dir}" ]] ; then
for cron_job_file in "${cron_job_dir}"/* ; do # */ <not a comment>
[[ -f "${cron_job_file}" ]] && echo "${cron_fields} ${cron_job_file}"
done
fi
fi
done;
}
# Temporary file for crontab lines.
temp=$(mktemp) || exit 1
# Add all of the jobs from the system-wide crontab file.
cat "${CRONTAB}" | clean_cron_lines | lookup_run_parts >"${temp}"
# Add all of the jobs from the system-wide cron directory.
cat "${CRONDIR}"/* | clean_cron_lines >>"${temp}" # */ <not a comment>
# Add each user's crontab (if it exists). Insert the user's name between the
# five time fields and the command.
while read user ; do
crontab -l -u "${user}" 2>/dev/null |
clean_cron_lines |
sed --regexp-extended "s/^((\S+ +){5})(.+)$/\1${user} \3/" >>"${temp}"
done < <(cut --fields=1 --delimiter=: /etc/passwd)
# Output the collected crontab lines. Replace the single spaces between the
# fields with tab characters, sort the lines by hour and minute, insert the
# header line, and format the results as a table.
cat "${temp}" |
sed --regexp-extended "s/^(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(\S+) +(.*)$/\1\t\2\t\3\t\4\t\5\t\6\t\7/" |
sort --numeric-sort --field-separator="${tab}" --key=2,1 |
sed "1i\mi\th\td\tm\tw\tuser\tcommand" |
column -s"${tab}" -t
rm --force "${temp}"
</code></pre> | {
"question_id": 134906,
"question_date": "2008-09-25T18:01:31.083Z",
"question_score": 949,
"tags": "unix|cron",
"answer_id": 137173,
"answer_date": "2008-09-26T00:50:39.277Z",
"answer_score": 336
} |
Please answer the following Stack Overflow question:
Title: String representation of an Enum
<p>I have the following enumeration:</p>
<pre><code>public enum AuthenticationMethod
{
FORMS = 1,
WINDOWSAUTHENTICATION = 2,
SINGLESIGNON = 3
}
</code></pre>
<p>The problem however is that I need the word "FORMS" when I ask for AuthenticationMethod.FORMS and not the id 1.</p>
<p>I have found the following solution for this problem (<a href="http://www.codeproject.com/Articles/11130/String-Enumerations-in-C" rel="noreferrer">link</a>):</p>
<p>First I need to create a custom attribute called "StringValue":</p>
<pre><code>public class StringValue : System.Attribute
{
private readonly string _value;
public StringValue(string value)
{
_value = value;
}
public string Value
{
get { return _value; }
}
}
</code></pre>
<p>Then I can add this attribute to my enumerator:</p>
<pre><code>public enum AuthenticationMethod
{
[StringValue("FORMS")]
FORMS = 1,
[StringValue("WINDOWS")]
WINDOWSAUTHENTICATION = 2,
[StringValue("SSO")]
SINGLESIGNON = 3
}
</code></pre>
<p>And of course I need something to retrieve that StringValue:</p>
<pre><code>public static class StringEnum
{
public static string GetStringValue(Enum value)
{
string output = null;
Type type = value.GetType();
//Check first in our cached results...
//Look for our 'StringValueAttribute'
//in the field's custom attributes
FieldInfo fi = type.GetField(value.ToString());
StringValue[] attrs =
fi.GetCustomAttributes(typeof(StringValue),
false) as StringValue[];
if (attrs.Length > 0)
{
output = attrs[0].Value;
}
return output;
}
}
</code></pre>
<p>Good now I've got the tools to get a string value for an enumerator.
I can then use it like this:</p>
<pre><code>string valueOfAuthenticationMethod = StringEnum.GetStringValue(AuthenticationMethod.FORMS);
</code></pre>
<p>Okay now all of these work like a charm but I find it a whole lot of work. I was wondering if there is a better solution for this.</p>
<p>I also tried something with a dictionary and static properties but that wasn't better either.</p> | <p>Try <a href="http://www.javacamp.org/designPattern/enum.html" rel="noreferrer">type-safe-enum</a> pattern.</p>
<pre><code>public sealed class AuthenticationMethod {
private readonly String name;
private readonly int value;
public static readonly AuthenticationMethod FORMS = new AuthenticationMethod (1, "FORMS");
public static readonly AuthenticationMethod WINDOWSAUTHENTICATION = new AuthenticationMethod (2, "WINDOWS");
public static readonly AuthenticationMethod SINGLESIGNON = new AuthenticationMethod (3, "SSN");
private AuthenticationMethod(int value, String name){
this.name = name;
this.value = value;
}
public override String ToString(){
return name;
}
}
</code></pre>
<hr>
<p><strong>Update</strong>
Explicit (or implicit) type conversion can be done by</p>
<ul>
<li><p>adding static field with mapping</p>
<pre><code>private static readonly Dictionary<string, AuthenticationMethod> instance = new Dictionary<string,AuthenticationMethod>();
</code></pre>
<ul>
<li>n.b. In order that the initialisation of the the "enum member" fields doesn't throw a NullReferenceException when calling the instance constructor, be sure to put the Dictionary field before the "enum member" fields in your class. This is because static field initialisers are called in declaration order, and before the static constructor, creating the weird and necessary but confusing situation that the instance constructor can be called before all static fields have been initialised, and before the static constructor is called.</li>
</ul></li>
<li><p>filling this mapping in instance constructor</p>
<pre><code>instance[name] = this;
</code></pre></li>
<li><p>and adding <a href="http://msdn.microsoft.com/en-us/library/09479473.aspx" rel="noreferrer">user-defined type conversion operator</a></p>
<pre><code>public static explicit operator AuthenticationMethod(string str)
{
AuthenticationMethod result;
if (instance.TryGetValue(str, out result))
return result;
else
throw new InvalidCastException();
}
</code></pre></li>
</ul> | {
"question_id": 424366,
"question_date": "2009-01-08T14:15:55.720Z",
"question_score": 949,
"tags": "c#|enums",
"answer_id": 424414,
"answer_date": "2009-01-08T14:29:12.947Z",
"answer_score": 886
} |
Please answer the following Stack Overflow question:
Title: Is there a way to check if a file is in use?
<p>I'm writing a program in C# that needs to repeatedly access 1 image file. Most of the time it works, but if my computer's running fast, it will try to access the file before it's been saved back to the filesystem and throw an error:</p>
<blockquote>
<p>"File in use by another process"</p>
</blockquote>
<p>I would like to find a way around this, but all my Googling has only yielded creating checks by using exception handling. This is against my religion, so I was wondering if anyone has a better way of doing it?</p> | <p><strong>Updated NOTE on this solution</strong>: Checking with <code>FileAccess.ReadWrite</code> will fail for Read-Only files so the solution has been modified to check with <code>FileAccess.Read</code>.</p>
<p><strong>ORIGINAL:</strong>
I've used this code for the past several years, and I haven't had any issues with it.</p>
<p>Understand your hesitation about using exceptions, but you can't avoid them all of the time:</p>
<pre><code>protected virtual bool IsFileLocked(FileInfo file)
{
try
{
using(FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.None))
{
stream.Close();
}
}
catch (IOException)
{
//the file is unavailable because it is:
//still being written to
//or being processed by another thread
//or does not exist (has already been processed)
return true;
}
//file is not locked
return false;
}
</code></pre> | {
"question_id": 876473,
"question_date": "2009-05-18T06:37:40.640Z",
"question_score": 947,
"tags": "c#|.net|file|file-io|file-locking",
"answer_id": 937558,
"answer_date": "2009-06-02T01:20:19.047Z",
"answer_score": 632
} |
Please answer the following Stack Overflow question:
Title: Convert a PHP object to an associative array
<p>I'm integrating an API to my website which works with data stored in objects while my code is written using arrays.</p>
<p>I'd like a quick-and-dirty function to convert an object to an array.</p> | <p>Just typecast it</p>
<pre><code>$array = (array) $yourObject;
</code></pre>
<p>From <em><a href="http://www.php.net/manual/en/language.types.array.php" rel="noreferrer">Arrays</a></em>:</p>
<blockquote>
<p>If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side.</p>
</blockquote>
<p><strong>Example: Simple Object</strong></p>
<pre><code>$object = new StdClass;
$object->foo = 1;
$object->bar = 2;
var_dump( (array) $object );
</code></pre>
<p><em>Output:</em></p>
<pre><code>array(2) {
'foo' => int(1)
'bar' => int(2)
}
</code></pre>
<p><strong>Example: Complex Object</strong></p>
<pre><code>class Foo
{
private $foo;
protected $bar;
public $baz;
public function __construct()
{
$this->foo = 1;
$this->bar = 2;
$this->baz = new StdClass;
}
}
var_dump( (array) new Foo );
</code></pre>
<p><em>Output (with \0s edited in for clarity):</em></p>
<pre><code>array(3) {
'\0Foo\0foo' => int(1)
'\0*\0bar' => int(2)
'baz' => class stdClass#2 (0) {}
}
</code></pre>
<p><em>Output with <code>var_export</code> instead of <code>var_dump</code>:</em></p>
<pre><code>array (
'' . "\0" . 'Foo' . "\0" . 'foo' => 1,
'' . "\0" . '*' . "\0" . 'bar' => 2,
'baz' =>
stdClass::__set_state(array(
)),
)
</code></pre>
<p>Typecasting this way will not do deep casting of the object graph and you need to apply the null bytes (as explained in the manual quote) to access any non-public attributes. So this works best when casting StdClass objects or objects with only public properties. For quick and dirty (what you asked for) it's fine.</p>
<p>Also see this in-depth blog post:</p>
<ul>
<li><em><a href="http://ocramius.github.io/blog/fast-php-object-to-array-conversion/" rel="noreferrer">Fast PHP Object to Array conversion</a></em></li>
</ul> | {
"question_id": 4345554,
"question_date": "2010-12-03T12:34:16.763Z",
"question_score": 946,
"tags": "php|arrays",
"answer_id": 4345609,
"answer_date": "2010-12-03T12:40:10.947Z",
"answer_score": 1699
} |
Please answer the following Stack Overflow question:
Title: Undo a particular commit in Git that's been pushed to remote repos
<p>What is the simplest way to undo a particular commit that is:</p>
<ul>
<li>not in the head or HEAD</li>
<li>Has been pushed to the remote.</li>
</ul>
<p>Because if it is not the latest commit, </p>
<pre><code>git reset HEAD
</code></pre>
<p>doesn't work. And because it has been pushed to a remote,</p>
<pre><code>git rebase -i
</code></pre>
<p>and</p>
<pre><code>git rebase --onto
</code></pre>
<p>will cause some problem in the remotes. </p>
<p>More so, I don't want to modify the history really. If there was bad code, it was there in the history and can be seen. I just want it out in the working copy, and I don't mind a reverse merge commit.</p>
<p>In other words, what is the <a href="http://en.wikipedia.org/wiki/Git_%28software%29" rel="noreferrer">Git</a> equivalent of the following svn commands:</p>
<pre><code>svn merge -r 303:295 http://svn.example.com/repos/calc/trunk
</code></pre>
<p>which removes all changes from 295 to 302 by reverse merging all changes in those revisions, as a new commit.</p>
<pre><code>svn merge -c -302 ^/trunk
</code></pre>
<p>which undoes the 302 commit, of course by adding another commit that reverse merges the changes from that respective commit.</p>
<p>I thought it should be a fairly simple operation in Git and a fairly common use case. What else is the point of atomic commits? </p>
<p>We have staging <a href="http://en.wikipedia.org/wiki/Git_%28software%29#Stash" rel="noreferrer">stashing</a> and all to ensure the commits are perfectly atomic, shouldn't you be able to undo one or more of those atomic commits easily?</p> | <p>Identify the hash of the commit, using <code>git log</code>, then use <code>git revert <commit></code> to create a new commit that removes these changes. In a way, <code>git revert</code> is the converse of <code>git cherry-pick</code> -- the latter applies the patch to a branch that's missing it, the former removes it from a branch that has it.</p> | {
"question_id": 2318777,
"question_date": "2010-02-23T14:21:08.830Z",
"question_score": 946,
"tags": "git|version-control|git-reset|git-revert",
"answer_id": 2318847,
"answer_date": "2010-02-23T14:31:16.063Z",
"answer_score": 1452
} |
Please answer the following Stack Overflow question:
Title: What is the equivalent of Java static methods in Kotlin?
<p>There is no <code>static</code> keyword in Kotlin.</p>
<p>What is the best way to represent a <code>static</code> Java method in Kotlin?</p> | <p>You place the function in the "companion object".</p>
<p>So the java code like this:</p>
<pre><code>class Foo {
public static int a() { return 1; }
}
</code></pre>
<p>will become</p>
<pre><code>class Foo {
companion object {
fun a() : Int = 1
}
}
</code></pre>
<p>You can then use it from inside Kotlin code as</p>
<pre><code>Foo.a();
</code></pre>
<p>But from within Java code, you would need to call it as</p>
<pre><code>Foo.Companion.a();
</code></pre>
<p>(Which also works from within Kotlin.)</p>
<p>If you don't like having to specify the <code>Companion</code> bit you can either add a <code>@JvmStatic</code> annotation or name your companion class.</p>
<p>From the <a href="https://kotlinlang.org/docs/reference/object-declarations.html#companion-objects" rel="noreferrer">docs</a>:</p>
<blockquote>
<h1>Companion Objects</h1>
<p>An object declaration inside a class can be marked with the <code>companion</code>
keyword:</p>
<pre><code>class MyClass {
companion object Factory {
fun create(): MyClass = MyClass()
}
}
</code></pre>
<p>Members of the companion object can be called by using simply the class
name as the qualifier:</p>
<pre><code>val instance = MyClass.create()
</code></pre>
<p>...</p>
<p>However, on the JVM you can have members of companion objects generated
as real static methods and fields, if you use the <code>@JvmStatic</code>
annotation. See the <a href="https://kotlinlang.org/docs/java-to-kotlin-interop.html#static-fields" rel="noreferrer">Java interoperability</a> section for more details.</p>
</blockquote>
<p>Adding the <code>@JvmStatic</code> annotation looks like this</p>
<pre><code>class Foo {
companion object {
@JvmStatic
fun a() : Int = 1;
}
}
</code></pre>
<p>and then it will exist as a real Java static function, accessible from
both Java and Kotlin as <code>Foo.a()</code>.</p>
<p>If it is just disliked for the <code>Companion</code> name, then you can also
provide an explicit name for the companion object looks like this:</p>
<pre><code>class Foo {
companion object Blah {
fun a() : Int = 1;
}
}
</code></pre>
<p>which will let you call it from Kotlin in the same way, but
from java like <code>Foo.Blah.a()</code> (which will also work in Kotlin).</p> | {
"question_id": 40352684,
"question_date": "2016-11-01T00:52:33.640Z",
"question_score": 946,
"tags": "java|kotlin|static",
"answer_id": 40352734,
"answer_date": "2016-11-01T01:00:06.750Z",
"answer_score": 1348
} |
Please answer the following Stack Overflow question:
Title: jQuery get value of select onChange
<p>I was under the impression that I could get the value of a select input by doing this <code>$(this).val();</code> and applying the <code>onchange</code> parameter to the select field.</p>
<p>It would appear it only works if I reference the ID. </p>
<p>How do I do it using this.</p> | <p>Try this-</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$('select').on('change', function() {
alert( this.value );
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="1">One</option>
<option value="2">Two</option>
</select></code></pre>
</div>
</div>
</p>
<p>You can also reference with onchange event-</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function getval(sel)
{
alert(sel.value);
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><select onchange="getval(this);">
<option value="1">One</option>
<option value="2">Two</option>
</select></code></pre>
</div>
</div>
</p> | {
"question_id": 11179406,
"question_date": "2012-06-24T17:00:50.037Z",
"question_score": 945,
"tags": "jquery|select",
"answer_id": 11179421,
"answer_date": "2012-06-24T17:02:49.450Z",
"answer_score": 1827
} |
Please answer the following Stack Overflow question:
Title: How do I check if a file exists in Java?
<blockquote>
<p>How can I check whether a file exists, before opening it for reading in <strong>Java</strong> (the equivalent of <strong>Perl's</strong> <code>-e $filename</code>)? </p>
</blockquote>
<p>The only <a href="https://stackoverflow.com/questions/1237235/check-file-exists-java">similar question on SO</a> deals with writing the file and was thus answered using <code>FileWriter</code> which is obviously not applicable here.</p>
<p>If possible I'd prefer a real <em>API</em> call returning true/false as opposed to some "Call API to open a file and catch when it throws an exception which you check for 'no file' in the text", but I can live with the latter.</p> | <p>Using <a href="https://docs.oracle.com/javase/9/docs/api/java/io/File.html" rel="noreferrer"><code>java.io.File</code></a>:</p>
<pre><code>File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}
</code></pre> | {
"question_id": 1816673,
"question_date": "2009-11-29T20:32:39.460Z",
"question_score": 945,
"tags": "java|file-io|io|file-exists",
"answer_id": 1816676,
"answer_date": "2009-11-29T20:35:03.350Z",
"answer_score": 1471
} |
Please answer the following Stack Overflow question:
Title: Error:java: javacTask: source release 8 requires target release 1.8
<p>Using IntelliJ IDE can't compile any projects. Screenshots of settings below:</p>
<p>Used JDK:</p>
<p><a href="https://i.stack.imgur.com/cpggk.png"><img src="https://i.stack.imgur.com/cpggk.png" alt="http://gyazo.com/b6e32119af7b04090d890cad04db6373"></a></p>
<p>Project SDK and Language level:</p>
<p><a href="https://i.stack.imgur.com/0gEQl.png"><img src="https://i.stack.imgur.com/0gEQl.png" alt="http://gyazo.com/55a5fc9f7f2bb721a04780ce9d74eeab"></a></p>
<p>Language Level:</p>
<p><a href="https://i.stack.imgur.com/8z6A4.png"><img src="https://i.stack.imgur.com/8z6A4.png" alt="http://gyazo.com/143bffad63fd89cafc231298729df2fc"></a></p>
<p>Anybody have any ideas?</p> | <ol>
<li>Go to <strong>File > Settings > Build, Execution, Deployment > Compiler > Java Compiler</strong> If on a Mac, it's under <strong>Intellij IDEA > Preferences... > Build, Execution, Deployment > Java Compiler</strong></li>
<li>Change <strong>Target bytecode version</strong> to <strong>1.8</strong> of the module that you are working for.</li>
</ol>
<p><strong>If you are using Maven</strong></p>
<p>Add the compiler plugin to <code>pom.xml</code> under the top-level <code>project</code> node:</p>
<pre><code><build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</code></pre>
<p>(Hoisted from the comments.)</p>
<p>Note: If you don't mind reimporting your project, then the only thing you really need to do is change the pom and reimport the project, then IntelliJ will pick up the correct settings and you don't have to manually change them.</p> | {
"question_id": 29888592,
"question_date": "2015-04-27T06:24:28.277Z",
"question_score": 945,
"tags": "java|intellij-idea|java-8",
"answer_id": 30524848,
"answer_date": "2015-05-29T08:31:47.760Z",
"answer_score": 2017
} |
Please answer the following Stack Overflow question:
Title: What are the differences between the urllib, urllib2, urllib3 and requests module?
<p>In Python, what are the differences between the <a href="https://docs.python.org/library/urllib.html" rel="noreferrer"><code>urllib</code></a>, <a href="https://docs.python.org/2.7/library/urllib2.html" rel="noreferrer"><code>urllib2</code></a>, <a href="https://urllib3.readthedocs.io/en/latest/" rel="noreferrer"><code>urllib3</code></a> and <a href="https://requests.readthedocs.io" rel="noreferrer"><code>requests</code></a> modules? Why are there three? They seem to do the same thing...</p> | <p>I know it's been said already, but I'd highly recommend the <a href="https://requests.readthedocs.io/" rel="noreferrer"><code>requests</code></a> Python package.</p>
<p>If you've used languages other than python, you're probably thinking <code>urllib</code> and <code>urllib2</code> are easy to use, not much code, and highly capable, that's how I used to think. But the <code>requests</code> package is so unbelievably useful and short that everyone should be using it.</p>
<p>First, it supports a fully restful API, and is as easy as:</p>
<pre><code>import requests
resp = requests.get('http://www.mywebsite.com/user')
resp = requests.post('http://www.mywebsite.com/user')
resp = requests.put('http://www.mywebsite.com/user/put')
resp = requests.delete('http://www.mywebsite.com/user/delete')
</code></pre>
<p>Regardless of whether GET / POST, you never have to encode parameters again, it simply takes a dictionary as an argument and is good to go:</p>
<pre><code>userdata = {"firstname": "John", "lastname": "Doe", "password": "jdoe123"}
resp = requests.post('http://www.mywebsite.com/user', data=userdata)
</code></pre>
<p>Plus it even has a built in JSON decoder (again, I know <code>json.loads()</code> isn't a lot more to write, but this sure is convenient):</p>
<pre><code>resp.json()
</code></pre>
<p>Or if your response data is just text, use:</p>
<pre><code>resp.text
</code></pre>
<p>This is just the tip of the iceberg. This is the list of features from the requests site:</p>
<ul>
<li>International Domains and URLs</li>
<li>Keep-Alive & Connection Pooling</li>
<li>Sessions with Cookie Persistence</li>
<li>Browser-style SSL Verification</li>
<li>Basic/Digest Authentication</li>
<li>Elegant Key/Value Cookies</li>
<li>Automatic Decompression</li>
<li>Unicode Response Bodies</li>
<li>Multipart File Uploads</li>
<li>Connection Timeouts</li>
<li>.netrc support</li>
<li>List item</li>
<li>Python 2.7, 3.6—3.9</li>
<li>Thread-safe.</li>
</ul> | {
"question_id": 2018026,
"question_date": "2010-01-07T03:26:35.793Z",
"question_score": 944,
"tags": "python|python-requests|urllib2|urllib|python-2.x",
"answer_id": 14804320,
"answer_date": "2013-02-11T00:32:09.150Z",
"answer_score": 835
} |
Please answer the following Stack Overflow question:
Title: Sending email in .NET through Gmail
<p>Instead of relying on my host to send an email, I was thinking of sending the email messages using my <strong>Gmail</strong> account. The emails are personalized emails to the bands I play on my show. </p>
<p>Is it possible to do it?</p> | <p>Be sure to use <code>System.Net.Mail</code>, not the deprecated <code>System.Web.Mail</code>. Doing SSL with <code>System.Web.Mail</code> is a gross mess of hacky extensions.</p>
<pre><code>using System.Net;
using System.Net.Mail;
var fromAddress = new MailAddress("[email protected]", "From Name");
var toAddress = new MailAddress("[email protected]", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
</code></pre>
<p>Additionally go to the <a href="https://myaccount.google.com/security" rel="noreferrer"><em>Google Account > Security</em></a> page and look at the <em>Signing in to Google > 2-Step Verification</em> setting.</p>
<ul>
<li>If it is enabled, then you have to generate a password allowing .NET to bypass the 2-Step Verification. To do this, click on <a href="https://myaccount.google.com/apppasswords" rel="noreferrer"><em>Signing in to Google > App passwords</em></a>, select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the <code>fromPassword</code> constant instead of your standard Gmail password.</li>
<li>If it is disabled, then you have to turn on <a href="https://myaccount.google.com/lesssecureapps" rel="noreferrer"><em>Less secure app access</em></a>, which is not recommended! So better enable the 2-Step verification.</li>
</ul> | {
"question_id": 32260,
"question_date": "2008-08-28T13:28:38.147Z",
"question_score": 943,
"tags": "c#|.net|email|smtp|gmail",
"answer_id": 32336,
"answer_date": "2008-08-28T14:08:03.307Z",
"answer_score": 1144
} |
Please answer the following Stack Overflow question:
Title: Can't find the 'libpq-fe.h header when trying to install pg gem
<p>I am using the Ruby on Rails 3.1 pre version. I like to use PostgreSQL, but the problem is installing the <code>pg</code> gem. It gives me the following error:</p>
<pre><code>$ gem install pg
Building native extensions. This could take a while...
ERROR: Error installing pg:
ERROR: Failed to build gem native extension.
/home/u/.rvm/rubies/ruby-1.9.2-p0/bin/ruby extconf.rb
checking for pg_config... no
No pg_config... trying anyway. If building fails, please try again with
--with-pg-config=/path/to/pg_config
checking for libpq-fe.h... no
Can't find the 'libpq-fe.h header
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers. Check the mkmf.log file for more
details. You may need configuration options.
Provided configuration options:
--with-opt-dir
--without-opt-dir
--with-opt-include
--without-opt-include=${opt-dir}/include
--with-opt-lib
--without-opt-lib=${opt-dir}/lib
--with-make-prog
--without-make-prog
--srcdir=.
--curdir
--ruby=/home/u/.rvm/rubies/ruby-1.9.2-p0/bin/ruby
--with-pg
--without-pg
--with-pg-dir
--without-pg-dir
--with-pg-include
--without-pg-include=${pg-dir}/include
--with-pg-lib
--without-pg-lib=${pg-dir}/lib
--with-pg-config
--without-pg-config
--with-pg_config
--without-pg_config
Gem files will remain installed in /home/u/.rvm/gems/ruby-1.9.2-p0/gems/pg-0.11.0 for inspection.
Results logged to /home/u/.rvm/gems/ruby-1.9.2-p0/gems/pg-0.11.0/ext/gem_make.out
</code></pre>
<p>How do I solve this problem?</p> | <p>It looks like in Ubuntu that header is part of the <a href="http://packages.ubuntu.com/natty/i386/libpq-dev/filelist" rel="noreferrer"><code>libpq-dev</code> package</a> (at least in the following Ubuntu versions:
<a href="http://en.wikipedia.org/wiki/List_of_Ubuntu_releases#Ubuntu_11.04_.28Natty_Narwhal.29" rel="noreferrer">11.04</a> (Natty Narwhal), <a href="https://en.wikipedia.org/wiki/List_of_Ubuntu_releases#Ubuntu_10.04_LTS_.28Lucid_Lynx.29" rel="noreferrer">10.04</a> (Lucid Lynx), <a href="http://en.wikipedia.org/wiki/List_of_Ubuntu_releases#Ubuntu_11.10_.28Oneiric_Ocelot.29" rel="noreferrer">11.10</a> (Oneiric Ocelot), <a href="http://en.wikipedia.org/wiki/List_of_Ubuntu_releases#Ubuntu_12.04_LTS_.28Precise_Pangolin.29" rel="noreferrer">12.04</a> (Precise Pangolin), <a href="https://en.wikipedia.org/wiki/List_of_Ubuntu_releases#Ubuntu_14.04_LTS_.28Trusty_Tahr.29" rel="noreferrer">14.04</a> (Trusty Tahr) and <a href="https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_18.04_LTS_(Bionic_Beaver)" rel="noreferrer">18.04</a> (Bionic Beaver)):</p>
<pre><code>...
/usr/include/postgresql/libpq-fe.h
...
</code></pre>
<p>So try installing <code>libpq-dev</code> or its equivalent for your OS:</p>
<ul>
<li>For Ubuntu/Debian systems: <code>sudo apt-get install libpq-dev</code></li>
<li>On <a href="http://en.wikipedia.org/wiki/Red_Hat_Linux" rel="noreferrer">Red Hat Linux</a> (RHEL) systems: <code>yum install postgresql-devel</code></li>
<li>For Mac <a href="https://en.wikipedia.org/wiki/Homebrew_%28package_management_software%29" rel="noreferrer">Homebrew</a>: <code>brew install postgresql</code></li>
<li>For Mac <a href="http://en.wikipedia.org/wiki/MacPorts" rel="noreferrer">MacPorts</a> PostgreSQL: <code>gem install pg -- --with-pg-config=/opt/local/lib/postgresql[version number]/bin/pg_config</code></li>
<li>For <a href="https://en.wikipedia.org/wiki/OpenSUSE" rel="noreferrer">OpenSuse</a>: <code>zypper in postgresql-devel</code></li>
<li>For <a href="https://en.wikipedia.org/wiki/Arch_Linux" rel="noreferrer">ArchLinux</a>: <code>pacman -S postgresql-libs</code></li>
</ul> | {
"question_id": 6040583,
"question_date": "2011-05-18T06:11:09.647Z",
"question_score": 943,
"tags": "ruby-on-rails|ruby-on-rails-3|postgresql|rails-postgresql|pg",
"answer_id": 6040822,
"answer_date": "2011-05-18T06:41:38.540Z",
"answer_score": 1505
} |
Please answer the following Stack Overflow question:
Title: jQuery disable/enable submit button
<p>I have this HTML:</p>
<pre><code><input type="text" name="textField" />
<input type="submit" value="send" />
</code></pre>
<p>How can I do something like this:</p>
<ul>
<li>When the text field is empty the submit should be disabled (disabled="disabled").</li>
<li>When something is typed in the text field to remove the disabled attribute.</li>
<li>If the text field becomes empty again(the text is deleted) the submit button should be disabled again.</li>
</ul>
<p>I tried something like this:</p>
<pre><code>$(document).ready(function(){
$('input[type="submit"]').attr('disabled','disabled');
$('input[type="text"]').change(function(){
if($(this).val != ''){
$('input[type="submit"]').removeAttr('disabled');
}
});
});
</code></pre>
<p>…but it doesn't work. Any ideas?</p> | <p>The problem is that the change event fires only when focus is moved away from the input (e.g. someone clicks off the input or tabs out of it). Try using keyup instead:</p>
<pre><code>$(document).ready(function() {
$(':input[type="submit"]').prop('disabled', true);
$('input[type="text"]').keyup(function() {
if($(this).val() != '') {
$(':input[type="submit"]').prop('disabled', false);
}
});
});
</code></pre> | {
"question_id": 1594952,
"question_date": "2009-10-20T14:21:12.410Z",
"question_score": 942,
"tags": "javascript|html|jquery",
"answer_id": 1594992,
"answer_date": "2009-10-20T14:26:29.733Z",
"answer_score": 1389
} |
Please answer the following Stack Overflow question:
Title: How to convert an instance of std::string to lower case
<p>I want to convert a <code>std::string</code> to lowercase. I am aware of the function <code>tolower()</code>. However, in the past I have had issues with this function and it is hardly ideal anyway as using it with a <code>std::string</code> would require iterating over each character.</p>
<p>Is there an alternative which works 100% of the time?</p> | <p>Adapted from <a href="http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/" rel="noreferrer"><em>Not So Frequently Asked Questions</em></a>:</p>
<pre><code>#include <algorithm>
#include <cctype>
#include <string>
std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(),
[](unsigned char c){ return std::tolower(c); });
</code></pre>
<p>You're really not going to get away without iterating through each character. There's no way to know whether the character is lowercase or uppercase otherwise.</p>
<p>If you really hate <a href="https://en.cppreference.com/w/cpp/string/byte/tolower" rel="noreferrer"><code>tolower()</code></a>, here's a specialized ASCII-only alternative that I don't recommend you use:</p>
<pre><code>char asciitolower(char in) {
if (in <= 'Z' && in >= 'A')
return in - ('Z' - 'z');
return in;
}
std::transform(data.begin(), data.end(), data.begin(), asciitolower);
</code></pre>
<p>Be aware that <code>tolower()</code> can only do a per-single-byte-character substitution, which is ill-fitting for many scripts, especially if using a multi-byte-encoding like UTF-8.</p> | {
"question_id": 313970,
"question_date": "2008-11-24T11:49:59.793Z",
"question_score": 942,
"tags": "c++|string|c++-standard-library|tolower",
"answer_id": 313990,
"answer_date": "2008-11-24T11:59:33.050Z",
"answer_score": 1067
} |
Please answer the following Stack Overflow question:
Title: See :hover state in Chrome Developer Tools
<p>I want to see the <code>:hover</code> style for an anchor I'm hovering on in <strong>Chrome</strong>. In <strong>Firebug</strong>, there's a style dropdown that allows me to select different states for an element. </p>
<blockquote>
<p>I can't seem to find anything similar in Chrome. Am I missing something?</p>
</blockquote> | <p>Now you can see both the pseudo-class rules and force them on elements. </p>
<p>To see the rules like <code>:hover</code> in the Styles pane click the small <code>:hov</code> text in the top right.</p>
<p><a href="https://i.stack.imgur.com/NwulC.png" rel="noreferrer"><img src="https://i.stack.imgur.com/NwulC.png" alt="Toggle element state"></a></p>
<p>To force an element into <code>:hover</code> state, right click it and select <code>:hover</code>.</p>
<p><a href="https://i.stack.imgur.com/XzMCB.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XzMCB.png" alt="Force element state"></a></p>
<p>Additional tips on the <a href="https://developers.google.com/chrome-developer-tools/docs/shortcuts#elements-panel" rel="noreferrer" title="elements panel">elements panel</a> in <a href="https://developers.google.com/chrome-developer-tools/docs/shortcuts" rel="noreferrer" title="Chrome Developer Tools Shortcuts">Chrome Developer Tools Shortcuts</a>.</p> | {
"question_id": 4515124,
"question_date": "2010-12-23T01:16:54.457Z",
"question_score": 942,
"tags": "css|google-chrome|browser|google-chrome-devtools",
"answer_id": 6778547,
"answer_date": "2011-07-21T15:25:11.307Z",
"answer_score": 1393
} |
Please answer the following Stack Overflow question:
Title: How can I get the current date and time in the terminal and set a custom command in the terminal for it?
<p>I have to check the time in a Linux terminal.</p>
<p>What is the command for getting date and time in a Linux terminal?</p>
<p>Is there a way in which we can set a custom function?</p> | <p>The command is <code>date</code></p>
<p>To customise the output there are a myriad of options available, see <code>date --help</code> for a list.</p>
<p>For example, <code>date '+%A %W %Y %X'</code> gives <code>Tuesday 34 2013 08:04:22</code> which is the name of the day of the week, the week number, the year and the time.</p> | {
"question_id": 18458839,
"question_date": "2013-08-27T06:52:17.103Z",
"question_score": 941,
"tags": "linux|command-line|terminal",
"answer_id": 18459076,
"answer_date": "2013-08-27T07:05:38.817Z",
"answer_score": 1299
} |
Please answer the following Stack Overflow question:
Title: How can I remove a style added with .css() function?
<p>I'm changing <strong>CSS</strong> with <strong>jQuery</strong> and I wish to remove the styling I'm adding based on the input value:</p>
<pre><code>if(color != '000000') $("body").css("background-color", color); else // remove style ?
</code></pre>
<blockquote>
<p>How can I do this?<br>
Note that the line above runs whenever a color is selected using a color picker (ie. when the mouse moves over a color wheel).</p>
</blockquote>
<p>2nd note: I can't do this with <code>css("background-color", "none")</code> because it will remove the default styling from the <strong>CSS</strong> files.<br>
I just want to remove the <code>background-color</code> inline style added by <strong>jQuery</strong>.</p> | <p>Changing the property to an empty string appears to do the job:</p>
<pre><code>$.css("background-color", "");
</code></pre> | {
"question_id": 4036857,
"question_date": "2010-10-27T19:21:10.490Z",
"question_score": 941,
"tags": "javascript|jquery|css",
"answer_id": 4036868,
"answer_date": "2010-10-27T19:22:17.183Z",
"answer_score": 1421
} |
Please answer the following Stack Overflow question:
Title: How to set TextView textStyle such as bold, italic
<p>How to set <code>TextView</code> style (bold or italic) within Java and without using the XML layout?</p>
<p>In other words, I need to write <code>android:textStyle</code> with Java.</p> | <pre><code>textView.setTypeface(null, Typeface.BOLD_ITALIC);
textView.setTypeface(null, Typeface.BOLD);
textView.setTypeface(null, Typeface.ITALIC);
textView.setTypeface(null, Typeface.NORMAL);
</code></pre>
<p>To keep the previous typeface</p>
<pre><code>textView.setTypeface(textView.getTypeface(), Typeface.BOLD_ITALIC)
</code></pre> | {
"question_id": 6200533,
"question_date": "2011-06-01T11:41:19.843Z",
"question_score": 941,
"tags": "android|textview|styles",
"answer_id": 6200841,
"answer_date": "2011-06-01T12:04:56.777Z",
"answer_score": 2069
} |
Please answer the following Stack Overflow question:
Title: What is the strict aliasing rule?
<p>When asking about <a href="https://stackoverflow.com/questions/98340/what-are-the-common-undefinedunspecified-behavior-for-c-that-you-run-into">common undefined behavior in C</a>, people sometimes refer to the strict aliasing rule.<br>
What are they talking about?</p> | <p>A typical situation where you encounter strict aliasing problems is when overlaying a struct (like a device/network msg) onto a buffer of the word size of your system (like a pointer to <code>uint32_t</code>s or <code>uint16_t</code>s). When you overlay a struct onto such a buffer, or a buffer onto such a struct through pointer casting you can easily violate strict aliasing rules.</p>
<p>So in this kind of setup, if I want to send a message to something I'd have to have two incompatible pointers pointing to the same chunk of memory. I might then naively code something like this:</p>
<pre><code>typedef struct Msg
{
unsigned int a;
unsigned int b;
} Msg;
void SendWord(uint32_t);
int main(void)
{
// Get a 32-bit buffer from the system
uint32_t* buff = malloc(sizeof(Msg));
// Alias that buffer through message
Msg* msg = (Msg*)(buff);
// Send a bunch of messages
for (int i = 0; i < 10; ++i)
{
msg->a = i;
msg->b = i+1;
SendWord(buff[0]);
SendWord(buff[1]);
}
}
</code></pre>
<p>The strict aliasing rule makes this setup illegal: dereferencing a pointer that aliases an object that is not of a <a href="http://en.cppreference.com/w/c/language/type" rel="noreferrer">compatible type</a> or one of the other types allowed by C 2011 6.5 paragraph 7<sup>1</sup> is undefined behavior. Unfortunately, you can still code this way, <em>maybe</em> get some warnings, have it compile fine, only to have weird unexpected behavior when you run the code.</p>
<p>(GCC appears somewhat inconsistent in its ability to give aliasing warnings, sometimes giving us a friendly warning and sometimes not.)</p>
<p>To see why this behavior is undefined, we have to think about what the strict aliasing rule buys the compiler. Basically, with this rule, it doesn't have to think about inserting instructions to refresh the contents of <code>buff</code> every run of the loop. Instead, when optimizing, with some annoyingly unenforced assumptions about aliasing, it can omit those instructions, load <code>buff[0]</code> and <code>buff[1]</code> into CPU registers once before the loop is run, and speed up the body of the loop. Before strict aliasing was introduced, the compiler had to live in a state of paranoia that the contents of <code>buff</code> could change by any preceding memory stores. So to get an extra performance edge, and assuming most people don't type-pun pointers, the strict aliasing rule was introduced.</p>
<p>Keep in mind, if you think the example is contrived, this might even happen if you're passing a buffer to another function doing the sending for you, if instead you have.</p>
<pre><code>void SendMessage(uint32_t* buff, size_t size32)
{
for (int i = 0; i < size32; ++i)
{
SendWord(buff[i]);
}
}
</code></pre>
<p>And rewrote our earlier loop to take advantage of this convenient function</p>
<pre><code>for (int i = 0; i < 10; ++i)
{
msg->a = i;
msg->b = i+1;
SendMessage(buff, 2);
}
</code></pre>
<p>The compiler may or may not be able to or smart enough to try to inline SendMessage and it may or may not decide to load or not load buff again. If <code>SendMessage</code> is part of another API that's compiled separately, it probably has instructions to load buff's contents. Then again, maybe you're in C++ and this is some templated header only implementation that the compiler thinks it can inline. Or maybe it's just something you wrote in your .c file for your own convenience. Anyway undefined behavior might still ensue. Even when we know some of what's happening under the hood, it's still a violation of the rule so no well defined behavior is guaranteed. So just by wrapping in a function that takes our word delimited buffer doesn't necessarily help.</p>
<p><strong>So how do I get around this?</strong></p>
<ul>
<li><p>Use a union. Most compilers support this without complaining about strict aliasing. This is allowed in C99 and explicitly allowed in C11.</p>
<pre><code> union {
Msg msg;
unsigned int asBuffer[sizeof(Msg)/sizeof(unsigned int)];
};
</code></pre>
</li>
<li><p>You can disable strict aliasing in your compiler (<a href="http://gcc.gnu.org/onlinedocs/gcc-4.6.1/gcc/Optimize-Options.html#index-fstrict_002daliasing-825" rel="noreferrer">f[no-]strict-aliasing</a> in gcc))</p>
</li>
<li><p>You can use <code>char*</code> for aliasing instead of your system's word. The rules allow an exception for <code>char*</code> (including <code>signed char</code> and <code>unsigned char</code>). It's always assumed that <code>char*</code> aliases other types. However this won't work the other way: there's no assumption that your struct aliases a buffer of chars.</p>
</li>
</ul>
<p><strong>Beginner beware</strong></p>
<p>This is only one potential minefield when overlaying two types onto each other. You should also learn about <a href="http://en.wikipedia.org/wiki/Endianness" rel="noreferrer">endianness</a>, <a href="http://web.archive.org/web/20170708093042/http://www.cs.umd.edu:80/class/sum2003/cmsc311/Notes/Data/aligned.html" rel="noreferrer">word alignment</a>, and how to deal with alignment issues through <a href="http://grok2.com/structure_packing.html" rel="noreferrer">packing structs</a> correctly.</p>
<h2>Footnote</h2>
<p><sup>1</sup> The types that C 2011 6.5 7 allows an lvalue to access are:</p>
<ul>
<li>a type compatible with the effective type of the object,</li>
<li>a qualified version of a type compatible with the effective type of the object,</li>
<li>a type that is the signed or unsigned type corresponding to the effective type of the object,</li>
<li>a type that is the signed or unsigned type corresponding to a qualified version of the effective type of the object,</li>
<li>an aggregate or union type that includes one of the aforementioned types among its members (including, recursively, a member of a subaggregate or contained union), or</li>
<li>a character type.</li>
</ul> | {
"question_id": 98650,
"question_date": "2008-09-19T01:30:27.830Z",
"question_score": 941,
"tags": "c++|c|undefined-behavior|strict-aliasing|type-punning",
"answer_id": 99010,
"answer_date": "2008-09-19T02:36:24.677Z",
"answer_score": 660
} |
Please answer the following Stack Overflow question:
Title: How do I check the versions of Python modules?
<p>I installed the Python modules <code>construct</code> and <code>statlib</code> using <code>setuptools</code>:</p>
<pre><code>sudo apt-get install python-setuptools
sudo easy_install statlib
sudo easy_install construct
</code></pre>
<p>How do I check their versions from the command line?</p> | <p><a href="https://stackoverflow.com/a/3220572/1265154">Use <code>pip</code> instead of <code>easy_install</code>.</a></p>
<p>With pip, list all installed packages and their versions via:</p>
<pre class="lang-none prettyprint-override"><code>pip freeze
</code></pre>
<p>On most Linux systems, you can pipe this to <code>grep</code> (or <code>findstr</code> on Windows) to find the row for the particular package you're interested in.</p>
<hr />
<h3>Linux:</h3>
<pre class="lang-none prettyprint-override"><code>pip freeze | grep lxml
</code></pre>
<blockquote>
<p>lxml==2.3</p>
</blockquote>
<h3>Windows:</h3>
<pre class="lang-none prettyprint-override"><code>pip freeze | findstr lxml
</code></pre>
<blockquote>
<p>lxml==2.3</p>
</blockquote>
<hr />
<p>For an individual module, you can try the <a href="http://www.python.org/dev/peps/pep-0396/" rel="noreferrer"><code>__version__</code> attribute</a>. However, there are modules without it:</p>
<pre class="lang-none prettyprint-override"><code>python -c "import requests; print(requests.__version__)"
2.14.2
python -c "import lxml; print(lxml.__version__)"
</code></pre>
<blockquote>
<p>Traceback (most recent call last): <br />
File "<string>", line 1, in <module> <br />
AttributeError: 'module' object has no attribute '<strong>version</strong>'</p>
</blockquote>
<p>Lastly, as the commands in your question are prefixed with <code>sudo</code>, it appears you're installing to the global python environment. I strongly advise to take look into Python <a href="https://pypi.python.org/pypi/virtualenv" rel="noreferrer">virtual environment</a> managers, for example <a href="http://virtualenvwrapper.readthedocs.org/en/latest/" rel="noreferrer">virtualenvwrapper</a>.</p> | {
"question_id": 20180543,
"question_date": "2013-11-24T20:25:01.600Z",
"question_score": 940,
"tags": "python",
"answer_id": 20180597,
"answer_date": "2013-11-24T20:30:33.187Z",
"answer_score": 975
} |
Please answer the following Stack Overflow question:
Title: What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
<p>What's the real difference between declaring an array like this:</p>
<pre><code>var myArray = new Array();
</code></pre>
<p>and</p>
<pre><code>var myArray = [];
</code></pre> | <p>There is a difference, but there is no difference in that example.</p>
<p>Using the more verbose method: <code>new Array()</code> does have one extra option in the parameters: if you pass a number to the constructor, you will get an array of that length:</p>
<pre><code>x = new Array(5);
alert(x.length); // 5
</code></pre>
<p>To illustrate the different ways to create an array:</p>
<pre><code>var a = [], // these are the same
b = new Array(), // a and b are arrays with length 0
c = ['foo', 'bar'], // these are the same
d = new Array('foo', 'bar'), // c and d are arrays with 2 strings
// these are different:
e = [3] // e.length == 1, e[0] == 3
f = new Array(3), // f.length == 3, f[0] == undefined
;
</code></pre>
<p>Another difference is that when using <code>new Array()</code> you're able to set the size of the array, which affects the stack size. This can be useful if you're getting stack overflows (<a href="https://stackoverflow.com/q/44031591/930998">Performance of Array.push vs Array.unshift</a>) which is what happens when the size of the array exceeds the size of the stack, and it has to be re-created. So there can actually, depending on the use case, be a performance increase when using <code>new Array()</code> because you can prevent the overflow from happening.</p>
<p>As pointed out in <a href="https://stackoverflow.com/a/44471705/930998">this answer</a>, <code>new Array(5)</code> will not actually add five <code>undefined</code> items to the array. It simply adds space for five items. Be aware that using <code>Array</code> this way makes it difficult to rely on <code>array.length</code> for calculations.</p> | {
"question_id": 931872,
"question_date": "2009-05-31T11:23:32.597Z",
"question_score": 940,
"tags": "javascript|arrays|declaration",
"answer_id": 931875,
"answer_date": "2009-05-31T11:25:01.970Z",
"answer_score": 1052
} |
Please answer the following Stack Overflow question:
Title: What is the difference between a 'closure' and a 'lambda'?
<p>Could someone explain? I understand the basic concepts behind them but I often see them used interchangeably and I get confused. </p>
<p>And now that we're here, how do they differ from a regular function?</p> | <p>A <b>lambda</b> is just an anonymous function - a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but they behave the same way otherwise.</p>
<p>A <b>closure</b> is any function which <b>closes over</b> the <b>environment</b> in which it was defined. This means that it can access variables not in its parameter list. Examples:</p>
<pre><code>def func(): return h
def anotherfunc(h):
return func()
</code></pre>
<p>This will cause an error, because <code>func</code> does not <b>close over</b> the environment in <code>anotherfunc</code> - <code>h</code> is undefined. <code>func</code> only closes over the global environment. This will work:</p>
<pre><code>def anotherfunc(h):
def func(): return h
return func()
</code></pre>
<p>Because here, <code>func</code> is defined in <code>anotherfunc</code>, and in python 2.3 and greater (or some number like this) when they <i>almost</i> got closures correct (mutation still doesn't work), this means that it <b>closes over</b> <code>anotherfunc</code>'s environment and can access variables inside of it. In Python 3.1+, mutation works too when using <a href="http://docs.python.org/release/3.1.3/reference/simple_stmts.html#nonlocal" rel="noreferrer">the <code>nonlocal</code> keyword</a>.</p>
<p>Another important point - <code>func</code> will continue to close over <code>anotherfunc</code>'s environment even when it's no longer being evaluated in <code>anotherfunc</code>. This code will also work:</p>
<pre><code>def anotherfunc(h):
def func(): return h
return func
print anotherfunc(10)()
</code></pre>
<p>This will print 10.</p>
<p>This, as you notice, has nothing to do with <b>lambda</b>s - they are two different (although related) concepts.</p> | {
"question_id": 220658,
"question_date": "2008-10-21T03:12:54.860Z",
"question_score": 940,
"tags": "function|lambda|functional-programming|closures",
"answer_id": 220728,
"answer_date": "2008-10-21T03:58:32.583Z",
"answer_score": 768
} |
Please answer the following Stack Overflow question:
Title: Python `if x is not None` or `if not x is None`?
<p>I've always thought of the <code>if not x is None</code> version to be more clear, but Google's <a href="https://google.github.io/styleguide/pyguide.html?showone=True/False_evaluations#True/False_evaluations" rel="noreferrer">style guide</a> and <a href="https://www.python.org/dev/peps/pep-0008/#programming-recommendations" rel="noreferrer">PEP-8</a> both use <code>if x is not None</code>. Are there any minor performance differences (I'm assuming not), and is there any case where one really doesn't fit (making the other a clear winner for my convention)?*</p>
<p>*I'm referring to any singleton, rather than just <code>None</code>.</p>
<blockquote>
<p>...to compare singletons like
None. Use is or is not.</p>
</blockquote> | <p>There's no performance difference, as they compile to the same bytecode:</p>
<pre><code>>>> import dis
>>> dis.dis("not x is None")
1 0 LOAD_NAME 0 (x)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
>>> dis.dis("x is not None")
1 0 LOAD_NAME 0 (x)
2 LOAD_CONST 0 (None)
4 COMPARE_OP 9 (is not)
6 RETURN_VALUE
</code></pre>
<p>Stylistically, I try to avoid <code>not x is y</code>, a human reader might misunderstand it as <code>(not x) is y</code>. If I write <code>x is not y</code> then there is no ambiguity.</p> | {
"question_id": 2710940,
"question_date": "2010-04-26T03:10:30.463Z",
"question_score": 939,
"tags": "python|coding-style|nonetype|boolean-expression|pep8",
"answer_id": 2711073,
"answer_date": "2010-04-26T03:55:04.673Z",
"answer_score": 1213
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.