input_text
stringlengths 115
13.8k
| output_text
stringlengths 24
15k
| metadata
dict |
---|---|---|
Please answer the following Stack Overflow question:
Title: Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000
<p>This is the error message that I get:</p>
<pre><code>Failed to execute 'postMessage' on 'DOMWindow': The target origin provided
('https://www.youtube.com') does not match the recipient window's origin
('http://localhost:9000').
</code></pre>
<p>I've seen other similar problems where the target origin is <code>http://www.youtube.com</code> and the recipient origin is <code>https://www.youtube.com</code>, but none like mine where the target is <code>https://www.youtube.com</code> and the origin is <code>http://localhost:9000</code>.</p>
<ol>
<li>I don't get the problem. What is the problem?</li>
<li>How can I fix it?</li>
</ol> | <p>I believe this is an issue with the target origin being <code>https</code>. I suspect it is because your iFrame url is using <code>http</code> instead of <code>https</code>. Try changing the url of the file you are trying to embed to be <code>https</code>.</p>
<p>For instance:</p>
<pre class="lang-js prettyprint-override"><code>'//www.youtube.com/embed/' + id + '?showinfo=0&enablejsapi=1&origin=http://localhost:9000';
</code></pre>
<p>to be:</p>
<pre class="lang-js prettyprint-override"><code>'https://www.youtube.com/embed/' + id + '?showinfo=0&enablejsapi=1&origin=http://localhost:9000';
</code></pre> | {
"question_id": 27573017,
"question_date": "2014-12-19T19:53:18.317Z",
"question_score": 216,
"tags": "javascript|angularjs|youtube|youtube-api|youtube-iframe-api",
"answer_id": 27574013,
"answer_date": "2014-12-19T21:17:04.260Z",
"answer_score": 115
} |
Please answer the following Stack Overflow question:
Title: Getting an "ambiguous redirect" error
<p>The following line in my Bash script</p>
<pre><code> echo $AAAA" "$DDDD" "$MOL_TAG >> ${OUPUT_RESULTS}
</code></pre>
<p>gives me this error:</p>
<pre><code> line 46: ${OUPUT_RESULTS}: ambiguous redirect
</code></pre>
<p>Why?</p> | <p>Bash can be pretty obtuse sometimes.</p>
<p>The following commands all return different error messages for basically the same error:</p>
<pre><code>$ echo hello >
bash: syntax error near unexpected token `newline`
$ echo hello > ${NONEXISTENT}
bash: ${NONEXISTENT}: ambiguous redirect
$ echo hello > "${NONEXISTENT}"
bash: : No such file or directory
</code></pre>
<p>Adding quotes around the variable seems to be a good way to deal with the "ambiguous redirect" message: You tend to get a better message when you've made a typing mistake -- and <strong>when the error is due to spaces in the filename, using quotes is the fix.</strong></p> | {
"question_id": 2462385,
"question_date": "2010-03-17T13:08:32.693Z",
"question_score": 216,
"tags": "bash",
"answer_id": 7775870,
"answer_date": "2011-10-15T05:03:09.220Z",
"answer_score": 330
} |
Please answer the following Stack Overflow question:
Title: PowerShell script to return versions of .NET Framework on a machine?
<p>What would a PowerShell script be to return versions of the .NET Framework on a machine?</p>
<p>My first guess is something involving WMI. Is there something better?</p>
<p>It should be a one-liner to return only the latest version for each installation of .NET [on each line].</p> | <p>If you're going to use the registry you have to recurse in order to get the full version for the 4.x Framework. The earlier answers both return the root number on my system for .NET 3.0 (where the WCF and WPF numbers, which are nested under 3.0, are higher -- I can't explain that), and fail to return anything for 4.0 ... </p>
<p>EDIT: For .Net 4.5 and up, this changed slightly again, so there's now a nice <a href="https://docs.microsoft.com/en-us/dotnet/framework/migration-guide/how-to-determine-which-versions-are-installed#to-find-net-framework-versions-by-querying-the-registry-in-code-net-framework-45-and-later" rel="noreferrer">MSDN article here</a> explaining how to convert the <em>Release</em> value to a .Net version number, it's a total train wreck :-(</p>
<p>This looks right to me (note that it outputs separate version numbers for WCF & WPF on 3.0. I don't know what that's about). It also outputs both <em>Client</em> and <em>Full</em> on 4.0 (if you have them both installed):</p>
<pre><code>Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -recurse |
Get-ItemProperty -name Version,Release -EA 0 |
Where { $_.PSChildName -match '^(?!S)\p{L}'} |
Select PSChildName, Version, Release
</code></pre>
<p>Based on the MSDN article, you could build a lookup table and return the marketing product version number for releases after 4.5:</p>
<pre><code>$Lookup = @{
378389 = [version]'4.5'
378675 = [version]'4.5.1'
378758 = [version]'4.5.1'
379893 = [version]'4.5.2'
393295 = [version]'4.6'
393297 = [version]'4.6'
394254 = [version]'4.6.1'
394271 = [version]'4.6.1'
394802 = [version]'4.6.2'
394806 = [version]'4.6.2'
460798 = [version]'4.7'
460805 = [version]'4.7'
461308 = [version]'4.7.1'
461310 = [version]'4.7.1'
461808 = [version]'4.7.2'
461814 = [version]'4.7.2'
528040 = [version]'4.8'
528049 = [version]'4.8'
}
# For One True framework (latest .NET 4x), change the Where-Object match
# to PSChildName -eq "Full":
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
Get-ItemProperty -name Version, Release -EA 0 |
Where-Object { $_.PSChildName -match '^(?!S)\p{L}'} |
Select-Object @{name = ".NET Framework"; expression = {$_.PSChildName}},
@{name = "Product"; expression = {$Lookup[$_.Release]}},
Version, Release
</code></pre>
<p>In fact, since I keep having to update this answer, here's a script to generate the script above (with a little extra) from the markdown source for that web page. This will probably break at some point, so I'm keeping the current copy above.</p>
<pre><code># Get the text from github
$url = "https://raw.githubusercontent.com/dotnet/docs/master/docs/framework/migration-guide/how-to-determine-which-versions-are-installed.md"
$md = Invoke-WebRequest $url -UseBasicParsing
$OFS = "`n"
# Replace the weird text in the tables, and the padding
# Then trim the | off the front and end of lines
$map = $md -split "`n" -replace " installed [^|]+" -replace "\s+\|" -replace "\|$" |
# Then we can build the table by looking for unique lines that start with ".NET Framework"
Select-String "^.NET" | Select-Object -Unique |
# And flip it so it's key = value
# And convert ".NET FRAMEWORK 4.5.2" to [version]4.5.2
ForEach-Object {
[version]$v, [int]$k = $_ -replace "\.NET Framework " -split "\|"
" $k = [version]'$v'"
}
# And output the whole script
@"
`$Lookup = @{
$map
}
# For extra effect we could get the Windows 10 OS version and build release id:
try {
`$WinRelease, `$WinVer = Get-ItemPropertyValue "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion" ReleaseId, CurrentMajorVersionNumber, CurrentMinorVersionNumber, CurrentBuildNumber, UBR
`$WindowsVersion = "`$(`$WinVer -join '.') (`$WinRelease)"
} catch {
`$WindowsVersion = [System.Environment]::OSVersion.Version
}
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse |
Get-ItemProperty -name Version, Release -EA 0 |
# For The One True framework (latest .NET 4x), change match to PSChildName -eq "Full":
Where-Object { `$_.PSChildName -match '^(?!S)\p{L}'} |
Select-Object @{name = ".NET Framework"; expression = {`$_.PSChildName}},
@{name = "Product"; expression = {`$Lookup[`$_.Release]}},
Version, Release,
# Some OPTIONAL extra output: PSComputerName and WindowsVersion
# The Computer name, so output from local machines will match remote machines:
@{ name = "PSComputerName"; expression = {`$Env:Computername}},
# The Windows Version (works on Windows 10, at least):
@{ name = "WindowsVersion"; expression = { `$WindowsVersion }}
"@
</code></pre> | {
"question_id": 3487265,
"question_date": "2010-08-15T12:02:02.557Z",
"question_score": 216,
"tags": ".net|powershell|version",
"answer_id": 3495491,
"answer_date": "2010-08-16T17:09:24.110Z",
"answer_score": 402
} |
Please answer the following Stack Overflow question:
Title: How to make a Python script run like a service or daemon in Linux
<p>I have written a Python script that checks a certain e-mail address and passes new e-mails to an external program. How can I get this script to execute 24/7, such as turning it into daemon or service in Linux. Would I also need a loop that never ends in the program, or can it be done by just having the code re executed multiple times?</p> | <p>You have two options here.</p>
<ol>
<li><p>Make a proper <strong>cron job</strong> that calls your script. Cron is a common name for a GNU/Linux daemon that periodically launches scripts according to a schedule you set. You add your script into a crontab or place a symlink to it into a special directory and the daemon handles the job of launching it in the background. You can <a href="http://en.wikipedia.org/wiki/Cron" rel="noreferrer">read more</a> at Wikipedia. There is a variety of different cron daemons, but your GNU/Linux system should have it already installed.</p></li>
<li><p>Use some kind of <strong>python approach</strong> (a library, for example) for your script to be able to daemonize itself. Yes, it will require a simple event loop (where your events are timer triggering, possibly, provided by sleep function).</p></li>
</ol>
<p>I wouldn't recommend you to choose 2., because you would be, in fact, repeating cron functionality. The Linux system paradigm is to let multiple simple tools interact and solve your problems. Unless there are additional reasons why you should make a daemon (in addition to trigger periodically), choose the other approach.</p>
<p>Also, if you use daemonize with a loop and a crash happens, no one will check the mail after that (as pointed out by <a href="https://stackoverflow.com/users/93988/ivan-nevostruev">Ivan Nevostruev</a> in comments to <a href="https://stackoverflow.com/questions/1603109/how-to-make-a-python-script-run-like-a-service-or-daemon-in-linux/1603146#1603146">this</a> answer). While if the script is added as a cron job, it will just trigger again.</p> | {
"question_id": 1603109,
"question_date": "2009-10-21T19:36:34.510Z",
"question_score": 216,
"tags": "python|linux|scripting|daemons",
"answer_id": 1603138,
"answer_date": "2009-10-21T19:43:06.880Z",
"answer_score": 110
} |
Please answer the following Stack Overflow question:
Title: How to take screenshot of a div with JavaScript?
<p>I am building something called the "HTML Quiz". It's completely ran on JavaScript and it's pretty cool.</p>
<p>At the end, a results box pops up that says "Your Results:" and it shows how much time they took, what percentage they got, and how many questions they got right out of 10. I would like to have a button that says "Capture results" and have it somehow take a screenshot or something of the div, and then just show the image captured on the page where they can right click and "Save image as."</p>
<p>I really would love to do this so they can share their results with others. I don't want them to "copy" the results because they can easily change that. If they change what it says in the image, oh well.</p>
<p>Does anyone know a way to do this or something similar? </p> | <p>No, I don't know of a way to 'screenshot' an element, but what you could do, is draw the quiz results into a canvas element, then use the <code>HTMLCanvasElement</code> object's <code>toDataURL</code> function to get a <code>data:</code> URI with the image's contents.</p>
<p>When the quiz is finished, do this:</p>
<pre><code>var c = document.getElementById('the_canvas_element_id');
var t = c.getContext('2d');
/* then use the canvas 2D drawing functions to add text, etc. for the result */
</code></pre>
<p>When the user clicks "Capture", do this:</p>
<pre><code>window.open('', document.getElementById('the_canvas_element_id').toDataURL());
</code></pre>
<p>This will open a new tab or window with the 'screenshot', allowing the user to save it. There is no way to invoke a 'save as' dialog of sorts, so this is the best you can do in my opinion.</p> | {
"question_id": 6887183,
"question_date": "2011-07-31T02:32:18.170Z",
"question_score": 216,
"tags": "javascript|jquery|html",
"answer_id": 6887206,
"answer_date": "2011-07-31T02:38:58.870Z",
"answer_score": 121
} |
Please answer the following Stack Overflow question:
Title: Configuring Git over SSH to login once
<p>I have cloned my git repository over ssh. So, each time I communicate with the origin master by pushing or pulling, I have to reenter my password. How can I configure git so that I do not need to enter my password multiple times?</p> | <h3>Try <code>ssh-add</code>, you need <code>ssh-agent</code> to be running and holding your private key</h3>
<p>(Ok, responding to the updated question, you first run <code>ssh-keygen</code> to generate a public and private key as <a href="https://stackoverflow.com/users/119963/jefromi">Jefromi</a> <a href="https://stackoverflow.com/a/1595858/450913">explained</a>. You put the public key on the server. You should use a passphrase, if you don't you have the equivalent of a plain-text password in your private key. But when you do, then you need as a practical matter <code>ssh-agent</code> as explained below.)</p>
<p>You want to be running <code>ssh-agent</code> in the background as you log in. Once you log in, the idea is to run <code>ssh-add</code> once and only once, in order to give the agent your passphrase, to decode your key. The agent then just sits in memory with your key unlocked and loaded, ready to use every time you ssh somewhere. </p>
<p>All ssh-family commands<sup>1</sup> will then consult the agent and automatically be able to use your private key.</p>
<p>On OSX (err, <em>macOS</em>), GNOME and KDE systems, <code>ssh-agent</code> is usually launched automatically for you. I will go through the details in case, like me, you also have a Cygwin or other windows environment where this most certainly is not done for you.</p>
<p>Start here: <code>man ssh-agent</code>.</p>
<p>There are various ways to automatically run the agent. As the man page explains, you can run it so that it is a parent of all your login session's other processes. That way, the environment variables it provides will automatically be in all your shells. When you (later) invoke <code>ssh-add</code> or <code>ssh</code> both will have access to the agent because they all have the environment variables with magic socket pathnames or whatever.</p>
<p>Alternatively, you can run the agent as an ordinary child, save the environment settings in a file, and source that file in every shell when it starts.</p>
<p>My OSX and Ubuntu systems automatically do the agent launch setup, so all I have to do is run <code>ssh-add</code> once. Try running <code>ssh-add</code> and see if it works, if so, then you just need to do that once per reboot. </p>
<p>My Cygwin system needed it done manually, so I did this in my <code>.profile</code> and I have <code>.bashrc</code> source <code>.profile</code>:</p>
<pre><code>. .agent > /dev/null
ps -p $SSH_AGENT_PID | grep ssh-agent > /dev/null || {
ssh-agent > .agent
. .agent > /dev/null
}
</code></pre>
<p>The <code>.agent</code> file is created automatically by the script; it contains the environment variables definitions and exports. The above tries to source the .agent file, and then tries to <code>ps(1)</code> the agent. If it doesn't work it starts an agent and creates a new agent file. You can also just run <code>ssh-add</code> and if it fails start an agent.
<hr>
<sup>1. And even local and remote <code>sudo</code> with the right pam extension.</sup></p> | {
"question_id": 1595848,
"question_date": "2009-10-20T16:27:27.250Z",
"question_score": 216,
"tags": "git|ssh|ssh-keys",
"answer_id": 1595863,
"answer_date": "2009-10-20T16:30:24.967Z",
"answer_score": 113
} |
Please answer the following Stack Overflow question:
Title: How do you synchronise projects to GitHub with Android Studio?
<p>I am trying to synchronise a project that I have on in my Android Studio folder to GitHub, but I am not fully sure what to do other than adding my credentials in the options menu. Could someone give me a quick guide, please?</p> | <p>Open the project you want to push in Android Studio.</p>
<p>Click <code>VCS -> Enable version Control Integration -> Git</code></p>
<p>There doesn't seem to be a way to add a remote through the GUI. So open Git Bash in the root of the project and do <code>git remote add <remote_name> <remote_url></code></p>
<p>Now when you do <code>VCS -> Commit changes -> Commit & Push</code> you should see your remote and everything should work through the GUI.</p>
<hr>
<p>If you are getting the error: <code>fatal: remote <remote_name> already exists</code> that means you already added it. To see your remotes do <code>git remote -v</code> and <code>git remote rm <remote_name></code> to remove.</p>
<hr>
<p>See these pages for details:</p>
<p><a href="http://www.jetbrains.com/idea/webhelp/using-git-integration.html" rel="noreferrer">http://www.jetbrains.com/idea/webhelp/using-git-integration.html</a></p>
<p><a href="http://gitref.org/remotes/" rel="noreferrer">http://gitref.org/remotes/</a></p> | {
"question_id": 16644946,
"question_date": "2013-05-20T07:53:02.260Z",
"question_score": 216,
"tags": "android|github|intellij-idea|android-studio",
"answer_id": 16682570,
"answer_date": "2013-05-22T02:34:55.240Z",
"answer_score": 274
} |
Please answer the following Stack Overflow question:
Title: How do I concatenate text files in Python?
<p>I have a list of 20 file names, like <code>['file1.txt', 'file2.txt', ...]</code>. I want to write a Python script to concatenate these files into a new file. I could open each file by <code>f = open(...)</code>, read line by line by calling <code>f.readline()</code>, and write each line into that new file. It doesn't seem very "elegant" to me, especially the part where I have to read/write line by line.</p>
<p>Is there a more "elegant" way to do this in Python?</p> | <p>This should do it</p>
<p><strong>For large files:</strong></p>
<pre><code>filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
for line in infile:
outfile.write(line)
</code></pre>
<p><strong>For small files:</strong></p>
<pre><code>filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
for fname in filenames:
with open(fname) as infile:
outfile.write(infile.read())
</code></pre>
<p><strong>… and another interesting one that I thought of</strong>:</p>
<pre><code>filenames = ['file1.txt', 'file2.txt', ...]
with open('path/to/output/file', 'w') as outfile:
for line in itertools.chain.from_iterable(itertools.imap(open, filnames)):
outfile.write(line)
</code></pre>
<p>Sadly, this last method leaves a few open file descriptors, which the GC should take care of anyway. I just thought it was interesting</p> | {
"question_id": 13613336,
"question_date": "2012-11-28T19:54:46.143Z",
"question_score": 216,
"tags": "python|file-io|concatenation",
"answer_id": 13613375,
"answer_date": "2012-11-28T19:57:47.770Z",
"answer_score": 309
} |
Please answer the following Stack Overflow question:
Title: Iterate a list with indexes in Python
<p>I could swear I've seen the function (or method) that takes a list, like this <code>[3, 7, 19]</code> and makes it into iterable list of tuples, like so: <code>[(0,3), (1,7), (2,19)]</code> to use it instead of:</p>
<pre><code>for i in range(len(name_of_list)):
name_of_list[i] = something
</code></pre>
<p>but I can't remember the name and googling "iterate list" gets nothing.</p> | <pre><code>>>> a = [3,4,5,6]
>>> for i, val in enumerate(a):
... print i, val
...
0 3
1 4
2 5
3 6
>>>
</code></pre> | {
"question_id": 126524,
"question_date": "2008-09-24T11:08:52.053Z",
"question_score": 216,
"tags": "python|list",
"answer_id": 126533,
"answer_date": "2008-09-24T11:11:41.173Z",
"answer_score": 384
} |
Please answer the following Stack Overflow question:
Title: Can pandas automatically read dates from a CSV file?
<p>Today I was positively surprised by the fact that while reading data from a data file (for example) pandas is able to recognize types of values:</p>
<pre><code>df = pandas.read_csv('test.dat', delimiter=r"\s+", names=['col1','col2','col3'])
</code></pre>
<p>For example it can be checked in this way:</p>
<pre><code>for i, r in df.iterrows():
print type(r['col1']), type(r['col2']), type(r['col3'])
</code></pre>
<p>In particular integer, floats and strings were recognized correctly. However, I have a column that has dates in the following format: <code>2013-6-4</code>. These dates were recognized as strings (not as python date-objects). Is there a way to "learn" pandas to recognized dates?</p> | <p>You should add <code>parse_dates=True</code>, or <code>parse_dates=['column name']</code> when reading, thats usually enough to magically parse it. But there are always weird formats which need to be defined manually. In such a case you can also add a date parser function, which is the most flexible way possible.</p>
<p>Suppose you have a column 'datetime' with your string, then:</p>
<pre><code>from datetime import datetime
dateparse = lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S')
df = pd.read_csv(infile, parse_dates=['datetime'], date_parser=dateparse)
</code></pre>
<p>This way you can even combine multiple columns into a single datetime column, this merges a 'date' and a 'time' column into a single 'datetime' column:</p>
<pre><code>dateparse = lambda x: datetime.strptime(x, '%Y-%m-%d %H:%M:%S')
df = pd.read_csv(infile, parse_dates={'datetime': ['date', 'time']}, date_parser=dateparse)
</code></pre>
<p>You can find directives (i.e. the letters to be used for different formats) for <code>strptime</code> and <code>strftime</code> <a href="https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior" rel="noreferrer">in this page</a>.</p> | {
"question_id": 17465045,
"question_date": "2013-07-04T08:08:39.807Z",
"question_score": 216,
"tags": "python|date|types|dataframe|pandas",
"answer_id": 17468012,
"answer_date": "2013-07-04T10:32:01.837Z",
"answer_score": 436
} |
Please answer the following Stack Overflow question:
Title: How do you add CSS with Javascript?
<p>How do you add CSS rules (eg <code>strong { color: red }</code>) by use of Javascript?</p> | <p>You can also do this using DOM Level 2 CSS interfaces (<a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/styleSheets" rel="noreferrer">MDN</a>):</p>
<pre><code>var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);
</code></pre>
<p>...on all but (naturally) IE8 and prior, which uses its own marginally-different wording:</p>
<pre><code>sheet.addRule('strong', 'color: red;', -1);
</code></pre>
<p>There is a theoretical advantage in this compared to the createElement-set-innerHTML method, in that you don't have to worry about putting special HTML characters in the innerHTML, but in practice style elements are CDATA in legacy HTML, and ‘<’ and ‘&’ are rarely used in stylesheets anyway.</p>
<p>You do need a stylesheet in place before you can started appending to it like this. That can be any existing active stylesheet: external, embedded or empty, it doesn't matter. If there isn't one, the only standard way to create it at the moment is with createElement.</p> | {
"question_id": 707565,
"question_date": "2009-04-01T22:19:10.817Z",
"question_score": 216,
"tags": "javascript|css",
"answer_id": 707794,
"answer_date": "2009-04-01T23:57:21.423Z",
"answer_score": 151
} |
Please answer the following Stack Overflow question:
Title: Pandas read_csv from url
<p>I'm trying to read a csv-file from given URL, using Python 3.x:</p>
<pre><code>import pandas as pd
import requests
url = "https://github.com/cs109/2014_data/blob/master/countries.csv"
s = requests.get(url).content
c = pd.read_csv(s)
</code></pre>
<p>I have the following error</p>
<blockquote>
<p>"Expected file path name or file-like object, got <class 'bytes'> type"</p>
</blockquote>
<p>How can I fix this? I'm using Python 3.4</p> | <p>UPDATE: From pandas <code>0.19.2</code> you can now just <a href="https://stackoverflow.com/a/41880513/2071807"><strong>pass <code>read_csv()</code> the url directly</strong></a>, although that will fail if it requires authentication.</p>
<hr />
<p>For <strong>older pandas versions</strong>, or <strong>if you need authentication</strong>, or for any other HTTP-fault-tolerant reason:</p>
<p><strong>Use <code>pandas.read_csv</code> with a file-like object as the first argument.</strong></p>
<ul>
<li><p>If you want to read the csv from a string, you can use <a href="https://docs.python.org/3/library/io.html#io.StringIO" rel="noreferrer"><code>io.StringIO</code></a>.</p>
</li>
<li><p>For the URL <code>https://github.com/cs109/2014_data/blob/master/countries.csv</code>, you get <strong><code>html</code></strong> response, not <strong>raw</strong> csv; you should use the url given by the <code>Raw</code> link in the github page for getting raw csv response , which is <code>https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv</code></p>
</li>
</ul>
<p>Example:</p>
<pre><code>import pandas as pd
import io
import requests
url="https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv"
s=requests.get(url).content
c=pd.read_csv(io.StringIO(s.decode('utf-8')))
</code></pre>
<p>Notes:</p>
<p>in Python 2.x, the string-buffer object was <a href="https://docs.python.org/2/library/stringio.html#StringIO.StringIO" rel="noreferrer"><code>StringIO.StringIO</code></a></p> | {
"question_id": 32400867,
"question_date": "2015-09-04T14:44:24.740Z",
"question_score": 216,
"tags": "python|csv|pandas|request",
"answer_id": 32400969,
"answer_date": "2015-09-04T14:50:24.840Z",
"answer_score": 242
} |
Please answer the following Stack Overflow question:
Title: Changing the width of Bootstrap popover
<p>I am designing a page using Bootstrap 3. I am trying to use a popover with <code>placement: right</code> on an input element. The new Bootstrap ensures that if you use <code>form-control</code> you basically have a full-width input element.</p>
<p>The HTML code looks something like this: </p>
<pre><code><div class="row">
<div class="col-md-6">
<label for="name">Name:</label>
<input id="name" class="form-control" type="text"
data-toggle="popover" data-trigger="hover"
data-content="My popover content.My popover content.My popover content.My popover content." />
</div>
</div>
</code></pre>
<p>The popovers width is too low, in my opinion because their isn't any width left in the div.
I want the input form on the left side, and a wide popover on the right side.</p>
<p>Mostly, I'm looking for a solution where I don't have to override Bootstrap. </p>
<p>The attached JsFiddle. The second input option. Haven't used jsfiddle a lot so don't know, but try increasing the size of the output box to see results, on smaller screens wouldn't even see it.
<a href="http://jsfiddle.net/Rqx8T/" rel="noreferrer">http://jsfiddle.net/Rqx8T/</a></p> | <pre><code><div class="row" data-toggle="popover" data-trigger="hover"
data-content="My popover content.My popover content.My popover content.My popover content.">
<div class="col-md-6">
<label for="name">Name:</label>
<input id="name" class="form-control" type="text" />
</div>
</div>
</code></pre>
<p>Basically i put the popover code in the row div, instead of the input div. Solved the problem.</p> | {
"question_id": 19448902,
"question_date": "2013-10-18T11:46:17.187Z",
"question_score": 216,
"tags": "css|twitter-bootstrap|twitter-bootstrap-3|popover",
"answer_id": 19604395,
"answer_date": "2013-10-26T08:00:43.637Z",
"answer_score": 6
} |
Please answer the following Stack Overflow question:
Title: How to reference a .css file on a razor view?
<p>I know how to set .css files on the _Layout.cshtml file, but what about applying a stylesheet on a per-view basis?</p>
<p>My thinking here is that, in _Layout.cshtml, you have <code><head></code> tags to work with, but not so in one of your non-layout views. Where do the <code><link></code> tags go?</p> | <p>For CSS that are reused among the entire site I define them in the <code><head></code> section of the <code>_Layout</code>:</p>
<pre><code><head>
<link href="@Url.Content("~/Styles/main.css")" rel="stylesheet" type="text/css" />
@RenderSection("Styles", false)
</head>
</code></pre>
<p>and if I need some view specific styles I define the <code>Styles</code> section in each view:</p>
<pre><code>@section Styles {
<link href="@Url.Content("~/Styles/view_specific_style.css")" rel="stylesheet" type="text/css" />
}
</code></pre>
<p>Edit: It's useful to know that the second parameter in @RenderSection, false, means that the section is not required on a view that uses this master page, and the view engine will blissfully ignore the fact that there is no "Styles" section defined in your view. If true, the view won't render and an error will be thrown unless the "Styles" section has been defined.</p> | {
"question_id": 5021552,
"question_date": "2011-02-16T20:08:42.347Z",
"question_score": 216,
"tags": "css|asp.net-mvc|razor",
"answer_id": 5021680,
"answer_date": "2011-02-16T20:21:20.433Z",
"answer_score": 378
} |
Please answer the following Stack Overflow question:
Title: How to force a component's re-rendering in Angular 2?
<p>How to force a component's re-rendering in Angular 2?
For debug purposes working with Redux i'd like to force a component to re-render it's view, is that possible?</p> | <p>Rendering happens after change detection. To force change detection, so that component property values that have changed get propagated to the DOM (and then the browser will render those changes in the view), here are some options:</p>
<ul>
<li><a href="https://angular.io/api/core/ApplicationRef#tick" rel="noreferrer">ApplicationRef.tick()</a> - similar to Angular 1's <code>$rootScope.$digest()</code> -- i.e., check the full component tree</li>
<li><a href="https://angular.io/api/core/NgZone#run" rel="noreferrer">NgZone.run(callback)</a> - similar to <code>$rootScope.$apply(callback)</code> -- i.e., evaluate the callback function inside the Angular 2 zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.</li>
<li><a href="https://angular.io/api/core/ChangeDetectorRef#detectChanges" rel="noreferrer">ChangeDetectorRef.detectChanges()</a> - similar to <code>$scope.$digest()</code> -- i.e., check only this component and its children</li>
</ul>
<p>You will need to import and then inject <code>ApplicationRef</code>, <code>NgZone</code>, or <code>ChangeDetectorRef</code> into your component.</p>
<p>For your particular scenario, I would recommend the last option if only a single component has changed.</p> | {
"question_id": 35105374,
"question_date": "2016-01-30T18:22:44.653Z",
"question_score": 216,
"tags": "angular|angular2-changedetection",
"answer_id": 35106069,
"answer_date": "2016-01-30T19:25:14.623Z",
"answer_score": 249
} |
Please answer the following Stack Overflow question:
Title: Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes
<p>What exactly are <code>process</code> and <code>update</code> in PrimeFaces <code>p:commandXxx</code> components and <code>execute</code> and <code>render</code> in <code>f:ajax</code> tag?</p>
<p>Which works at the time of validation? What does <code>update</code> attribute do rather than updating value to component from back end? Do <code>process</code> attribute bind value to model? What exactly do <code>@this</code>, <code>@parent</code>, <code>@all</code> and <code>@form</code> in both attributes?</p>
<p>The example below is working fine, but I am a little confused in basic concepts.</p>
<pre class="lang-html prettyprint-override"><code><p:commandButton process="@parent"
update="@form"
action="#{bean.submit}"
value="Submit" />
</code></pre> | <h2><code><p:commandXxx process></code> <code><p:ajax process></code> <code><f:ajax execute></code></h2>
<p>The <code>process</code> attribute is server side and can only affect <a href="http://docs.oracle.com/javaee/7/api/javax/faces/component/UIComponent.html" rel="noreferrer"><code>UIComponent</code></a>s implementing <a href="http://docs.oracle.com/javaee/7/api/javax/faces/component/EditableValueHolder.html" rel="noreferrer"><code>EditableValueHolder</code></a> (input fields) or <a href="http://docs.oracle.com/javaee/7/api/javax/faces/component/ActionSource.html" rel="noreferrer"><code>ActionSource</code></a> (command fields). The <code>process</code> attribute tells JSF, using a space-separated list of client IDs, which components exactly must be processed through the entire JSF lifecycle upon (partial) form submit.</p>
<p>JSF will then apply the request values (finding HTTP request parameter based on component's own client ID and then either setting it as submitted value in case of <code>EditableValueHolder</code> components or queueing a new <a href="http://docs.oracle.com/javaee/7/api/javax/faces/event/ActionEvent.html" rel="noreferrer"><code>ActionEvent</code></a> in case of <code>ActionSource</code> components), perform conversion, validation and updating the model values (<code>EditableValueHolder</code> components only) and finally invoke the queued <code>ActionEvent</code> (<code>ActionSource</code> components only). JSF will skip processing of all other components which are not covered by <code>process</code> attribute. Also, components whose <code>rendered</code> attribute evaluates to <code>false</code> during apply request values phase will also be skipped as part of safeguard against tampered requests.</p>
<p>Note that it's in case of <code>ActionSource</code> components (such as <code><p:commandButton></code>) very important that you also include the component itself in the <code>process</code> attribute, particularly if you intend to invoke the action associated with the component. So the below example which intends to process only certain input component(s) when a certain command component is invoked ain't gonna work:</p>
<pre><code><p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="foo" action="#{bean.action}" />
</code></pre>
<p>It would only process the <code>#{bean.foo}</code> and <strong>not</strong> the <code>#{bean.action}</code>. You'd need to include the command component itself as well:</p>
<pre><code><p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="@this foo" action="#{bean.action}" />
</code></pre>
<p>Or, as you apparently found out, using <code>@parent</code> if they happen to be the only components having a common parent:</p>
<pre><code><p:panel><!-- Type doesn't matter, as long as it's a common parent. -->
<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="@parent" action="#{bean.action}" />
</p:panel>
</code></pre>
<p>Or, if they both happen to be the only components of the parent <a href="http://docs.oracle.com/javaee/7/api/javax/faces/component/UIForm.html" rel="noreferrer"><code>UIForm</code></a> component, then you can also use <code>@form</code>:</p>
<pre><code><h:form>
<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="@form" action="#{bean.action}" />
</h:form>
</code></pre>
<p>This is sometimes undesirable if the form contains more input components which you'd like to skip in processing, more than often in cases when you'd like to update another input component(s) or some UI section based on the current input component in an ajax listener method. You namely don't want that validation errors on other input components are preventing the ajax listener method from being executed.</p>
<p>Then there's the <code>@all</code>. This has no special effect in <code>process</code> attribute, but only in <code>update</code> attribute. A <code>process="@all"</code> behaves exactly the same as <code>process="@form"</code>. HTML doesn't support submitting multiple forms at once anyway.</p>
<p>There's by the way also a <code>@none</code> which may be useful in case you absolutely don't need to process anything, but <em>only</em> want to update some specific parts via <code>update</code>, particularly those sections whose content doesn't depend on submitted values or action listeners.</p>
<p>Noted should be that the <code>process</code> attribute has <strong>no</strong> influence on the HTTP request payload (the amount of request parameters). Meaning, the default HTML behavior of sending "everything" contained within the HTML representation of the <code><h:form></code> will be not be affected. In case you have a large form, and want to reduce the HTTP request payload to only these absolutely necessary in processing, i.e. only these covered by <code>process</code> attribute, then you can set the <code>partialSubmit</code> attribute in PrimeFaces Ajax components as in <code><p:commandXxx ... partialSubmit="true"></code> or <code><p:ajax ... partialSubmit="true"></code>. You can also configure this 'globally' by editing <code>web.xml</code> and add</p>
<pre><code><context-param>
<param-name>primefaces.SUBMIT</param-name>
<param-value>partial</param-value>
</context-param>
</code></pre>
<p>Alternatively, you can also use <a href="http://showcase.omnifaces.org/components/form" rel="noreferrer"><code><o:form></code></a> of OmniFaces 3.0+ which defaults to this behavior.</p>
<p>The standard JSF equivalent to the PrimeFaces specific <code>process</code> is <code>execute</code> from <code><f:ajax execute></code>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the <code>@parent</code> keyword. Also, it may be useful to know that <code><p:commandXxx process></code> defaults to <code>@form</code> while <code><p:ajax process></code> and <code><f:ajax execute></code> defaults to <code>@this</code>. Finally, it's also useful to know that <code>process</code> supports the so-called "PrimeFaces Selectors", see also <a href="https://stackoverflow.com/questions/20080861/how-do-primefaces-selectors-as-in-update-myclass-work">How do PrimeFaces Selectors as in update="@(.myClass)" work?</a></p>
<hr />
<h2><code><p:commandXxx update></code> <code><p:ajax update></code> <code><f:ajax render></code></h2>
<p>The <code>update</code> attribute is client side and can affect the HTML representation of all <code>UIComponent</code>s. The <code>update</code> attribute tells JavaScript (the one responsible for handling the ajax request/response), using a space-separated list of client IDs, which parts in the HTML DOM tree need to be updated as response to the form submit.</p>
<p>JSF will then prepare the right ajax response for that, containing <em>only</em> the requested parts to update. JSF will skip all other components which are not covered by <code>update</code> attribute in the ajax response, hereby keeping the response payload small. Also, components whose <code>rendered</code> attribute evaluates to <code>false</code> during render response phase will be skipped. Note that even though it would return <code>true</code>, JavaScript cannot update it in the HTML DOM tree if it was initially <code>false</code>. You'd need to wrap it or update its parent instead. See also <a href="https://stackoverflow.com/questions/14790014">Ajax update/render does not work on a component which has rendered attribute</a>.</p>
<p>Usually, you'd like to update <em>only</em> the components which <em>really</em> need to be "refreshed" in the client side upon (partial) form submit. The example below updates the entire parent form via <code>@form</code>:</p>
<pre><code><h:form>
<p:inputText id="foo" value="#{bean.foo}" required="true" />
<p:message id="foo_m" for="foo" />
<p:inputText id="bar" value="#{bean.bar}" required="true" />
<p:message id="bar_m" for="bar" />
<p:commandButton action="#{bean.action}" update="@form" />
</h:form>
</code></pre>
<p><em>(note that <code>process</code> attribute is omitted as that defaults to <code>@form</code> already)</em></p>
<p>Whilst that may work fine, the update of input and command components is in this particular example unnecessary. Unless you change the model values <code>foo</code> and <code>bar</code> inside <code>action</code> method (which would in turn be unintuitive in UX perspective), there's no point of updating them. The message components are the only which <em>really</em> need to be updated:</p>
<pre><code><h:form>
<p:inputText id="foo" value="#{bean.foo}" required="true" />
<p:message id="foo_m" for="foo" />
<p:inputText id="bar" value="#{bean.bar}" required="true" />
<p:message id="bar_m" for="bar" />
<p:commandButton action="#{bean.action}" update="foo_m bar_m" />
</h:form>
</code></pre>
<p>However, that gets tedious when you have many of them. That's one of the reasons why PrimeFaces Selectors exist. Those message components have in the generated HTML output a common style class of <code>ui-message</code>, so the following should also do:</p>
<pre><code><h:form>
<p:inputText id="foo" value="#{bean.foo}" required="true" />
<p:message id="foo_m" for="foo" />
<p:inputText id="bar" value="#{bean.bar}" required="true" />
<p:message id="bar_m" for="bar" />
<p:commandButton action="#{bean.action}" update="@(.ui-message)" />
</h:form>
</code></pre>
<p><em>(note that you should keep the IDs on message components, otherwise <code>@(...)</code> won't work! Again, see <a href="https://stackoverflow.com/questions/20080861/how-do-primefaces-selectors-as-in-update-myclass-work">How do PrimeFaces Selectors as in update="@(.myClass)" work?</a> for detail)</em></p>
<p>The <code>@parent</code> updates only the parent component, which thus covers the current component and all siblings and their children. This is more useful if you have separated the form in sane groups with each its own responsibility. The <code>@this</code> updates, obviously, only the current component. Normally, this is only necessary when you need to change one of the component's own HTML attributes in the action method. E.g.</p>
<pre><code><p:commandButton action="#{bean.action}" update="@this"
oncomplete="doSomething('#{bean.value}')" />
</code></pre>
<p>Imagine that the <code>oncomplete</code> needs to work with the <code>value</code> which is changed in <code>action</code>, then this construct wouldn't have worked if the component isn't updated, for the simple reason that <code>oncomplete</code> is part of generated HTML output (and thus all EL expressions in there are evaluated during render response).</p>
<p>The <code>@all</code> updates the entire document, which should be used with care. Normally, you'd like to use a true GET request for this instead by either a plain link (<code><a></code> or <code><h:link></code>) or a redirect-after-POST by <code>?faces-redirect=true</code> or <code>ExternalContext#redirect()</code>. In effects, <code>process="@form" update="@all"</code> has exactly the same effect as a non-ajax (non-partial) submit. In my entire JSF career, the only sensible use case I encountered for <code>@all</code> is to display an error page in its entirety in case an exception occurs during an ajax request. See also <a href="https://stackoverflow.com/questions/10449862/what-is-the-correct-way-to-deal-with-jsf-2-0-exceptions-for-ajaxified-components/">What is the correct way to deal with JSF 2.0 exceptions for AJAXified components?</a></p>
<p>The standard JSF equivalent to the PrimeFaces specific <code>update</code> is <code>render</code> from <code><f:ajax render></code>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the <code>@parent</code> keyword. Both <code>update</code> and <code>render</code> defaults to <code>@none</code> (which is, "nothing").</p>
<hr />
<p><strong>See also:</strong></p>
<ul>
<li><a href="https://stackoverflow.com/questions/8634156">How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"</a></li>
<li><a href="https://stackoverflow.com/questions/20146630">Execution order of events when pressing PrimeFaces p:commandButton</a></li>
<li><a href="https://stackoverflow.com/questions/30934671">How to decrease request payload of p:ajax during e.g. p:dataTable pagination</a></li>
<li><a href="https://stackoverflow.com/questions/28236228">How to show details of current row from p:dataTable in a p:dialog and update after save</a></li>
<li><a href="https://stackoverflow.com/questions/7371903">How to use <h:form> in JSF page? Single form? Multiple forms? Nested forms?</a></li>
</ul> | {
"question_id": 25339056,
"question_date": "2014-08-16T10:02:07.933Z",
"question_score": 216,
"tags": "jsf|primefaces|process|updates",
"answer_id": 25347186,
"answer_date": "2014-08-17T07:33:07.020Z",
"answer_score": 336
} |
Please answer the following Stack Overflow question:
Title: Add line break within tooltips
<p>How can line breaks be added within a HTML tooltip?</p>
<p>I tried using <code><br/></code> and <code>\n</code> within the tooltip as follows: </p>
<pre><code><a href="#" title="Some long text <br/> Second line text \n Third line text">Hover me</a>
</code></pre>
<p>However, this was useless and I could see the literal text <code><br/></code> and <code>\n</code> within the tooltip. Any suggestions will be helpful.</p> | <p>Just use the entity code <code>&#013;</code> for a linebreak in a title attribute.</p> | {
"question_id": 3340802,
"question_date": "2010-07-27T04:44:28.163Z",
"question_score": 216,
"tags": "html|tooltip|newline",
"answer_id": 9118551,
"answer_date": "2012-02-02T19:20:41.390Z",
"answer_score": 327
} |
Please answer the following Stack Overflow question:
Title: Why aren't programs written in Assembly more often?
<p>It seems to be a mainstream opinion that assembly programming takes longer and is more difficult to program in than a higher level language such as C. Therefore it seems to be recommend or assumed that it is better to write in a higher level language for these reasons and for the reason of better portability.</p>
<p>Recently I've been writing in x86 assembly and it has dawned on me that perhaps these reasons are not really true, except perhaps portability. Perhaps it is more of a matter of familiarity and knowing how to write assembly well. I also noticed that programming in assembly is quite different than programming in an HLL. Perhaps a good and experienced assembly programmer could write programs just as easily and as quickly as an experienced C programmer writing in C.</p>
<p>Perhaps it is because assembly programming is quite different than HLLs, and so requires different thinking, methods and ways, which makes it seem very awkward to program in for the unfamiliar, and so gives it its bad name for writing programs in.</p>
<p>If portability isn't an issue, then really, what would C have over a good assembler such as NASM?</p>
<p><b>Edit:</b>
Just to point out. When you are writing in assembly, you don't have to write just in instruction codes. You can use macros and procedures and your own conventions to make various abstractions to make programs more modular, more maintainable and easier to read. This is where being familiar with how to write good assembly comes in.</p> | <p>ASM has <strong>poor legibility</strong> and <strong>isn't really maintainable</strong> compared to higher-level languages.</p>
<p>Also, there are many <strong>fewer ASM developers</strong> than for other more popular languages, such as C.</p>
<p>Furthermore, if you use a higher-level language and <strong>new ASM instructions become available</strong> (SSE for example), you just need to update your compiler and your old code can easily make use of the new instructions.</p>
<p>What if the next CPU has twice as many registers?</p>
<p>The converse of this question would be: <em>What functionality do compilers provide?</em></p>
<p>I doubt you can/want to/should optimize your ASM better than <code>gcc -O3</code> can.</p> | {
"question_id": 2684364,
"question_date": "2010-04-21T15:39:17.487Z",
"question_score": 216,
"tags": "c|programming-languages|assembly",
"answer_id": 2684384,
"answer_date": "2010-04-21T15:41:10.150Z",
"answer_score": 331
} |
Please answer the following Stack Overflow question:
Title: How to switch between hide and view password
<p>Is there a clever way to let the user switch between hide and view password in an android EditText?
A number of PC based apps let the user do this.</p> | <p>You can dynamically change the attributes of a TextView. If you would set the XML Atrribute <code>android:password</code> to true the view would show dots if you set it to false the text is shown. </p>
<p>With the method <a href="http://developer.android.com/reference/android/widget/TextView.html#setTransformationMethod%28android.text.method.TransformationMethod%29" rel="noreferrer">setTransformationMethod</a> you should be able to change this attributes from code. (Disclaimer: I have not tested if the method still works after the view is displayed. If you encounter problems with that leave me a comment for me to know.) </p>
<p>The full sample code would be </p>
<pre><code>yourTextView.setTransformationMethod(new PasswordTransformationMethod());
</code></pre>
<p>to hide the password. To show the password you could set one of the existing transformation methods or implement an empty <a href="http://developer.android.com/reference/android/text/method/TransformationMethod.html" rel="noreferrer">TransformationMethod</a> that does nothing with the input text.</p>
<pre><code>yourTextView.setTransformationMethod(new DoNothingTransformation());
</code></pre> | {
"question_id": 3685790,
"question_date": "2010-09-10T15:11:25.843Z",
"question_score": 216,
"tags": "android|passwords",
"answer_id": 3685867,
"answer_date": "2010-09-10T15:19:56.060Z",
"answer_score": 182
} |
Please answer the following Stack Overflow question:
Title: CSS for grabbing cursors (drag & drop)
<p>I have a JavaScript webapp where the user needs to grab the background to move the whole screen around. So I want the cursor to change when they're hovering over the background. The <code>-moz-grab</code> and <code>-moz-grabbing</code> CSS cursors are ideal for this. Of course, they only work in Firefox... are there equivalent cursors for other browsers? Do I have to do something a little more custom than standard CSS cursors?</p> | <p>I think <code>move</code> would probably be the closest <a href="http://www.w3.org/TR/CSS21/ui.html#propdef-cursor" rel="noreferrer">standard cursor value</a> for what you're doing:</p>
<blockquote>
<p><strong>move</strong><br>
Indicates something is to be moved.</p>
</blockquote> | {
"question_id": 5697067,
"question_date": "2011-04-17T23:02:31.387Z",
"question_score": 216,
"tags": "css|mouse-cursor",
"answer_id": 5697103,
"answer_date": "2011-04-17T23:12:29.943Z",
"answer_score": 133
} |
Please answer the following Stack Overflow question:
Title: CSS @media print issues with background-color;
<p>I'm new here at this company and we have a product that uses miles of css. I'm attempting to make a printable stylesheet for our app but I'm having issues with <code>background-color</code> in <code>@media print</code>.</p>
<pre class="lang-css prettyprint-override"><code> @media print {
#header{display:none;}
#adwrapper{display:none;}
td {
border-bottom: solid;
border-right: solid;
background-color: #c0c0c0;
}
}
</code></pre>
<p>Everything else works, I can modify the borders and such but <code>background-color</code> won't come through in the print. Now I understand that y'all might not be able to answer my question without more details. I was just curious if anyone had this issue, or something similar, before. </p> | <p>IF a user has "Print Background colours and images" turned off in their print settings, no CSS will override that, so always account for that. <strong>This is a default setting</strong>.</p>
<p>Once that is set so it will print background colours and images, what you have there will work.</p>
<p>It is found in different spots.
In IE9beta it's found in Print->Page Options under Paper options</p>
<p>In FireFox it's in Page Setup -> [Format & Options] Tab under Options.</p> | {
"question_id": 3893986,
"question_date": "2010-10-08T20:13:55.737Z",
"question_score": 216,
"tags": "css|media-queries",
"answer_id": 3894013,
"answer_date": "2010-10-08T20:17:56.927Z",
"answer_score": 269
} |
Please answer the following Stack Overflow question:
Title: How do I install a module globally using npm?
<p>I recently installed Node.js and npm module on OSX and have a problem with the settings I think:</p>
<pre><code>npm install [MODULE] is not installing the node.js module to the default path
which is /usr/local/lib/node_modules.
</code></pre> | <p>If you want to install a npm module globally, make sure to use the new <code>-g</code> flag, for example:</p>
<p><code>npm install forever -g</code></p>
<p>The general recommendations concerning npm module installation since 1.0rc (taken from <a href="http://blog.nodejs.org/2011/03/23/npm-1-0-global-vs-local-installation/">blog.nodejs.org</a>):</p>
<blockquote>
<ul>
<li>If you’re installing something that you want to use in your program, using
require('whatever'), then <strong>install it
locally</strong>, at the root of your
project.</li>
<li>If you’re installing something that you want to use in your shell, on the
command line or something, <strong>install
it globally</strong>, so that its binaries
end up in your PATH environment
variable.</li>
</ul>
</blockquote>
<p>I just recently used this recommendations and it went down pretty smoothly. I installed forever globally (since it is a command line tool) and all my application modules locally.</p>
<p>However, if you want to use some modules globally (i.e. express or mongodb), take this advice (also taken from <a href="http://blog.nodejs.org/2011/03/23/npm-1-0-global-vs-local-installation/">blog.nodejs.org</a>):</p>
<blockquote>
<p>Of course, there are some cases where
you want to do both. Coffee-script and
Express both are good examples of apps
that have a command line interface, as
well as a library. In those cases, you
can do one of the following:</p>
<ul>
<li><strong>Install it in both places</strong>. Seriously, are you that short on disk
space? It’s fine, really. They’re tiny
JavaScript programs.</li>
<li><strong>Install it globally, and then npm link coffee-script or npm link express</strong>
(if you’re on a platform that supports
symbolic links.) Then you only need to
update the global copy to update all
the symlinks as well.</li>
</ul>
<p>The first option is the best in my
opinion. Simple, clear, explicit. The
second is really handy if you are
going to re-use the same library in a
bunch of different projects. (More on
npm link in a future installment.)</p>
</blockquote>
<p>I did not test one of those variations, but they seem to be pretty straightforward.</p> | {
"question_id": 5817874,
"question_date": "2011-04-28T11:30:05.223Z",
"question_score": 216,
"tags": "node.js|npm",
"answer_id": 5830153,
"answer_date": "2011-04-29T09:07:35.427Z",
"answer_score": 375
} |
Please answer the following Stack Overflow question:
Title: How to test if a string contains one of the substrings in a list, in pandas?
<p>Is there any function that would be the equivalent of a combination of <code>df.isin()</code> and <code>df[col].str.contains()</code>? </p>
<p>For example, say I have the series
<code>s = pd.Series(['cat','hat','dog','fog','pet'])</code>, and I want to find all places where <code>s</code> contains any of <code>['og', 'at']</code>, I would want to get everything but 'pet'.</p>
<p>I have a solution, but it's rather inelegant:</p>
<pre><code>searchfor = ['og', 'at']
found = [s.str.contains(x) for x in searchfor]
result = pd.DataFrame[found]
result.any()
</code></pre>
<p>Is there a better way to do this?</p> | <p>One option is just to use the regex <code>|</code> character to try to match each of the substrings in the words in your Series <code>s</code> (still using <code>str.contains</code>). </p>
<p>You can construct the regex by joining the words in <code>searchfor</code> with <code>|</code>:</p>
<pre><code>>>> searchfor = ['og', 'at']
>>> s[s.str.contains('|'.join(searchfor))]
0 cat
1 hat
2 dog
3 fog
dtype: object
</code></pre>
<p>As @AndyHayden noted in the comments below, take care if your substrings have special characters such as <code>$</code> and <code>^</code> which you want to match literally. These characters have specific meanings in the context of regular expressions and will affect the matching.</p>
<p>You can make your list of substrings safer by escaping non-alphanumeric characters with <code>re.escape</code>:</p>
<pre><code>>>> import re
>>> matches = ['$money', 'x^y']
>>> safe_matches = [re.escape(m) for m in matches]
>>> safe_matches
['\\$money', 'x\\^y']
</code></pre>
<p>The strings with in this new list will match each character literally when used with <code>str.contains</code>.</p> | {
"question_id": 26577516,
"question_date": "2014-10-26T20:23:37.160Z",
"question_score": 216,
"tags": "python|string|pandas|dataframe|match",
"answer_id": 26577689,
"answer_date": "2014-10-26T20:40:33.717Z",
"answer_score": 375
} |
Please answer the following Stack Overflow question:
Title: Using NotNull Annotation in method argument
<p>I just started using the <code>@NotNull</code> annotation with Java 8 and getting some unexpected results.</p>
<p>I have a method like this:</p>
<pre><code>public List<Found> findStuff(@NotNull List<Searching> searchingList) {
... code here ...
}
</code></pre>
<p>I wrote a JUnit test passing in the null value for the argument searchingList. I was expecting some type of error to happen but it went through as though the annotation was not there. Is this expected behavior? From what I understood, this was to allow you to skip writing the boilerplate null check code.</p>
<p>An explanation of what exactly @NotNull is supposed to do would be greatly appreciated.</p> | <p><strong><code>@Nullable</code> and <code>@NotNull</code> do nothing on their own. They are supposed to act as Documentation tools.</strong></p>
<p>The <code>@Nullable</code> Annotation reminds you about the necessity to introduce an NPE check when:</p>
<ol>
<li>Calling methods that can return null.</li>
<li>Dereferencing variables (fields, local variables, parameters) that can be null.</li>
</ol>
<p>The <code>@NotNull</code> Annotation is, actually, an explicit contract declaring the following:</p>
<ol>
<li>A method should not return null.</li>
<li>A variable (like fields, local variables, and parameters) <s>cannot</s> <i>should not</i> hold null value. </li>
</ol>
<p>For example, instead of writing:</p>
<pre><code>/**
* @param aX should not be null
*/
public void setX(final Object aX ) {
// some code
}
</code></pre>
<p>You can use:</p>
<pre><code>public void setX(@NotNull final Object aX ) {
// some code
}
</code></pre>
<p>Additionally, <code>@NotNull</code> is often checked by <a href="https://docs.oracle.com/javaee/7/api/javax/validation/ConstraintValidator.html" rel="noreferrer">ConstraintValidators</a> (eg. in spring and hibernate). </p>
<p>The <code>@NotNull</code> annotation doesn't do any validation on its own because the <a href="https://docs.oracle.com/javaee/7/api/javax/validation/constraints/NotNull.html" rel="noreferrer">annotation definition</a> does not provide any <code>ConstraintValidator</code> type reference.</p>
<p>For more info see: </p>
<ol>
<li><a href="https://beanvalidation.org/2.0/" rel="noreferrer">Bean validation</a></li>
<li><a href="https://docs.oracle.com/javaee/7/api/javax/validation/constraints/NotNull.html" rel="noreferrer">NotNull.java</a></li>
<li><a href="https://docs.oracle.com/javaee/7/api/javax/validation/Constraint.html" rel="noreferrer">Constraint.java</a></li>
<li><a href="https://docs.oracle.com/javaee/7/api/javax/validation/ConstraintValidator.html" rel="noreferrer">ConstraintValidator.java</a></li>
</ol> | {
"question_id": 34094039,
"question_date": "2015-12-04T17:26:04.043Z",
"question_score": 216,
"tags": "java",
"answer_id": 34094352,
"answer_date": "2015-12-04T17:46:05.787Z",
"answer_score": 261
} |
Please answer the following Stack Overflow question:
Title: How do I purge a linux mail box with huge number of emails?
<p>I have setup some cron jobs and they send the crons result to an email. Now over the months I have accumulated a huge number of emails.</p>
<p>Now my question is how can I purge all those emails from my mailbox?</p> | <p>You can simply delete the <code>/var/mail/username</code> file to delete all emails for a specific user. Also, emails that are outgoing but have not yet been sent will be stored in <code>/var/spool/mqueue</code>.</p> | {
"question_id": 7076186,
"question_date": "2011-08-16T09:33:53.847Z",
"question_score": 216,
"tags": "email|purge",
"answer_id": 7076239,
"answer_date": "2011-08-16T09:38:22.553Z",
"answer_score": 174
} |
Please answer the following Stack Overflow question:
Title: Java Set retain order?
<p>Does a Java Set retain order? A method is returning a Set to me and supposedly the data is ordered but iterating over the Set, the data is unordered. Is there a better way to manage this? Does the method need to be changed to return something other than a Set?</p> | <p>The <a href="http://docs.oracle.com/javase/6/docs/api/java/util/Set.html" rel="noreferrer"><code>Set</code></a> interface does not provide any ordering guarantees.</p>
<p>Its sub-interface <a href="http://docs.oracle.com/javase/6/docs/api/java/util/SortedSet.html" rel="noreferrer"><code>SortedSet</code></a> represents a set that is sorted according to some criterion. In Java 6, there are two standard containers that implement <code>SortedSet</code>. They are <a href="http://docs.oracle.com/javase/6/docs/api/java/util/TreeSet.html" rel="noreferrer"><code>TreeSet</code></a> and <a href="http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ConcurrentSkipListSet.html" rel="noreferrer"><code>ConcurrentSkipListSet</code></a>.</p>
<p>In addition to the <code>SortedSet</code> interface, there is also the <a href="http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html" rel="noreferrer"><code>LinkedHashSet</code></a> class. It remembers the order in which the elements were inserted into the set, and returns its elements in that order.</p> | {
"question_id": 10752753,
"question_date": "2012-05-25T10:27:01.990Z",
"question_score": 216,
"tags": "java|sorting|set",
"answer_id": 10752804,
"answer_date": "2012-05-25T10:30:12.337Z",
"answer_score": 315
} |
Please answer the following Stack Overflow question:
Title: How to access a dictionary element in a Django template?
<p>I would like to print out the number of votes that each choice got. I have this code in a template: </p>
<pre><code>{% for choice in choices %}
{{choice.choice}} - {{votes[choice.id]}} <br />
{% endfor %}
</code></pre>
<p><code>votes</code> is just a dictionary while <code>choices</code> is a model object.</p>
<p>It raises an exception with this message:</p>
<pre class="lang-none prettyprint-override"><code>"Could not parse the remainder"
</code></pre> | <p>To echo / extend upon Jeff's comment, what I think you should aim for is simply a property in your Choice class that calculates the number of votes associated with that object:</p>
<pre><code>class Choice(models.Model):
text = models.CharField(max_length=200)
def calculateVotes(self):
return Vote.objects.filter(choice=self).count()
votes = property(calculateVotes)
</code></pre>
<p>And then in your template, you can do:</p>
<pre><code>{% for choice in choices %}
{{choice.choice}} - {{choice.votes}} <br />
{% endfor %}
</code></pre>
<p>The template tag, is IMHO a bit overkill for this solution, but it's not a terrible solution either. The goal of templates in Django is to insulate you from code in your templates and vice-versa.</p>
<p>I'd try the above method and see what SQL the ORM generates as I'm not sure off the top of my head if it will pre-cache the properties and just create a subselect for the property or if it will iteratively / on-demand run the query to calculate vote count. But if it generates atrocious queries, you could always populate the property in your view with data you've collected yourself.</p> | {
"question_id": 1275735,
"question_date": "2009-08-14T02:24:58.657Z",
"question_score": 216,
"tags": "python|django|django-templates",
"answer_id": 1275999,
"answer_date": "2009-08-14T04:07:47.573Z",
"answer_score": 67
} |
Please answer the following Stack Overflow question:
Title: Mac SQLite editor
<p>I am aware of <a href="http://cocoamysql.sourceforge.net/" rel="noreferrer">CocoaMySQL</a> but I have not seen a Mac GUI for SQLite, is there one?</p>
<p>My Google search didn't turn up any Mac related GUI's which is why I'm asking here rather than Google.</p> | <p><a href="https://addons.mozilla.org/en-US/firefox/addon/5817" rel="noreferrer">SQLite Manager for FireFox</a></p> | {
"question_id": 100959,
"question_date": "2008-09-19T10:24:18.450Z",
"question_score": 216,
"tags": "macos|user-interface|sqlite",
"answer_id": 100986,
"answer_date": "2008-09-19T10:30:56.703Z",
"answer_score": 108
} |
Please answer the following Stack Overflow question:
Title: Getting list of lists into pandas DataFrame
<p>I am reading contents of a spreadsheet into pandas. DataNitro has a method that returns a rectangular selection of cells as a list of lists. So</p>
<pre><code>table = Cell("A1").table
</code></pre>
<p>gives</p>
<pre><code>table = [['Heading1', 'Heading2'], [1 , 2], [3, 4]]
headers = table.pop(0) # gives the headers as list and leaves data
</code></pre>
<p>I am busy writing code to translate this, but my guess is that it is such a simple use that there must be method to do this. Cant seem to find it in documentation. Any pointers to the method that would simplify this?</p> | <p>Call the <code>pd.DataFrame</code> constructor directly:</p>
<pre><code>df = pd.DataFrame(table, columns=headers)
df
Heading1 Heading2
0 1 2
1 3 4
</code></pre> | {
"question_id": 19112398,
"question_date": "2013-10-01T09:19:40.023Z",
"question_score": 216,
"tags": "python|pandas|datanitro",
"answer_id": 19112890,
"answer_date": "2013-10-01T09:41:12.887Z",
"answer_score": 314
} |
Please answer the following Stack Overflow question:
Title: Relative frequencies / proportions with dplyr
<p>Suppose I want to calculate the proportion of different values within each group. For example, using the <code>mtcars</code> data, how do I calculate the <em>relative</em> frequency of number of <strong>gears</strong> by <strong>am</strong> (automatic/manual) in one go with <code>dplyr</code>?</p>
<pre><code>library(dplyr)
data(mtcars)
mtcars <- tbl_df(mtcars)
# count frequency
mtcars %>%
group_by(am, gear) %>%
summarise(n = n())
# am gear n
# 0 3 15
# 0 4 4
# 1 4 8
# 1 5 5
</code></pre>
<p>What I would like to achieve:</p>
<pre><code>am gear n rel.freq
0 3 15 0.7894737
0 4 4 0.2105263
1 4 8 0.6153846
1 5 5 0.3846154
</code></pre> | <p>Try this:</p>
<pre><code>mtcars %>%
group_by(am, gear) %>%
summarise(n = n()) %>%
mutate(freq = n / sum(n))
# am gear n freq
# 1 0 3 15 0.7894737
# 2 0 4 4 0.2105263
# 3 1 4 8 0.6153846
# 4 1 5 5 0.3846154
</code></pre>
<p>From the <a href="https://cran.r-project.org/web/packages/dplyr/vignettes/dplyr.html" rel="noreferrer"><strong>dplyr vignette</strong></a>:</p>
<blockquote>
<p>When you group by multiple variables, each summary peels off one level of the grouping. That makes it easy to progressively roll-up a dataset.</p>
</blockquote>
<p>Thus, after the <code>summarise</code>, the last grouping variable specified in <code>group_by</code>, 'gear', is peeled off. In the <code>mutate</code> step, the data is grouped by the remaining grouping variable(s), here 'am'. You may check grouping in each step with <code>groups</code>. </p>
<p>The outcome of the peeling is of course dependent of the order of the grouping variables in the <code>group_by</code> call. You may wish to do a subsequent <code>group_by(am)</code>, to make your code more explicit. </p>
<p>For rounding and prettification, please refer to the nice answer by @Tyler Rinker.</p> | {
"question_id": 24576515,
"question_date": "2014-07-04T14:31:15.420Z",
"question_score": 216,
"tags": "r|group-by|dplyr|frequency",
"answer_id": 24576703,
"answer_date": "2014-07-04T14:42:52.817Z",
"answer_score": 393
} |
Please answer the following Stack Overflow question:
Title: Histogram using gnuplot?
<p>I know how to create a histogram (just use "with boxes") in gnuplot if my .dat file already has properly binned data. Is there a way to take a list of numbers and have gnuplot provide a histogram based on ranges and bin sizes the user provides?</p> | <p>yes, and its quick and simple though very hidden:</p>
<pre><code>binwidth=5
bin(x,width)=width*floor(x/width)
plot 'datafile' using (bin($1,binwidth)):(1.0) smooth freq with boxes</code></pre>
<p>check out <code>help smooth freq</code> to see why the above makes a histogram</p>
<p>to deal with ranges just set the xrange variable.</p> | {
"question_id": 2471884,
"question_date": "2010-03-18T17:10:28.857Z",
"question_score": 216,
"tags": "gnuplot|histogram|binning",
"answer_id": 2538846,
"answer_date": "2010-03-29T14:52:21.310Z",
"answer_score": 239
} |
Please answer the following Stack Overflow question:
Title: Space between Column's children in Flutter
<p>I have a <code>Column</code> widget with two <code>TextField</code> widgets as children and I want to have some space between both of them.</p>
<p>I already tried <code>mainAxisAlignment: MainAxisAlignment.spaceAround</code>, but the result was not what I wanted.</p> | <p>You can use <code>Padding</code> widget in between those two widget or wrap those widgets with <code>Padding</code> widget.</p>
<p><strong>Update</strong></p>
<p><strong><a href="https://api.flutter.dev/flutter/widgets/SizedBox-class.html" rel="noreferrer">SizedBox</a></strong> widget can be use in between two widget to add space between two widget and it makes code more readable than padding widget.</p>
<p>Ex:</p>
<pre><code>Column(
children: <Widget>[
Widget1(),
SizedBox(height: 10),
Widget2(),
],
),
</code></pre> | {
"question_id": 52774921,
"question_date": "2018-10-12T08:00:17.263Z",
"question_score": 216,
"tags": "dart|flutter|flutter-layout",
"answer_id": 52774984,
"answer_date": "2018-10-12T08:04:37.077Z",
"answer_score": 295
} |
Please answer the following Stack Overflow question:
Title: What method in the String class returns only the first N characters?
<p>I'd like to write an extension method to the <code>String</code> class so that if the input string to is longer than the provided length <code>N</code>, only the first <code>N</code> characters are to be displayed.</p>
<p>Here's how it looks like:</p>
<pre><code>public static string TruncateLongString(this string str, int maxLength)
{
if (str.Length <= maxLength)
return str;
else
//return the first maxLength characters
}
</code></pre>
<p>What <code>String.*()</code> method can I use to get only the first <code>N</code> characters of <code>str</code>?</p> | <pre><code>public static string TruncateLongString(this string str, int maxLength)
{
if (string.IsNullOrEmpty(str)) return str;
return str.Substring(0, Math.Min(str.Length, maxLength));
}
</code></pre>
<p>In C# 8 or later it is also possible to use a <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges" rel="noreferrer">Range</a> to make this a bit terser:</p>
<pre><code>public static string TruncateLongString(this string str, int maxLength)
{
return str?[0..Math.Min(str.Length, maxLength)];
}
</code></pre>
<p>Which can be further reduced using an expression body:</p>
<pre><code>public static string TruncateLongString(this string str, int maxLength) =>
str?[0..Math.Min(str.Length, maxLength)];
</code></pre>
<p>Note null-conditional operator (<code>?</code>) is there to handle the case where <code>str</code> is null. This replaces the need for an explict null check.</p> | {
"question_id": 3566830,
"question_date": "2010-08-25T14:22:29.757Z",
"question_score": 216,
"tags": "c#|.net|string|character",
"answer_id": 3566842,
"answer_date": "2010-08-25T14:23:54.010Z",
"answer_score": 432
} |
Please answer the following Stack Overflow question:
Title: What is Dispatcher Servlet in Spring?
<p>In this image (which I got from <strong><a href="http://maestric.com/wiki/lib/exe/fetch.php?w=&h=&cache=cache&media=java:spring:spring_mvc.png" rel="noreferrer">here</a></strong>), <em>HTTP</em> request sends something to <em>Dispatcher Servlet.</em> </p>
<p><img src="https://i.stack.imgur.com/nRDbB.png" alt="enter image description here"></p>
<p>My Question is what does <em>Dispatcher Servlet</em> do?</p>
<p>Is it something like getting the information thrown from the web page and throwing it to the controller?</p> | <p>The job of the <em>DispatcherServlet</em> is to take an incoming URI and find the right combination of handlers (generally methods on <em>Controller</em> classes) and views (generally JSPs) that combine to form the page or resource that's supposed to be found at that location.</p>
<p>I might have</p>
<ul>
<li>a file <code>/WEB-INF/jsp/pages/Home.jsp</code></li>
<li><p>and a <em>method</em> on a class</p>
<pre><code>@RequestMapping(value="/pages/Home.html")
private ModelMap buildHome() {
return somestuff;
}
</code></pre></li>
</ul>
<p>The <em>Dispatcher servlet</em> is the bit that "knows" to call that method when a browser requests the page, and to combine its results with the matching JSP file to make an html document.</p>
<p>How it accomplishes this varies widely with configuration and Spring version.</p>
<p>There's also no reason the end result has to be web pages. It can do the same thing to locate <em>RMI</em> end points, handle <em>SOAP</em> requests, anything that can come into a servlet.</p> | {
"question_id": 2769467,
"question_date": "2010-05-04T22:48:46.453Z",
"question_score": 216,
"tags": "java|spring|spring-mvc|servlet-dispatching",
"answer_id": 2769523,
"answer_date": "2010-05-04T22:59:21.293Z",
"answer_score": 227
} |
Please answer the following Stack Overflow question:
Title: Where is Xcode's build folder?
<p>Before Xcode 4 the build used to be created in the root folder of my project.
I can no longer find it.</p>
<p>Where can i find the build folder?</p> | <p><code>~/Library/Developer/Xcode/DerivedData</code> is now the default.<br>
You can set the prefs in Xcode to allow projects to specify their build directories.</p> | {
"question_id": 5952782,
"question_date": "2011-05-10T15:45:56.593Z",
"question_score": 216,
"tags": "xcode|build",
"answer_id": 5952823,
"answer_date": "2011-05-10T15:50:22.240Z",
"answer_score": 279
} |
Please answer the following Stack Overflow question:
Title: Best way to compare 2 XML documents in Java
<p>I'm trying to write an automated test of an application that basically translates a custom message format into an XML message and sends it out the other end. I've got a good set of input/output message pairs so all I need to do is send the input messages in and listen for the XML message to come out the other end.</p>
<p>When it comes time to compare the actual output to the expected output I'm running into some problems. My first thought was just to do string comparisons on the expected and actual messages. This doens't work very well because the example data we have isn't always formatted consistently and there are often times different aliases used for the XML namespace (and sometimes namespaces aren't used at all.)</p>
<p>I know I can parse both strings and then walk through each element and compare them myself and this wouldn't be too difficult to do, but I get the feeling there's a better way or a library I could leverage. </p>
<p>So, boiled down, the question is:</p>
<p>Given two Java Strings which both contain valid XML how would you go about determining if they are semantically equivalent? Bonus points if you have a way to determine what the differences are.</p> | <p>Sounds like a job for XMLUnit</p>
<ul>
<li><a href="http://www.xmlunit.org/" rel="noreferrer">http://www.xmlunit.org/</a></li>
<li><a href="https://github.com/xmlunit" rel="noreferrer">https://github.com/xmlunit</a></li>
</ul>
<p>Example:</p>
<pre><code>public class SomeTest extends XMLTestCase {
@Test
public void test() {
String xml1 = ...
String xml2 = ...
XMLUnit.setIgnoreWhitespace(true); // ignore whitespace differences
// can also compare xml Documents, InputSources, Readers, Diffs
assertXMLEqual(xml1, xml2); // assertXMLEquals comes from XMLTestCase
}
}
</code></pre> | {
"question_id": 141993,
"question_date": "2008-09-26T21:10:32.827Z",
"question_score": 216,
"tags": "java|xml|testing|parsing|comparison",
"answer_id": 142167,
"answer_date": "2008-09-26T21:43:03.857Z",
"answer_score": 210
} |
Please answer the following Stack Overflow question:
Title: Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu
<p>I am running the 32bit version of Ubuntu 10.10 and trying to cross compile to a 64 bit target. Based on my research, I have installed the g++-multilib package.</p>
<p>The program is a very simple hello world:</p>
<pre><code>#include <iostream>
int main( int argc, char** argv )
{
std::cout << "hello world" << std::endl;
return 0;
}
</code></pre>
<p>Compile:</p>
<pre><code>g++ -m64 main.cpp
</code></pre>
<p>Error:</p>
<pre><code>In file included from main.cpp:1:
/usr/include/c++/4.4/iostream:39: fatal error: bits/c++config.h: No such file or directory
compilation terminated.
</code></pre>
<p>I have found a <code>c++config.h</code> file but they reside under the <code>i486-linux-gnu</code> and <code>i686-linux-gnu</code> directories in <code>/usr/include/c++/4.4/</code> There is not <code>c++config.h</code> in <code>/usr/include/c++/bits</code>.</p>
<p>Any ideas on what I am missing? Compiling without the <code>-m64</code> flag works fine (a.out is created and runs correctly).</p>
<p><strong>Edit</strong> Thanks to the hint from @nightcracker, I did a little more investigation into the include structure on the 32 and 64 bit systems. I have added an <a href="https://stackoverflow.com/questions/4643197/missing-include-bits-cconfig-h-when-cross-compiling-64-bit-program-on-32-bit/4643464#4643464">answer</a> below that "fixes" the problem temporarily but I think it will break on the next update. Basically, I am missing a directory called <code>/usr/include/c++/4.4/i686-linux-gnu/64</code> that should contain a subdirectory called <code>bits</code> that has the missing include file. Any idea what package should be taking care of this?</p> | <p>Adding this answer partially because it fixed my problem of the same issue and so I can bookmark this question myself.</p>
<p>I was able to fix it by doing the following:</p>
<pre><code>sudo apt-get install gcc-multilib g++-multilib
</code></pre>
<p>If you've installed a version of <code>gcc</code> / <code>g++</code> that doesn't ship by default (such as <code>g++-4.8</code> on lucid) you'll want to match the version as well:</p>
<pre><code>sudo apt-get install gcc-4.8-multilib g++-4.8-multilib
</code></pre> | {
"question_id": 4643197,
"question_date": "2011-01-10T02:20:44.497Z",
"question_score": 216,
"tags": "ubuntu|g++|32bit-64bit|cross-compiling|ubuntu-10.10",
"answer_id": 14391677,
"answer_date": "2013-01-18T02:49:18.990Z",
"answer_score": 363
} |
Please answer the following Stack Overflow question:
Title: How to initialize static variables
<p>I have this code:</p>
<pre><code>private static $dates = array(
'start' => mktime( 0, 0, 0, 7, 30, 2009), // Start date
'end' => mktime( 0, 0, 0, 8, 2, 2009), // End date
'close' => mktime(23, 59, 59, 7, 20, 2009), // Date when registration closes
'early' => mktime( 0, 0, 0, 3, 19, 2009), // Date when early bird discount ends
);
</code></pre>
<p>Which gives me the following error:</p>
<blockquote>
<p>Parse error: syntax error, unexpected '(', expecting ')' in /home/user/Sites/site/registration/inc/registration.class.inc on line 19</p>
</blockquote>
<p>So, I guess I am doing something wrong... but how can I do this if not like that? If I change the mktime stuff with regular strings, it works. So I know that I can do it <em>sort of</em> like that..</p>
<p>Anyone have some pointers?</p> | <p>PHP can't parse non-trivial expressions in initializers.</p>
<p>I prefer to work around this by adding code right after definition of the class:</p>
<pre><code>class Foo {
static $bar;
}
Foo::$bar = array(…);
</code></pre>
<p>or</p>
<pre><code>class Foo {
private static $bar;
static function init()
{
self::$bar = array(…);
}
}
Foo::init();
</code></pre>
<hr>
<p><a href="https://wiki.php.net/rfc/const_scalar_exprs" rel="noreferrer">PHP 5.6</a> can handle some expressions now.</p>
<pre><code>/* For Abstract classes */
abstract class Foo{
private static function bar(){
static $bar = null;
if ($bar == null)
bar = array(...);
return $bar;
}
/* use where necessary */
self::bar();
}
</code></pre> | {
"question_id": 693691,
"question_date": "2009-03-28T22:50:59.133Z",
"question_score": 216,
"tags": "php|class|static-members",
"answer_id": 693799,
"answer_date": "2009-03-28T23:50:04.017Z",
"answer_score": 353
} |
Please answer the following Stack Overflow question:
Title: How can I access "static" class variables within methods in Python?
<p>If I have the following code:</p>
<pre><code>class Foo(object):
bar = 1
def bah(self):
print(bar)
f = Foo()
f.bah()
</code></pre>
<p>It complains</p>
<blockquote>
<p>NameError: global name 'bar' is not defined</p>
</blockquote>
<p>How can I access class/static variable <code>bar</code> within method <code>bah</code>?</p> | <p>Instead of <code>bar</code> use <code>self.bar</code> or <code>Foo.bar</code>. Assigning to <code>Foo.bar</code> will create a static variable, and assigning to <code>self.bar</code> will create an instance variable.</p> | {
"question_id": 707380,
"question_date": "2009-04-01T21:23:39.717Z",
"question_score": 216,
"tags": "python|oop|static-variables",
"answer_id": 707389,
"answer_date": "2009-04-01T21:25:28.403Z",
"answer_score": 223
} |
Please answer the following Stack Overflow question:
Title: How do I use the lines of a file as arguments of a command?
<p>Say, I have a file <code>foo.txt</code> specifying <code>N</code> arguments</p>
<pre><code>arg1
arg2
...
argN
</code></pre>
<p>which I need to pass to the command <code>my_command</code></p>
<p>How do I use the lines of a file as arguments of a command?</p> | <p>If your shell is bash (amongst others), a shortcut for <code>$(cat afile)</code> is <code>$(< afile)</code>, so you'd write:</p>
<pre><code>mycommand "$(< file.txt)"
</code></pre>
<p>Documented in the bash man page in the 'Command Substitution' section.</p>
<p>Alterately, have your command read from stdin, so: <code>mycommand < file.txt</code></p> | {
"question_id": 4227994,
"question_date": "2010-11-19T18:04:36.017Z",
"question_score": 216,
"tags": "linux|unix|shell|command-line|command-line-arguments",
"answer_id": 4229151,
"answer_date": "2010-11-19T20:35:13.070Z",
"answer_score": 294
} |
Please answer the following Stack Overflow question:
Title: Which is more efficient, a for-each loop, or an iterator?
<p>Which is the most efficient way to traverse a collection?</p>
<pre><code>List<Integer> a = new ArrayList<Integer>();
for (Integer integer : a) {
integer.toString();
}
</code></pre>
<p>or</p>
<pre><code>List<Integer> a = new ArrayList<Integer>();
for (Iterator iterator = a.iterator(); iterator.hasNext();) {
Integer integer = (Integer) iterator.next();
integer.toString();
}
</code></pre>
<p>Please note, that this is not an exact duplicate of <a href="https://stackoverflow.com/questions/89891/what-are-the-benefits-of-the-iterator-interface-in-java">this</a>, <a href="https://stackoverflow.com/questions/131241/why-use-iterators-instead-of-array-indices">this</a>, <a href="https://stackoverflow.com/questions/99164/iterate-with-for-loop-or-while-loop">this</a>, or <a href="https://stackoverflow.com/questions/1879255/traditional-for-loop-vs-iterator-in-java">this</a>, although one of the answers to the last question comes close. The reason that this is not a dupe, is that most of these are comparing loops where you call <code>get(i)</code> inside the loop, rather than using the iterator.</p>
<p>As suggested on <a href="https://meta.stackexchange.com/questions/12513/stackoverflow-should-i-answer-my-own-question-or-not">Meta</a> I will be posting my answer to this question.</p> | <p>If you are just wandering over the collection to read all of the values, then there is no difference between using an iterator or the new for loop syntax, as the new syntax just uses the iterator underwater.</p>
<p>If however, you mean by loop the old "c-style" loop:</p>
<pre><code>for(int i=0; i<list.size(); i++) {
Object o = list.get(i);
}
</code></pre>
<p>Then the new for loop, or iterator, can be a lot more efficient, depending on the underlying data structure. The reason for this is that for some data structures, <code>get(i)</code> is an O(n) operation, which makes the loop an O(n<sup>2</sup>) operation. A traditional linked list is an example of such a data structure. All iterators have as a fundamental requirement that <code>next()</code> should be an O(1) operation, making the loop O(n).</p>
<p>To verify that the iterator is used underwater by the new for loop syntax, compare the generated bytecodes from the following two Java snippets. First the for loop:</p>
<pre><code>List<Integer> a = new ArrayList<Integer>();
for (Integer integer : a)
{
integer.toString();
}
// Byte code
ALOAD 1
INVOKEINTERFACE java/util/List.iterator()Ljava/util/Iterator;
ASTORE 3
GOTO L2
L3
ALOAD 3
INVOKEINTERFACE java/util/Iterator.next()Ljava/lang/Object;
CHECKCAST java/lang/Integer
ASTORE 2
ALOAD 2
INVOKEVIRTUAL java/lang/Integer.toString()Ljava/lang/String;
POP
L2
ALOAD 3
INVOKEINTERFACE java/util/Iterator.hasNext()Z
IFNE L3
</code></pre>
<p>And second, the iterator:</p>
<pre><code>List<Integer> a = new ArrayList<Integer>();
for (Iterator iterator = a.iterator(); iterator.hasNext();)
{
Integer integer = (Integer) iterator.next();
integer.toString();
}
// Bytecode:
ALOAD 1
INVOKEINTERFACE java/util/List.iterator()Ljava/util/Iterator;
ASTORE 2
GOTO L7
L8
ALOAD 2
INVOKEINTERFACE java/util/Iterator.next()Ljava/lang/Object;
CHECKCAST java/lang/Integer
ASTORE 3
ALOAD 3
INVOKEVIRTUAL java/lang/Integer.toString()Ljava/lang/String;
POP
L7
ALOAD 2
INVOKEINTERFACE java/util/Iterator.hasNext()Z
IFNE L8
</code></pre>
<p>As you can see, the generated byte code is effectively identical, so there is no performance penalty to using either form. Therefore, you should choose the form of loop that is most aesthetically appealing to you, for most people that will be the for-each loop, as that has less boilerplate code.</p> | {
"question_id": 2113216,
"question_date": "2010-01-21T21:52:10.063Z",
"question_score": 216,
"tags": "java|collections|foreach",
"answer_id": 2113226,
"answer_date": "2010-01-21T21:53:26.033Z",
"answer_score": 278
} |
Please answer the following Stack Overflow question:
Title: How to set DialogFragment's width and height?
<p>Let's say I specify the layout of my <code>DialogFragment</code> in an xml layout file named <code>my_dialog_fragment.xml</code> and I specify the <code>layout_width</code> and <code>layout_height</code> values of its root view to a fixed value (e.g. <code>100dp</code>). I then inflate this layout in my <code>DialogFragment</code>'s <code>onCreateView(...)</code> method as follows:</p>
<pre><code>View view = inflater.inflate(R.layout.my_dialog_fragment, container, false);
</code></pre>
<p>Sadly, I find that when my <code>DialogFragment</code> appears, it does not respect the <code>layout_width</code> and <code>layout_height</code> values specified in its xml layout file and instead shrinks or expands depending on its content. Anyone know whether or how I can get my <code>DialogFragment</code> to respect the <code>layout_width</code> and <code>layout_height</code> values specified in its xml layout file? At the moment I'm having to specify the width and height of the <code>Dialog</code> again in my <code>DialogFragment</code>'s <code>onResume()</code> method as follows:</p>
<pre><code>getDialog().getWindow().setLayout(width, height);
</code></pre>
<p>The problem with this is that I have to remember to make any future changes to the width and height in two places.</p> | <p>If you convert directly from resources values:</p>
<pre class="lang-java prettyprint-override"><code>int width = getResources().getDimensionPixelSize(R.dimen.popup_width);
int height = getResources().getDimensionPixelSize(R.dimen.popup_height);
getDialog().getWindow().setLayout(width, height);
</code></pre>
<p>Then specify <code>match_parent</code> in your layout for the dialog:</p>
<pre class="lang-xml prettyprint-override"><code>android:layout_width="match_parent"
android:layout_height="match_parent"
</code></pre>
<p>Now you only have to worry about one place (i.e. your <code>DialogFragment.onResume</code> method). It's not perfect but at least it works for having a <code>RelativeLayout</code> as the root of your dialog's layout file.</p> | {
"question_id": 12478520,
"question_date": "2012-09-18T13:57:40.903Z",
"question_score": 216,
"tags": "android-dialogfragment|android-dialog",
"answer_id": 12923805,
"answer_date": "2012-10-16T21:35:27.673Z",
"answer_score": 194
} |
Please answer the following Stack Overflow question:
Title: String comparison in bash. [[: not found
<p>I am trying to compare strings in bash. I already found an answer on how to do it on <a href="https://stackoverflow.com/questions/229551/string-contains-in-bash">stackoverflow</a>. In script I am trying, I am using the code submitted by Adam in the mentioned question:</p>
<pre><code>#!/bin/bash
string='My string';
if [[ "$string" == *My* ]]
then
echo "It's there!";
fi
needle='y s'
if [[ "$string" == *"$needle"* ]]; then
echo "haystack '$string' contains needle '$needle'"
fi
</code></pre>
<p>I also tried approach from <a href="http://ubuntuforums.org/showthread.php?t=562398" rel="noreferrer">ubuntuforums</a> that you can find in 2nd post</p>
<pre><code>if [[ $var =~ regexp ]]; then
#do something
fi
</code></pre>
<p>In both cases I receive error:</p>
<pre><code>[[: not found
</code></pre>
<p>What am I doing wrong?</p> | <p><code>[[</code> is a bash-builtin. Your <code>/bin/bash</code> doesn't seem to be an actual bash.</p>
<p><em>From a comment:</em></p>
<p>Add <code>#!/bin/bash</code> at the top of file</p> | {
"question_id": 12230690,
"question_date": "2012-09-01T19:23:56.510Z",
"question_score": 216,
"tags": "bash|shell|ubuntu-11.04|string-comparison",
"answer_id": 12230723,
"answer_date": "2012-09-01T19:27:45.577Z",
"answer_score": 238
} |
Please answer the following Stack Overflow question:
Title: Chrome doesn't delete session cookies
<p>I'm trying to set session cookie in javascript like this:</p>
<pre><code>document.cookie = 'name=alex; path=/'
</code></pre>
<p>But Chrome doesn't delete it even if I quit browser and launch it again. </p>
<p>I checked in Firefox and Opera and both work as intended - they delete session cookie on browser exit.</p>
<p>Is Chrome just ignoring expiration rules?</p>
<p>I checked in multiple OSes and found out that session cookie gets removed on Chrome in Windows XP and Ubuntu, but NOT in Mac OSX Lion. </p> | <p>This can be caused by having Chrome set to <strong>Continue where you left off</strong>.</p>
<p><img src="https://i.stack.imgur.com/VMMIv.png" alt="enter image description here" /></p>
<h3>Further reading</h3>
<ul>
<li><a href="https://productforums.google.com/d/topic/chrome/9l-gKYIUg50/discussion" rel="noreferrer">Bug report: Chrome is not deleting temporary cookies – i.e. not logging me out automatically when I close all browser Windows</a></li>
<li><a href="https://code.google.com/p/chromium/issues/detail?id=128513" rel="noreferrer">Issue 128513 in Chromium: Session Cookies not cleared when Chrome processes closed</a></li>
<li><a href="https://bugs.chromium.org/p/chromium/issues/detail?id=128567" rel="noreferrer">Issue 128567: Session only cookies don't delete</a></li>
</ul> | {
"question_id": 10617954,
"question_date": "2012-05-16T11:54:14.467Z",
"question_score": 216,
"tags": "javascript|session|google-chrome|cookies",
"answer_id": 10772420,
"answer_date": "2012-05-27T07:42:29.927Z",
"answer_score": 258
} |
Please answer the following Stack Overflow question:
Title: Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT
<p>Before KitKat (or before the new Gallery) the <code>Intent.ACTION_GET_CONTENT</code> returned a URI like this</p>
<blockquote>
<p>content://media/external/images/media/3951.</p>
</blockquote>
<p>Using the <code>ContentResolver</code> and quering for
<code>MediaStore.Images.Media.DATA</code> returned the file URL.</p>
<p>In KitKat however the Gallery returns a URI (via "Last") like this:</p>
<blockquote>
<p>content://com.android.providers.media.documents/document/image:3951</p>
</blockquote>
<p>How do I handle this?</p> | <p>Try this: </p>
<pre><code>if (Build.VERSION.SDK_INT <19){
Intent intent = new Intent();
intent.setType("image/jpeg");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, getResources().getString(R.string.select_picture)),GALLERY_INTENT_CALLED);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/jpeg");
startActivityForResult(intent, GALLERY_KITKAT_INTENT_CALLED);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) return;
if (null == data) return;
Uri originalUri = null;
if (requestCode == GALLERY_INTENT_CALLED) {
originalUri = data.getData();
} else if (requestCode == GALLERY_KITKAT_INTENT_CALLED) {
originalUri = data.getData();
final int takeFlags = data.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION
| Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Check for the freshest data.
getContentResolver().takePersistableUriPermission(originalUri, takeFlags);
}
loadSomeStreamAsynkTask(originalUri);
}
</code></pre>
<p>Probably need </p>
<blockquote>
<p>@SuppressLint("NewApi")</p>
</blockquote>
<p>for </p>
<blockquote>
<p>takePersistableUriPermission</p>
</blockquote> | {
"question_id": 19834842,
"question_date": "2013-11-07T11:33:16.303Z",
"question_score": 216,
"tags": "android|android-intent|android-gallery|android-contentresolver",
"answer_id": 19874645,
"answer_date": "2013-11-09T09:57:11.240Z",
"answer_score": 109
} |
Please answer the following Stack Overflow question:
Title: How does JPA orphanRemoval=true differ from the ON DELETE CASCADE DML clause
<p>I am a little confused about the JPA 2.0 <code>orphanRemoval</code> attribute.</p>
<p>I think I can see it is needed when I use my JPA provider's DB generation tools to create the underlying database DDL to have an <code>ON DELETE CASCADE</code> on the particular relation.</p>
<p>However, if the DB exists and it already has an <code>ON DELETE CASCADE</code> on the relation, is this not enough to cascade the deletion appropriately? What does the <code>orphanRemoval</code> do in addition?</p>
<p>Cheers</p> | <p><code>orphanRemoval</code> has nothing to do with <code>ON DELETE CASCADE</code>.</p>
<p><code>orphanRemoval</code> is an entirely <strong>ORM-specific thing</strong>. It marks "child" entity to be removed when it's no longer referenced from the "parent" entity, e.g. when you remove the child entity from the corresponding collection of the parent entity.</p>
<p><code>ON DELETE CASCADE</code> is a <strong>database-specific thing</strong>, it deletes the "child" row in the database when the "parent" row is deleted.</p> | {
"question_id": 4329577,
"question_date": "2010-12-01T21:58:15.100Z",
"question_score": 216,
"tags": "hibernate|jpa|cascade|cascading-deletes|orphan-removal",
"answer_id": 4329723,
"answer_date": "2010-12-01T22:18:00.890Z",
"answer_score": 346
} |
Please answer the following Stack Overflow question:
Title: Guzzlehttp - How get the body of a response from Guzzle 6?
<p>I'm trying to write a wrapper around an api my company is developing. It's restful, and using Postman I can send a post request to an endpoint like <code>http://subdomain.dev.myapi.com/api/v1/auth/</code> with a username and password as POST data and I am given back a token. All works as expected. Now, when I try and do the same from PHP I get back a <code>GuzzleHttp\Psr7\Response</code> object, but can't seem to find the token anywhere inside it as I did with the Postman request. </p>
<p>The relevant code looks like: </p>
<pre><code>$client = new Client(['base_uri' => 'http://companysub.dev.myapi.com/']);
$response = $client->post('api/v1/auth/', [
'form_params' => [
'username' => $user,
'password' => $password
]
]);
var_dump($response); //or $resonse->getBody(), etc...
</code></pre>
<p>The output of the code above looks something like (warning, incoming wall of text):</p>
<pre><code>object(guzzlehttp\psr7\response)#36 (6) {
["reasonphrase":"guzzlehttp\psr7\response":private]=>
string(2) "ok"
["statuscode":"guzzlehttp\psr7\response":private]=>
int(200)
["headers":"guzzlehttp\psr7\response":private]=>
array(9) {
["connection"]=>
array(1) {
[0]=>
string(10) "keep-alive"
}
["server"]=>
array(1) {
[0]=>
string(15) "gunicorn/19.3.0"
}
["date"]=>
array(1) {
[0]=>
string(29) "sat, 30 may 2015 17:22:41 gmt"
}
["transfer-encoding"]=>
array(1) {
[0]=>
string(7) "chunked"
}
["content-type"]=>
array(1) {
[0]=>
string(16) "application/json"
}
["allow"]=>
array(1) {
[0]=>
string(13) "post, options"
}
["x-frame-options"]=>
array(1) {
[0]=>
string(10) "sameorigin"
}
["vary"]=>
array(1) {
[0]=>
string(12) "cookie, host"
}
["via"]=>
array(1) {
[0]=>
string(9) "1.1 vegur"
}
}
["headerlines":"guzzlehttp\psr7\response":private]=>
array(9) {
["connection"]=>
array(1) {
[0]=>
string(10) "keep-alive"
}
["server"]=>
array(1) {
[0]=>
string(15) "gunicorn/19.3.0"
}
["date"]=>
array(1) {
[0]=>
string(29) "sat, 30 may 2015 17:22:41 gmt"
}
["transfer-encoding"]=>
array(1) {
[0]=>
string(7) "chunked"
}
["content-type"]=>
array(1) {
[0]=>
string(16) "application/json"
}
["allow"]=>
array(1) {
[0]=>
string(13) "post, options"
}
["x-frame-options"]=>
array(1) {
[0]=>
string(10) "sameorigin"
}
["vary"]=>
array(1) {
[0]=>
string(12) "cookie, host"
}
["via"]=>
array(1) {
[0]=>
string(9) "1.1 vegur"
}
}
["protocol":"guzzlehttp\psr7\response":private]=>
string(3) "1.1"
["stream":"guzzlehttp\psr7\response":private]=>
object(guzzlehttp\psr7\stream)#27 (7) {
["stream":"guzzlehttp\psr7\stream":private]=>
resource(40) of type (stream)
["size":"guzzlehttp\psr7\stream":private]=>
null
["seekable":"guzzlehttp\psr7\stream":private]=>
bool(true)
["readable":"guzzlehttp\psr7\stream":private]=>
bool(true)
["writable":"guzzlehttp\psr7\stream":private]=>
bool(true)
["uri":"guzzlehttp\psr7\stream":private]=>
string(10) "php://temp"
["custommetadata":"guzzlehttp\psr7\stream":private]=>
array(0) {
}
}
}
</code></pre>
<p>The output from Postman was something like:</p>
<pre><code>{
"data" : {
"token" "fasdfasf-asfasdfasdf-sfasfasf"
}
}
</code></pre>
<p>Clearly I'm missing something about working with the response objects in Guzzle. The Guzzle response indicates a 200 status code on the request, so I'm not sure exactly what I need to do to retrieve the returned data.</p> | <p>Guzzle implements <a href="http://www.php-fig.org/psr/psr-7/">PSR-7</a>. That means that it will by default store the body of a message in a <a href="https://github.com/php-fig/http-message/blob/master/src/StreamInterface.php">Stream</a> that uses PHP temp streams. To retrieve all the data, you can use casting operator:</p>
<pre><code>$contents = (string) $response->getBody();
</code></pre>
<p>You can also do it with</p>
<pre><code>$contents = $response->getBody()->getContents();
</code></pre>
<p>The difference between the two approaches is that <code>getContents</code> returns the remaining contents, so that a second call returns nothing unless you seek the position of the stream with <code>rewind</code> or <code>seek</code> .</p>
<pre><code>$stream = $response->getBody();
$contents = $stream->getContents(); // returns all the contents
$contents = $stream->getContents(); // empty string
$stream->rewind(); // Seek to the beginning
$contents = $stream->getContents(); // returns all the contents
</code></pre>
<p>Instead, usings PHP's string casting operations, it will reads all the data from the stream from the beginning until the end is reached.</p>
<pre><code>$contents = (string) $response->getBody(); // returns all the contents
$contents = (string) $response->getBody(); // returns all the contents
</code></pre>
<p>Documentation: <a href="http://docs.guzzlephp.org/en/latest/psr7.html#responses">http://docs.guzzlephp.org/en/latest/psr7.html#responses</a></p> | {
"question_id": 30549226,
"question_date": "2015-05-30T17:29:23.893Z",
"question_score": 216,
"tags": "php|response|guzzle|guzzle6",
"answer_id": 30549372,
"answer_date": "2015-05-30T17:43:33.470Z",
"answer_score": 558
} |
Please answer the following Stack Overflow question:
Title: How to remove all subviews of a view in Swift?
<p>I'm looking for a simple method to remove at once all subviews from a superview instead of removing them one by one.</p>
<pre><code>//I'm trying something like this, but is not working
let theSubviews : Array = container_view.subviews
for (view : NSView) in theSubviews {
view.removeFromSuperview(container_view)
}
</code></pre>
<p>What I am missing?</p>
<p><strong>UPDATE</strong></p>
<p>My app has a main <code>container_view</code>. I have to add different other views as subviews to <code>container_view</code> in order to provide a sort of navigation.</p>
<p>So, when clicking the button to "open" a particular page, I need to remove allsubviews and add the new one.</p>
<p><strong>UPDATE 2 - A working solution (OS X)</strong></p>
<p>I guess Apple fixed it.</p>
<p>Now it is more easy than ever, just call: </p>
<pre><code>for view in containerView.subviews{
view.removeFromSuperview()
}
</code></pre> | <p>EDIT: (thanks Jeremiah / Rollo)</p>
<p>By far the best way to do this in Swift for iOS is:</p>
<pre><code>view.subviews.forEach({ $0.removeFromSuperview() }) // this gets things done
view.subviews.map({ $0.removeFromSuperview() }) // this returns modified array
</code></pre>
<p>^^ These features are fun!</p>
<pre><code>let funTimes = ["Awesome","Crazy","WTF"]
extension String {
func readIt() {
print(self)
}
}
funTimes.forEach({ $0.readIt() })
</code></pre>
<p>//// END EDIT</p>
<p>Just do this:</p>
<pre><code>for view in self.view.subviews {
view.removeFromSuperview()
}
</code></pre>
<p>Or if you are looking for a specific class</p>
<pre><code>for view:CustomViewClass! in self.view.subviews {
if view.isKindOfClass(CustomViewClass) {
view.doClassThing()
}
}
</code></pre> | {
"question_id": 24312760,
"question_date": "2014-06-19T17:26:22.713Z",
"question_score": 216,
"tags": "macos|view|swift",
"answer_id": 24666052,
"answer_date": "2014-07-10T01:13:40.740Z",
"answer_score": 400
} |
Please answer the following Stack Overflow question:
Title: Unit testing void methods?
<p>What is the best way to unit test a method that doesn't return anything? Specifically in c#.</p>
<p>What I am really trying to test is a method that takes a log file and parses it for specific strings. The strings are then inserted into a database. Nothing that hasn't been done before but being VERY new to TDD I am wondering if it is possible to test this or is it something that doesn't really get tested.</p> | <p>If a method doesn't return anything, it's either one of the following</p>
<ul>
<li><strong>imperative</strong> - You're either asking the object to do something to itself.. e.g change state (without expecting any confirmation.. its assumed that it will be done)</li>
<li><strong>informational</strong> - just notifying someone that something happened (without expecting action or response) respectively. </li>
</ul>
<p>Imperative methods - you can verify if the task was actually performed. Verify if state change actually took place. e.g.</p>
<pre><code>void DeductFromBalance( dAmount )
</code></pre>
<p>can be tested by verifying if the balance post this message is indeed less than the initial value by dAmount</p>
<p>Informational methods - are rare as a member of the public interface of the object... hence not normally unit-tested. However if you must, You can verify if the handling to be done on a notification takes place. e.g.</p>
<pre><code>void OnAccountDebit( dAmount ) // emails account holder with info
</code></pre>
<p>can be tested by verifying if the email is being sent</p>
<p><em>Post more details about your actual method and people will be able to answer better.</em><br>
<strong>Update</strong>: Your method is doing 2 things. I'd actually split it into two methods that can now be independently tested. </p>
<pre><code>string[] ExamineLogFileForX( string sFileName );
void InsertStringsIntoDatabase( string[] );
</code></pre>
<p>String[] can be easily verified by providing the first method with a dummy file and expected strings. The second one is slightly tricky.. you can either use a Mock (google or search stackoverflow on mocking frameworks) to mimic the DB or hit the actual DB and verify if the strings were inserted in the right location. Check <a href="https://stackoverflow.com/questions/31837/best-books-about-tdd">this thread</a> for some good books... I'd recomment Pragmatic Unit Testing if you're in a crunch.<br>
In the code it would be used like </p>
<pre><code>InsertStringsIntoDatabase( ExamineLogFileForX( "c:\OMG.log" ) );
</code></pre> | {
"question_id": 246038,
"question_date": "2008-10-29T07:28:12.883Z",
"question_score": 216,
"tags": "c#|unit-testing|void",
"answer_id": 246060,
"answer_date": "2008-10-29T07:39:52.050Z",
"answer_score": 173
} |
Please answer the following Stack Overflow question:
Title: Delete all the queues from RabbitMQ?
<p>I installed <code>rabbitmqadmin</code> and was able to list all the exchanges and queues. How can I use <code>rabbitmqadmin</code> or <code>rabbitmqctl</code> to delete all the queues.</p> | <p>First, list your queues: </p>
<p><code>rabbitmqadmin list queues name</code></p>
<p>Then from the list, you'll need to manually delete them one by one: </p>
<p><code>rabbitmqadmin delete queue name='queuename'</code></p>
<p>Because of the output format, doesn't appear you can grep the response from <code>list queues</code>. Alternatively, if you're just looking for a way to clear <em>everything</em> (read: <strong>reset all settings</strong>, returning the installation to a default state), use:</p>
<pre><code>rabbitmqctl stop_app
rabbitmqctl reset # Be sure you really want to do this!
rabbitmqctl start_app
</code></pre> | {
"question_id": 11459676,
"question_date": "2012-07-12T19:59:36.923Z",
"question_score": 216,
"tags": "rabbitmq|rabbitmqctl",
"answer_id": 11459967,
"answer_date": "2012-07-12T20:19:39.183Z",
"answer_score": 308
} |
Please answer the following Stack Overflow question:
Title: Map enum in JPA with fixed values?
<p>I'm looking for the different ways to map an enum using JPA. I especially want to set the integer value of each enum entry and to save only the integer value.</p>
<pre><code>@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {
public enum Right {
READ(100), WRITE(200), EDITOR (300);
private int value;
Right(int value) { this.value = value; }
public int getValue() { return value; }
};
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "AUTHORITY_ID")
private Long id;
// the enum to map :
private Right right;
}
</code></pre>
<p>A simple solution is to use the Enumerated annotation with EnumType.ORDINAL:</p>
<pre><code>@Column(name = "RIGHT")
@Enumerated(EnumType.ORDINAL)
private Right right;
</code></pre>
<p>But in this case JPA maps the enum index (0,1,2) and not the value I want (100,200,300).</p>
<p>Th two solutions I found do not seem simple...</p>
<h2>First Solution</h2>
<p>A solution, <a href="http://forums.java.net/jive/thread.jspa?threadID=32048" rel="noreferrer">proposed here</a>, uses @PrePersist and @PostLoad to convert the enum to an other field and mark the enum field as transient:</p>
<pre><code>@Basic
private int intValueForAnEnum;
@PrePersist
void populateDBFields() {
intValueForAnEnum = right.getValue();
}
@PostLoad
void populateTransientFields() {
right = Right.valueOf(intValueForAnEnum);
}
</code></pre>
<h2>Second Solution</h2>
<p>The second solution <a href="http://appfuse.org/display/APF/Java+5+Enums+Persistence+with+Hibernate" rel="noreferrer">proposed here</a> proposed a generic conversion object, but still seems heavy and hibernate-oriented (@Type doesn't seem to exist in Java EE): </p>
<pre><code>@Type(
type = "org.appfuse.tutorial.commons.hibernate.GenericEnumUserType",
parameters = {
@Parameter(
name = "enumClass",
value = "Authority$Right"),
@Parameter(
name = "identifierMethod",
value = "toInt"),
@Parameter(
name = "valueOfMethod",
value = "fromInt")
}
)
</code></pre>
<h2>Is there any other solutions ?</h2>
<p>I've several ideas in mind but I don't know if they exist in JPA:</p>
<ul>
<li>use the setter and getter methods of right member of Authority Class when loading and saving the Authority object</li>
<li>an equivalent idea would be to tell JPA what are the methods of Right enum to convert enum to int and int to enum</li>
<li>Because I'm using Spring, is there any way to tell JPA to use a specific converter (RightEditor) ?</li>
</ul> | <p>For versions earlier than JPA 2.1, JPA provides only two ways to deal with enums, by their <code>name</code> or by their <code>ordinal</code>. And the standard JPA doesn't support custom types. So:</p>
<ul>
<li>If you want to do custom type conversions, you'll have to use a provider extension (with Hibernate <code>UserType</code>, EclipseLink <code>Converter</code>, etc). (the second solution). ~or~</li>
<li>You'll have to use the @PrePersist and @PostLoad trick (the first solution). ~or~</li>
<li>Annotate getter and setter taking and returning the <code>int</code> value ~or~</li>
<li>Use an integer attribute at the entity level and perform a translation in getters and setters.</li>
</ul>
<p>I'll illustrate the latest option (this is a basic implementation, tweak it as required):</p>
<pre><code>@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {
public enum Right {
READ(100), WRITE(200), EDITOR (300);
private int value;
Right(int value) { this.value = value; }
public int getValue() { return value; }
public static Right parse(int id) {
Right right = null; // Default
for (Right item : Right.values()) {
if (item.getValue()==id) {
right = item;
break;
}
}
return right;
}
};
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "AUTHORITY_ID")
private Long id;
@Column(name = "RIGHT_ID")
private int rightId;
public Right getRight () {
return Right.parse(this.rightId);
}
public void setRight(Right right) {
this.rightId = right.getValue();
}
}
</code></pre> | {
"question_id": 2751733,
"question_date": "2010-05-01T22:14:59.290Z",
"question_score": 216,
"tags": "java|spring|orm|jpa|enums",
"answer_id": 2751896,
"answer_date": "2010-05-01T23:25:56.597Z",
"answer_score": 182
} |
Please answer the following Stack Overflow question:
Title: View not attached to window manager crash
<p>I am using ACRA to report app crashes. I was getting a <code>View not attached to window manager</code> error message and thought I had fixed it by wrapping the <code>pDialog.dismiss();</code> in an if statement:</p>
<pre><code>if (pDialog!=null)
{
if (pDialog.isShowing())
{
pDialog.dismiss();
}
}
</code></pre>
<p>It has reduced the amount of <code>View not attached to window manager</code> crashes I recieve, but I am still getting some and I am not sure how to solve it.</p>
<p>Error message:</p>
<pre><code>java.lang.IllegalArgumentException: View not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:425)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:327)
at android.view.WindowManagerImpl.removeView(WindowManagerImpl.java:83)
at android.app.Dialog.dismissDialog(Dialog.java:330)
at android.app.Dialog.dismiss(Dialog.java:312)
at com.package.class$LoadAllProducts.onPostExecute(class.java:624)
at com.package.class$LoadAllProducts.onPostExecute(class.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>Code snippet:</p>
<pre><code>class LoadAllProducts extends AsyncTask<String, String, String>
{
/**
* Before starting background thread Show Progress Dialog
* */
@Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(CLASS.this);
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args)
{
// Building Parameters
doMoreStuff("internet");
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url)
{
// dismiss the dialog after getting all products
if (pDialog!=null)
{
if (pDialog.isShowing())
{
pDialog.dismiss(); //This is line 624!
}
}
something(note);
}
}
</code></pre>
<p>Manifest:</p>
<pre><code> <activity
android:name="pagename.CLASS"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize|screenLayout"
android:label="@string/name" >
</activity>
</code></pre>
<p>What am I missing to stop this crash from happening?</p> | <p><strong>How to reproduce the bug:</strong></p>
<ol>
<li>Enable this option on your device: <code>Settings -> Developer Options -> Don't keep Activities</code>.</li>
<li>Press Home button while the <code>AsyncTask</code> is executing and the <code>ProgressDialog</code> is showing.</li>
</ol>
<p>The Android OS will destroy an activity as soon as it is hidden. When <code>onPostExecute</code> is called the <code>Activity</code> will be in <em>"finishing"</em> state and the <code>ProgressDialog</code> will be not attached to <code>Activity</code>.</p>
<p><strong>How to fix it:</strong></p>
<ol>
<li>Check for the activity state in your <code>onPostExecute</code> method. </li>
<li>Dismiss the <code>ProgressDialog</code> in <code>onDestroy</code> method. Otherwise, <code>android.view.WindowLeaked</code> exception will be thrown. This exception usually comes from dialogs that are still active when the activity is finishing.</li>
</ol>
<p>Try this fixed code:</p>
<pre><code>public class YourActivity extends Activity {
private void showProgressDialog() {
if (pDialog == null) {
pDialog = new ProgressDialog(StartActivity.this);
pDialog.setMessage("Loading. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
}
pDialog.show();
}
private void dismissProgressDialog() {
if (pDialog != null && pDialog.isShowing()) {
pDialog.dismiss();
}
}
@Override
protected void onDestroy() {
dismissProgressDialog();
super.onDestroy();
}
class LoadAllProducts extends AsyncTask<String, String, String> {
// Before starting background thread Show Progress Dialog
@Override
protected void onPreExecute() {
showProgressDialog();
}
//getting All products from url
protected String doInBackground(String... args) {
doMoreStuff("internet");
return null;
}
// After completing background task Dismiss the progress dialog
protected void onPostExecute(String file_url) {
if (YourActivity.this.isDestroyed()) { // or call isFinishing() if min sdk version < 17
return;
}
dismissProgressDialog();
something(note);
}
}
}
</code></pre> | {
"question_id": 22924825,
"question_date": "2014-04-07T23:17:11.787Z",
"question_score": 216,
"tags": "android",
"answer_id": 23586127,
"answer_date": "2014-05-10T20:46:08.247Z",
"answer_score": 498
} |
Please answer the following Stack Overflow question:
Title: Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider
<p>I received this error upon upgrading from AngularJS <strong>1.0.7</strong> to <strong>1.2.0rc1</strong>. </p> | <p>The ngRoute module is no longer part of the core <code>angular.js</code> file. If you are continuing to use $routeProvider then you will now need to include <code>angular-route.js</code> in your HTML:</p>
<pre><code><script src="angular.js">
<script src="angular-route.js">
</code></pre>
<p><a href="http://docs.angularjs.org/api/ngRoute" rel="noreferrer">API Reference</a></p>
<p>You also have to add <code>ngRoute</code> as a dependency for your application:</p>
<pre><code>var app = angular.module('MyApp', ['ngRoute', ...]);
</code></pre>
<p>If instead you are planning on using <a href="https://github.com/angular-ui/ui-router" rel="noreferrer"><code>angular-ui-router</code></a> or the like then just remove the <code>$routeProvider</code> dependency from your module <code>.config()</code> and substitute it with the relevant provider of choice (e.g. <code>$stateProvider</code>). You would then use the <code>ui.router</code> dependency:</p>
<pre><code>var app = angular.module('MyApp', ['ui.router', ...]);
</code></pre> | {
"question_id": 18481863,
"question_date": "2013-08-28T07:34:41.347Z",
"question_score": 216,
"tags": "javascript|angularjs|routes",
"answer_id": 18481864,
"answer_date": "2013-08-28T07:34:41.347Z",
"answer_score": 404
} |
Please answer the following Stack Overflow question:
Title: Swift extract regex matches
<p>I want to extract substrings from a string that match a regex pattern. </p>
<p>So I'm looking for something like this:</p>
<pre><code>func matchesForRegexInText(regex: String!, text: String!) -> [String] {
???
}
</code></pre>
<p>So this is what I have:</p>
<pre><code>func matchesForRegexInText(regex: String!, text: String!) -> [String] {
var regex = NSRegularExpression(pattern: regex,
options: nil, error: nil)
var results = regex.matchesInString(text,
options: nil, range: NSMakeRange(0, countElements(text)))
as Array<NSTextCheckingResult>
/// ???
return ...
}
</code></pre>
<p>The problem is, that <code>matchesInString</code> delivers me an array of <code>NSTextCheckingResult</code>, where <code>NSTextCheckingResult.range</code> is of type <code>NSRange</code>. </p>
<p><code>NSRange</code> is incompatible with <code>Range<String.Index></code>, so it prevents me of using <code>text.substringWithRange(...)</code></p>
<p>Any idea how to achieve this simple thing in swift without too many lines of code?</p> | <p>Even if the <code>matchesInString()</code> method takes a <code>String</code> as the first argument,
it works internally with <code>NSString</code>, and the range parameter must be given
using the <code>NSString</code> length and not as the Swift string length. Otherwise it will
fail for "extended grapheme clusters" such as "flags".</p>
<p>As of <strong>Swift 4</strong> (Xcode 9), the Swift standard
library provides functions to convert between <code>Range<String.Index></code>
and <code>NSRange</code>.</p>
<pre><code>func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let results = regex.matches(in: text,
range: NSRange(text.startIndex..., in: text))
return results.map {
String(text[Range($0.range, in: text)!])
}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
</code></pre>
<p>Example:</p>
<pre><code>let string = "€4€9"
let matched = matches(for: "[0-9]", in: string)
print(matched)
// ["4", "9"]
</code></pre>
<p><em>Note:</em> The forced unwrap <code>Range($0.range, in: text)!</code> is safe because
the <code>NSRange</code> refers to a substring of the given string <code>text</code>.
However, if you want to avoid it then use</p>
<pre><code> return results.flatMap {
Range($0.range, in: text).map { String(text[$0]) }
}
</code></pre>
<p>instead.</p>
<hr>
<p><em>(Older answer for Swift 3 and earlier:)</em></p>
<p>So you should convert the given Swift string to an <code>NSString</code> and then extract the
ranges. The result will be converted to a Swift string array automatically.</p>
<p>(The code for Swift 1.2 can be found in the edit history.)</p>
<p><strong>Swift 2 (Xcode 7.3.1) :</strong></p>
<pre><code>func matchesForRegexInText(regex: String, text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matchesInString(text,
options: [], range: NSMakeRange(0, nsString.length))
return results.map { nsString.substringWithRange($0.range)}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
</code></pre>
<p>Example:</p>
<pre><code>let string = "€4€9"
let matches = matchesForRegexInText("[0-9]", text: string)
print(matches)
// ["4", "9"]
</code></pre>
<hr>
<p><strong>Swift 3 (Xcode 8)</strong></p>
<pre><code>func matches(for regex: String, in text: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex)
let nsString = text as NSString
let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
return results.map { nsString.substring(with: $0.range)}
} catch let error {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
</code></pre>
<p>Example:</p>
<pre><code>let string = "€4€9"
let matched = matches(for: "[0-9]", in: string)
print(matched)
// ["4", "9"]
</code></pre> | {
"question_id": 27880650,
"question_date": "2015-01-10T20:04:04.580Z",
"question_score": 216,
"tags": "ios|regex|string|swift",
"answer_id": 27880748,
"answer_date": "2015-01-10T20:12:24.743Z",
"answer_score": 370
} |
Please answer the following Stack Overflow question:
Title: How can I install the VS2017 version of msbuild on a build server without installing the IDE?
<p>Historically, this has been done with the <a href="https://www.microsoft.com/en-us/download/details.aspx?id=48159" rel="noreferrer">Microsoft Build Tools</a>. But it seems that <a href="https://blogs.msdn.microsoft.com/vcblog/2016/11/16/introducing-the-visual-studio-build-tools/" rel="noreferrer">the Build Tools may not be available for versions after 2015</a>. The replacement appears to be the Visual Studio build tools, which doesn't seem to have a real homepage yet.</p>
<p>I downloaded the <a href="https://www.visualstudio.com/downloads/" rel="noreferrer">VS2017 Professional installer</a>, and went to the <strong>Individual Components</strong> tab. Right away, the summary is telling me that the Visual Studio core editor is there, taking up 753MB. I don't want the editor. Just msbuild. There is no way to unselect the editor.</p>
<p>Is there a way I can install the latest version of msbuild without also installing the Visual Studio IDE?</p> | <p>The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called <strong>Build Tools for Visual Studio 2019</strong> (<a href="https://www.visualstudio.com/downloads/#build-tools-for-visual-studio-2019" rel="noreferrer">download</a>).</p>
<p>You can use the GUI to do the installation, or you can script the installation of msbuild:</p>
<pre><code>vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet
</code></pre>
<p><strong>Microsoft.VisualStudio.Workload.MSBuildTools</strong> is a "wrapper" ID for <a href="https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-build-tools" rel="noreferrer">the three subcomponents you need</a>:</p>
<ul>
<li>Microsoft.Component.MSBuild</li>
<li>Microsoft.VisualStudio.Component.CoreBuildTools</li>
<li>Microsoft.VisualStudio.Component.Roslyn.Compiler</li>
</ul>
<p>You can find documentation about the other available CLI switches <a href="https://docs.microsoft.com/en-us/visualstudio/install/use-command-line-parameters-to-install-visual-studio" rel="noreferrer">here</a>.</p>
<p>The build tools installation is <em>much</em> quicker than the full IDE. In my test, it took 5-10 seconds. With <code>--quiet</code> there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in <code>%programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin</code>.</p>
<p>If you don't see them there, try running without <code>--quiet</code> to see any error messages that may occur during installation.</p> | {
"question_id": 42696948,
"question_date": "2017-03-09T13:41:41.693Z",
"question_score": 216,
"tags": "msbuild|visual-studio-2017|visual-studio-2019|build-tools|build-server",
"answer_id": 42697374,
"answer_date": "2017-03-09T14:01:46.523Z",
"answer_score": 328
} |
Please answer the following Stack Overflow question:
Title: Prevent pushing to master on GitHub?
<p>GitHub allows you to configure your repository so that <a href="https://github.com/blog/2051-protected-branches-and-required-status-checks" rel="noreferrer">users can't force push to master</a>, but is there a way to prevent pushing to master entirely? I'm hoping to make it so that the only way of adding to commits to master is through the GitHub pull request UI.</p> | <p>Since the original question / answer, Github has added a new option for this to the restricted branches UI which allows you to set this up.</p>
<blockquote>
<p><strong>Require pull request reviews before merging</strong> When enabled, all commits must be made to a non-protected branch and submitted via a
pull request with the required number of approving reviews and no
changes requested before it can be merged into a branch that matches
this rule.</p>
</blockquote>
<p>To find it go to Settings > Branches > Branch Protection Rules
and click 'Add Rule'.
<a href="https://i.stack.imgur.com/yXqu9.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yXqu9.png" alt="Github UI after following instructions" /></a>
Then, enter the name of the branch you want to protect and click the checkbox to require pull request reviews before merging.
<a href="https://i.stack.imgur.com/05hTU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/05hTU.png" alt="Github UI with the button to click" /></a>
By default, this only stops people who are not moderators. There is also another checkbox later down for ensuring that even moderators cannot merge.
<a href="https://i.stack.imgur.com/a1oHr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/a1oHr.png" alt="Github UI with the other button to click" /></a></p> | {
"question_id": 46146491,
"question_date": "2017-09-10T23:34:46.603Z",
"question_score": 216,
"tags": "git|github|branch|access-control|pull-request",
"answer_id": 57685576,
"answer_date": "2019-08-28T05:27:39.450Z",
"answer_score": 163
} |
Please answer the following Stack Overflow question:
Title: How to copy a file to multiple directories using the gnu cp command
<p>Is it possible to copy a single file to multiple directories using the cp command ?</p>
<p>I tried the following , which did not work: </p>
<pre><code>cp file1 /foo/ /bar/
cp file1 {/foo/,/bar}
</code></pre>
<p>I know it's possible using a for loop, or find. But is it possible using the gnu cp command?</p> | <p>No, <code>cp</code> can copy multiple sources but will only copy to a single destination. You need to arrange to invoke <code>cp</code> multiple times - once per destination - for what you want to do; using, as you say, a loop or some other tool.</p> | {
"question_id": 195655,
"question_date": "2008-10-12T16:21:56.363Z",
"question_score": 216,
"tags": "linux|bash|shell",
"answer_id": 195663,
"answer_date": "2008-10-12T16:28:07.677Z",
"answer_score": 111
} |
Please answer the following Stack Overflow question:
Title: How to unit test with ILogger in ASP.NET Core
<p>This is my controller:</p>
<pre><code>public class BlogController : Controller
{
private IDAO<Blog> _blogDAO;
private readonly ILogger<BlogController> _logger;
public BlogController(ILogger<BlogController> logger, IDAO<Blog> blogDAO)
{
this._blogDAO = blogDAO;
this._logger = logger;
}
public IActionResult Index()
{
var blogs = this._blogDAO.GetMany();
this._logger.LogInformation("Index page say hello", new object[0]);
return View(blogs);
}
}
</code></pre>
<p>As you can see I have 2 dependencies, a <code>IDAO</code> and a <code>ILogger</code></p>
<p>And this is my test class, I use xUnit to test and Moq to create mock and stub, I can mock <code>DAO</code> easy, but with the <code>ILogger</code> I don't know what to do so I just pass null and comment out the call to log in controller when run test. Is there a way to test but still keep the logger somehow ?</p>
<pre><code>public class BlogControllerTest
{
[Fact]
public void Index_ReturnAViewResult_WithAListOfBlog()
{
var mockRepo = new Mock<IDAO<Blog>>();
mockRepo.Setup(repo => repo.GetMany(null)).Returns(GetListBlog());
var controller = new BlogController(null,mockRepo.Object);
var result = controller.Index();
var viewResult = Assert.IsType<ViewResult>(result);
var model = Assert.IsAssignableFrom<IEnumerable<Blog>>(viewResult.ViewData.Model);
Assert.Equal(2, model.Count());
}
}
</code></pre> | <p>Just mock it as well as any other dependency:</p>
<pre><code>var mock = new Mock<ILogger<BlogController>>();
ILogger<BlogController> logger = mock.Object;
//or use this short equivalent
logger = Mock.Of<ILogger<BlogController>>()
var controller = new BlogController(logger);
</code></pre>
<p>You probably will need to install <code>Microsoft.Extensions.Logging.Abstractions</code> package to use <code>ILogger<T></code>. </p>
<p>Moreover you can create a real logger:</p>
<pre><code>var serviceProvider = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();
var factory = serviceProvider.GetService<ILoggerFactory>();
var logger = factory.CreateLogger<BlogController>();
</code></pre> | {
"question_id": 43424095,
"question_date": "2017-04-15T08:51:22.640Z",
"question_score": 216,
"tags": "c#|unit-testing|asp.net-core|moq|ilogger",
"answer_id": 43425633,
"answer_date": "2017-04-15T11:44:12.757Z",
"answer_score": 231
} |
Please answer the following Stack Overflow question:
Title: How can I convert spaces to tabs in Vim or Linux?
<p>I've looked over several questions on Stack Overflow for how to convert spaces to tabs without finding what I need. There seem to be more questions about how to convert tabs to spaces, but I'm trying to do the opposite.</p>
<p>In <code>Vim</code> I've tried <code>:retab</code> and <code>:retab!</code> without luck, but I believe those are actually for going from tabs to spaces anyways.</p>
<p>I tried both <code>expand</code> and <code>unexpand</code> at the command prompt without any luck.</p>
<p>Here is the file in question:</p>
<p><a href="http://gdata-python-client.googlecode.com/hg-history/a9ed9edefd61a0ba0e18c43e448472051821003a/samples/docs/docs_v3_example.py">http://gdata-python-client.googlecode.com/hg-history/a9ed9edefd61a0ba0e18c43e448472051821003a/samples/docs/docs_v3_example.py</a></p>
<p>How can I convert <strong>leading</strong> spaces to tabs using either <code>Vim</code> or the shell?</p> | <p>Using Vim to expand all <em>leading</em> spaces (wider than <a href="http://vimdoc.sourceforge.net/htmldoc/options.html#%27tabstop%27" rel="noreferrer"><code>'tabstop'</code></a>), you were right to use <a href="http://vimdoc.sourceforge.net/htmldoc/change.html#:retab" rel="noreferrer"><code>retab</code></a> but first ensure <a href="http://vimdoc.sourceforge.net/htmldoc/options.html#%27expandtab%27" rel="noreferrer"><code>'expandtab'</code></a> is reset (<code>:verbose set ts? et?</code> is your friend). <code>retab</code> takes a <em>range</em>, so I usually specify <a href="http://vimdoc.sourceforge.net/htmldoc/cmdline.html#:%25" rel="noreferrer"><code>%</code></a> to mean "the whole file".</p>
<pre><code>:set tabstop=2 " To match the sample file
:set noexpandtab " Use tabs, not spaces
:%retab! " Retabulate the whole file
</code></pre>
<p>Before doing anything like this (particularly with Python files!), I usually set <a href="http://vimdoc.sourceforge.net/htmldoc/options.html#%27list%27" rel="noreferrer"><code>'list'</code></a>, so that I can <strong>see</strong> the whitespace and change. </p>
<p>I have the following mapping in <a href="https://github.com/johnsyweb/dotfiles/blob/e2289d90acd1f6e6df1c7cbe762ee39bd68ed3c6/.vimrc#L330" rel="noreferrer">my <code>.vimrc</code></a> for this:</p>
<pre><code>nnoremap <F2> :<C-U>setlocal lcs=tab:>-,trail:-,eol:$ list! list? <CR>
</code></pre> | {
"question_id": 9104706,
"question_date": "2012-02-01T23:02:22.337Z",
"question_score": 216,
"tags": "linux|vim|tabs|spaces",
"answer_id": 9105889,
"answer_date": "2012-02-02T01:26:54.450Z",
"answer_score": 367
} |
Please answer the following Stack Overflow question:
Title: Return positions of a regex match() in Javascript?
<p>Is there a way to retrieve the (starting) character positions inside a string of the results of a regex match() in Javascript?</p> | <p>Here's what I came up with:</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>// Finds starting and ending positions of quoted text
// in double or single quotes with escape char support like \" \'
var str = "this is a \"quoted\" string as you can 'read'";
var patt = /'((?:\\.|[^'])*)'|"((?:\\.|[^"])*)"/igm;
while (match = patt.exec(str)) {
console.log(match.index + ' ' + patt.lastIndex);
}</code></pre>
</div>
</div>
</p> | {
"question_id": 2295657,
"question_date": "2010-02-19T10:45:24.647Z",
"question_score": 216,
"tags": "javascript|regex|match|string-matching",
"answer_id": 2295943,
"answer_date": "2010-02-19T11:38:26.793Z",
"answer_score": 75
} |
Please answer the following Stack Overflow question:
Title: Running NPM scripts sequentially
<p>Let's say I have </p>
<pre><code>"scripts": {
"pre-build": "echo \"Welcome\" && exit 1",
"build_logic": "start cmd.exe @cmd /k \"yo esri-appbuilder-js:widget && exit 1\"",
"post_build": "start C:\\WebAppBuilderForArcGIS\\startupShortcut",
"exit" : "start cmd.exe @cmd /k \"echo \"goodbye\" && exit 1\""
},
</code></pre>
<p>What NPM command can I run to let all of these scripts launch sequentially. When I use pre/post fixing they launch sequentially but they don't wait for the parent script to finish before executing. I am assuming the only solution is like: <a href="https://stackoverflow.com/q/25371192/3174123">How do I get Gulp tasks to fire sequentially when firing shell commands in an async.series helper function?</a> ? I know this can be done with Gulp but I would like to stick with NPM for now to explore its capabilities. Thanks for any help!</p> | <p>Invoke these scripts via npm run and chain them with double ampersand <strong><code>&&</code></strong>:</p>
<pre><code>npm run pre-build && npm run build_logic && npm run post_build && npm run exit
</code></pre>
<p>Explanation:</p>
<ul>
<li>Use <strong><code>&&</code></strong> (double ampersand) for sequential execution.</li>
<li>Use <strong><code>&</code></strong> (single ampersand) for parallel execution.</li>
</ul> | {
"question_id": 39172536,
"question_date": "2016-08-26T18:22:26.673Z",
"question_score": 216,
"tags": "javascript|node.js|npm|cmd",
"answer_id": 39172660,
"answer_date": "2016-08-26T18:28:37.510Z",
"answer_score": 461
} |
Please answer the following Stack Overflow question:
Title: Pass Parameter to Gulp Task
<p>Normally we can run gulp task from console via something like <code>gulp mytask</code>. Is there anyway that I can pass in parameter to gulp task? If possible, please show example how it can be done.</p> | <p>It's a feature programs cannot stay without. You can try <a href="https://www.npmjs.com/package/yargs" rel="noreferrer">yargs</a>.</p>
<pre><code>npm install --save-dev yargs
</code></pre>
<p>You can use it like this:</p>
<pre><code>gulp mytask --production --test 1234
</code></pre>
<p>In the code, for example:</p>
<pre><code>var argv = require('yargs').argv;
var isProduction = (argv.production === undefined) ? false : true;
</code></pre>
<p>For your understanding:</p>
<pre><code>> gulp watch
console.log(argv.production === undefined); <-- true
console.log(argv.test === undefined); <-- true
> gulp watch --production
console.log(argv.production === undefined); <-- false
console.log(argv.production); <-- true
console.log(argv.test === undefined); <-- true
console.log(argv.test); <-- undefined
> gulp watch --production --test 1234
console.log(argv.production === undefined); <-- false
console.log(argv.production); <-- true
console.log(argv.test === undefined); <-- false
console.log(argv.test); <-- 1234
</code></pre>
<p>Hope you can take it from here.</p>
<p>There's another plugin that you can use, minimist. There's another post where there's good examples for both yargs and minimist: (<a href="https://stackoverflow.com/q/23023650">Is it possible to pass a flag to Gulp to have it run tasks in different ways?</a>)</p> | {
"question_id": 28538918,
"question_date": "2015-02-16T10:07:19.777Z",
"question_score": 216,
"tags": "gulp",
"answer_id": 28784063,
"answer_date": "2015-02-28T16:32:26.217Z",
"answer_score": 299
} |
Please answer the following Stack Overflow question:
Title: How do I change the default port (9000) that Play uses when I execute the "run" command?
<p>How can I change the default port used by the play framework in development mode when issueing the "run" command on the play console.</p>
<p>This is for playframework 2.0 beta.</p>
<p>Using the http.port configuration parameter either on the command line or in the application.conf seems to have no effect:</p>
<pre><code>C:\dev\prototype\activiti-preso>play run --http.port=8080
[info] Loading project definition from C:\dev\prototype\activiti-preso\project
[info] Set current project to activiti-preso (in build file:/C:/dev/prototype/activiti-preso/)
Windows, really? Ok, disabling colors.
--- (Running the application from SBT, auto-reloading is enabled) ---
[error] org.jboss.netty.channel.ChannelException: Failed to bind to: 0.0.0.0/0.0.0.0:9000
[error] Use 'last' for the full log.
</code></pre> | <h1>Play 2.x</h1>
<blockquote>
<p>In Play 2, these are implemented with an sbt plugin, so the following instructions are really just sbt tasks. You can use any sbt runner (e
In Play 2, these are implemented with an sbt plugin, so the following are really just
sbt tasks. You can use any sbt runner (e.g. <code>sbt</code>, <code>play</code>, or
<code>activator</code>). Below the <code>sbt</code> runner is used, but
you can substitute it for your sbt runner of choice.</p>
</blockquote>
<h2>Play 2.x - Dev Mode</h2>
<p>For browser-reload mode:</p>
<pre><code>sbt "run 8080"
</code></pre>
<p>For continuous-reload mode:</p>
<pre><code>sbt "~run 8080"
</code></pre>
<h2>Play 2.x - Debug Mode</h2>
<p>To run in debug mode with the http listener on port <code>8080</code>, run:</p>
<pre><code>sbt -jvm-debug 9999 "run 8080"
</code></pre>
<h2>Play 2.x - Prod Mode</h2>
<p>Start in Prod mode:</p>
<pre><code>sbt "start -Dhttp.port=8080"
</code></pre>
<h2>Play 2.x - Staged Distribution</h2>
<p>Create a staged distribution:</p>
<pre><code>sbt stage
</code></pre>
<p>For Play 2.0.x and 2.1.x use the <code>target/start</code> script (Unix Only):</p>
<pre><code>target/start -Dhttp.port=8080
</code></pre>
<p>For Play 2.2.x & 2.3.x use the appropriate start script in the <code>target/universal/stage/bin</code> directory:</p>
<pre><code>target/universal/stage/bin/[appname] -Dhttp.port=8080
</code></pre>
<p>With Play 2.2.x & 2.3.x on Windows:</p>
<pre><code>target\universal\stage\bin\[appname].bat -Dhttp.port=8080
</code></pre>
<h2>Play 2.x - Zip Distribution</h2>
<p>To create a zip distribution:</p>
<pre><code>sbt dist
</code></pre>
<p>For Play 2.0.x and 2.1.x use the <code>start</code> script (Unix Only) in the extracted zip:</p>
<pre><code>start -Dhttp.port=8080
</code></pre>
<p>For Play 2.2.x use the appropriate script in the <code>[appname]-[version]/bin</code> directory:</p>
<pre><code>[appname]-[version]/bin/[appname] -Dhttp.port=8080
</code></pre>
<p>With Play 2.2.x on Windows:</p>
<pre><code>[appname]-[version]\bin\[appname].bat -Dhttp.port=8080
</code></pre>
<h2>Play 1.x</h2>
<p>Change the <code>http.port</code> value in the <code>conf/application.conf</code> file or pass it command line:</p>
<pre><code>play run --http.port=8080
</code></pre> | {
"question_id": 8205067,
"question_date": "2011-11-20T21:56:34.233Z",
"question_score": 216,
"tags": "playframework|port|playframework-2.0",
"answer_id": 8206747,
"answer_date": "2011-11-21T02:49:26.977Z",
"answer_score": 420
} |
Please answer the following Stack Overflow question:
Title: Converting an integer to a hexadecimal string in Ruby
<p>Is there a built in way to convert an integer in Ruby into its hexadecimal equivalent?</p>
<p>Something like the opposite of <a href="http://ruby-doc.org/core-2.0.0/String.html#method-i-to_i" rel="noreferrer"><code>String#to_i</code></a>:</p>
<pre><code>"0A".to_i(16) #=>10
</code></pre>
<p>Like perhaps:</p>
<pre><code>"0A".hex #=>10
</code></pre>
<p>I know how to roll my own, but it's probably more efficient to use a built in Ruby function.</p> | <p>You can give <a href="http://www.ruby-doc.org/core/classes/Integer.html#method-i-to_s" rel="noreferrer"><code>to_s</code></a> a base other than 10:</p>
<pre><code>10.to_s(16) #=> "a"
</code></pre>
<p>Note that in ruby 2.4 <code>FixNum</code> and <code>BigNum</code> were unified in the <code>Integer</code> class.
If you are using an older ruby check the documentation of <a href="https://ruby-doc.org/core-2.3.8/Fixnum.html#method-i-to_s" rel="noreferrer">FixNum#<code>to_s</code></a> and <a href="https://ruby-doc.org/core-2.3.8/Bignum.html#method-i-to_s" rel="noreferrer">BigNum#<code>to_s</code></a></p> | {
"question_id": 84421,
"question_date": "2008-09-17T15:23:26.360Z",
"question_score": 216,
"tags": "ruby|hex|base-conversion",
"answer_id": 84485,
"answer_date": "2008-09-17T15:27:57.317Z",
"answer_score": 339
} |
Please answer the following Stack Overflow question:
Title: jquery's append not working with svg element?
<p>Assuming this:</p>
<pre><code><html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("svg").append('<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red"/>');
});
</script>
</head>
<body>
<svg xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 100" width="200px" height="100px">
</svg>
</body>
</code></pre>
<p>Why don't I see anything?</p> | <p>When you pass a markup string into <code>$</code>, it's parsed as HTML using the browser's <code>innerHTML</code> property on a <code><div></code> (or other suitable container for special cases like <code><tr></code>). <code>innerHTML</code> can't parse SVG or other non-HTML content, and even if it could it wouldn't be able to tell that <code><circle></code> was supposed to be in the SVG namespace.</p>
<p><code>innerHTML</code> is not available on SVGElement—it is a property of HTMLElement only. Neither is there currently an <code>innerSVG</code> property or other way(*) to parse content into an SVGElement. For this reason you should use DOM-style methods. jQuery doesn't give you easy access to the namespaced methods needed to create SVG elements. Really jQuery isn't designed for use with SVG at all and many operations may fail.</p>
<p>HTML5 promises to let you use <code><svg></code> without an <code>xmlns</code> inside a plain HTML (<code>text/html</code>) document in the future. But this is just a parser hack(**), the SVG content will still be SVGElements in the SVG namespace, and not HTMLElements, so you'll not be able to use <code>innerHTML</code> even though they <em>look</em> like part of an HTML document.</p>
<p>However, for today's browsers you must use <em>X</em>HTML (properly served as <code>application/xhtml+xml</code>; save with the .xhtml file extension for local testing) to get SVG to work at all. (It kind of makes sense to anyway; SVG is a properly XML-based standard.) This means you'd have to escape the <code><</code> symbols inside your script block (or enclose in a CDATA section), and include the XHTML <code>xmlns</code> declaration. example:</p>
<pre><code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"><head>
</head><body>
<svg id="s" xmlns="http://www.w3.org/2000/svg"/>
<script type="text/javascript">
function makeSVG(tag, attrs) {
var el= document.createElementNS('http://www.w3.org/2000/svg', tag);
for (var k in attrs)
el.setAttribute(k, attrs[k]);
return el;
}
var circle= makeSVG('circle', {cx: 100, cy: 50, r:40, stroke: 'black', 'stroke-width': 2, fill: 'red'});
document.getElementById('s').appendChild(circle);
circle.onmousedown= function() {
alert('hello');
};
</script>
</body></html>
</code></pre>
<p>*: well, there's DOM Level 3 LS's <a href="http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-LSParser-parseWithContext" rel="noreferrer">parseWithContext</a>, but browser support is very poor. Edit to add: however, whilst you can't inject markup into an SVGElement, you could inject a new SVGElement into an HTMLElement using <code>innerHTML</code>, then transfer it to the desired target. It'll likely be a bit slower though:</p>
<pre><code><script type="text/javascript"><![CDATA[
function parseSVG(s) {
var div= document.createElementNS('http://www.w3.org/1999/xhtml', 'div');
div.innerHTML= '<svg xmlns="http://www.w3.org/2000/svg">'+s+'</svg>';
var frag= document.createDocumentFragment();
while (div.firstChild.firstChild)
frag.appendChild(div.firstChild.firstChild);
return frag;
}
document.getElementById('s').appendChild(parseSVG(
'<circle cx="100" cy="50" r="40" stroke="black" stroke-width="2" fill="red" onmousedown="alert(\'hello\');"/>'
));
]]></script>
</code></pre>
<p>**: I hate the way the authors of HTML5 seem to be scared of XML and determined to shoehorn XML-based features into the crufty mess that is HTML. XHTML solved these problems years ago.</p> | {
"question_id": 3642035,
"question_date": "2010-09-04T11:24:17.620Z",
"question_score": 216,
"tags": "jquery|html|svg",
"answer_id": 3642265,
"answer_date": "2010-09-04T12:26:19.213Z",
"answer_score": 265
} |
Please answer the following Stack Overflow question:
Title: Detecting which UIButton was pressed in a UITableView
<p>I have a <code>UITableView</code> with 5 <code>UITableViewCells</code>. Each cell contains a <code>UIButton</code> which is set up as follows:</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = @"identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
[cell autorelelase];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 40, 20)];
[button addTarget:self action:@selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside];
[button setTag:1];
[cell.contentView addSubview:button];
[button release];
}
UIButton *button = (UIButton *)[cell viewWithTag:1];
[button setTitle:@"Edit" forState:UIControlStateNormal];
return cell;
}
</code></pre>
<p>My question is this: in the <code>buttonPressedAction:</code> method, how do I know which button has been pressed. I've considered using tags but I'm not sure this is the best route. I'd like to be able to somehow tag the <code>indexPath</code> onto the control.</p>
<pre><code>- (void)buttonPressedAction:(id)sender
{
UIButton *button = (UIButton *)sender;
// how do I know which button sent this message?
// processing button press for this row requires an indexPath.
}
</code></pre>
<p>What's the standard way of doing this?</p>
<p><strong>Edit:</strong></p>
<p>I've kinda solved it by doing the following. I would still like to have an opinion whether this is the standard way of doing it or is there a better way?</p>
<pre><code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *identifier = @"identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[UITableView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
[cell autorelelase];
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(10, 5, 40, 20)];
[button addTarget:self action:@selector(buttonPressedAction:) forControlEvents:UIControlEventTouchUpInside];
[cell.contentView addSubview:button];
[button release];
}
UIButton *button = (UIButton *)[cell.contentView.subviews objectAtIndex:0];
[button setTag:indexPath.row];
[button setTitle:@"Edit" forState:UIControlStateNormal];
return cell;
}
- (void)buttonPressedAction:(id)sender
{
UIButton *button = (UIButton *)sender;
int row = button.tag;
}
</code></pre>
<p>What's important to note is that I can't set the tag in the creation of the cell since the cell might be dequeued instead. It feels very dirty. There must be a better way.</p> | <p>In Apple's <a href="http://developer.apple.com/iphone/library/samplecode/Accessory/index.html" rel="noreferrer">Accessory</a> sample the following method is used:</p>
<pre><code>[button addTarget:self action:@selector(checkButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
</code></pre>
<p>Then in touch handler touch coordinate retrieved and index path is calculated from that coordinate: </p>
<pre><code>- (void)checkButtonTapped:(id)sender
{
CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:buttonPosition];
if (indexPath != nil)
{
...
}
}
</code></pre> | {
"question_id": 1802707,
"question_date": "2009-11-26T09:57:01.067Z",
"question_score": 216,
"tags": "ios|iphone|uitableview|uibutton",
"answer_id": 1802875,
"answer_date": "2009-11-26T10:31:52.377Z",
"answer_score": 402
} |
Please answer the following Stack Overflow question:
Title: How do you implement a good profanity filter?
<p>Many of us need to deal with user input, search queries, and situations where the input text can potentially contain profanity or undesirable language. Oftentimes this needs to be filtered out.</p>
<p>Where can one find a good list of swear words in various languages and dialects? </p>
<p>Are there APIs available to sources that contain good lists? Or maybe an API that simply says "yes this is clean" or "no this is dirty" with some parameters?</p>
<p>What are some good methods for catching folks trying to trick the system, like a$$, azz, or a55?</p>
<p>Bonus points if you offer solutions for PHP. :)</p>
<h2><em>Edit: Response to answers that say simply avoid the programmatic issue:</em></h2>
<p>I think there is a place for this kind of filter when, for instance, a user can use public image search to find pictures that get added to a sensitive community pool. If they can search for "penis", then they will likely get many pictures of, yep. If we don't want pictures of that, then preventing the word as a search term is a good gatekeeper, though admittedly not a foolproof method. Getting the list of words in the first place is the real question.</p>
<p>So I'm really referring to a way to figure out of a single token is dirty or not and then simply disallow it. I'd not bother preventing a sentiment like the totally hilarious "long necked giraffe" reference. Nothing you can do there. :)</p> | <p><a href="http://blog.codinghorror.com/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea/" rel="nofollow noreferrer">Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?</a></p>
<p>Also, one can't forget <a href="http://habitatchronicles.com/2007/03/the-untold-history-of-toontowns-speedchat-or-blockchattm-from-disney-finally-arrives/" rel="nofollow noreferrer">The Untold History of Toontown's SpeedChat</a>, where even using a "safe-word whitelist" resulted in a 14-year-old quickly circumventing it with:
<em>"I want to stick my long-necked Giraffe up your fluffy white bunny."</em></p>
<p>Bottom line: Ultimately, for any system that you implement, there is absolutely no substitute for human review (whether peer or otherwise). Feel free to implement a rudimentary tool to get rid of the drive-by's, but for the determined troll, you absolutely must have a non-algorithm-based approach.</p>
<p>A system that removes anonymity and introduces accountability (something that Stack Overflow does well) is helpful also, particularly in order to help combat <a href="http://www.penny-arcade.com/comic/2004/03/19/" rel="nofollow noreferrer">John Gabriel's G.I.F.T.</a></p>
<p>You also asked where you can get profanity lists to get you started -- one open-source project to check out is <a href="http://dansguardian.org" rel="nofollow noreferrer">Dansguardian</a> -- check out the source code for their default profanity lists. There is also an additional third party <a href="http://contentfilter.futuragts.com/phraselists/" rel="nofollow noreferrer">Phrase List</a> that you can download for the proxy that may be a helpful gleaning point for you.</p>
<p><strong>Edit in response to the question edit:</strong> Thanks for the clarification on what you're trying to do. In that case, if you're just trying to do a simple word filter, there are two ways you can do it. One is to create a single long regexp with all of the banned phrases that you want to censor, and merely do a regex find/replace with it. A regex like:</p>
<pre><code>$filterRegex = "(boogers|snot|poop|shucks|argh)"
</code></pre>
<p>and run it on your input string using <a href="http://us.php.net/preg_match" rel="nofollow noreferrer">preg_match()</a> to wholesale test for a hit,</p>
<p>or <a href="http://us.php.net/preg_replace" rel="nofollow noreferrer">preg_replace()</a> to blank them out.</p>
<p>You can also load those functions up with arrays rather than a single long regex, and for long word lists, it may be more manageable. See the <a href="http://us.php.net/preg_replace" rel="nofollow noreferrer">preg_replace()</a> for some good examples as to how arrays can be used flexibly.</p>
<p>For additional PHP programming examples, see this page for a <a href="http://www.bitrepository.com/advanced-word-filter.html" rel="nofollow noreferrer">somewhat advanced generic class</a> for word filtering that *'s out the center letters from censored words, and this <a href="https://stackoverflow.com/questions/24515/bad-words-filter">previous Stack Overflow question</a> that also has a PHP example (the main valuable part in there is the SQL-based filtered word approach -- the leet-speak compensator can be dispensed with if you find it unnecessary).</p>
<p>You also added: "<em>Getting the list of words in the first place is the real question.</em>" -- in addition to some of the previous Dansgaurdian links, you may find <a href="http://urbanoalvarez.es/blog/2008/04/04/bad-words-list/" rel="nofollow noreferrer">this handy .zip</a> of 458 words to be helpful.</p> | {
"question_id": 273516,
"question_date": "2008-11-07T20:19:41.417Z",
"question_score": 216,
"tags": "php|regex|user-input",
"answer_id": 273520,
"answer_date": "2008-11-07T20:21:12.833Z",
"answer_score": 182
} |
Please answer the following Stack Overflow question:
Title: Error: Unable to run mksdcard SDK tool
<p>Keep getting an error in the set-up wizard while trying to install android studio on Ubuntu.</p>
<pre><code>"Unable to run mksdcard SDK tool."
</code></pre>
<p>Also, in the terminal I get this:</p>
<pre><code>[ 115528] ERROR - tRunWizard$SetupProgressStep$1 - Android Studio 1.1.0 Build #AI-135.1740770
[ 115531] ERROR - tRunWizard$SetupProgressStep$1 - JDK: 1.8.0_40
[ 115531] ERROR - tRunWizard$SetupProgressStep$1 - VM: Java HotSpot(TM) 64-Bit Server VM
[ 115531] ERROR - tRunWizard$SetupProgressStep$1 - Vendor: Oracle Corporation
[ 115531] ERROR - tRunWizard$SetupProgressStep$1 - OS: Linux
[ 115532] ERROR - tRunWizard$SetupProgressStep$1 - Last Action:
</code></pre> | <p>This really needs to be added to the documentation, which is why I filed <a href="https://code.google.com/p/android/issues/detail?id=82711" rel="noreferrer">an issue about it</a> a few months ago...</p>
<p>You need some 32-bit binaries, and you have a 64-bit OS version (apparently). Try:</p>
<pre><code>sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6
</code></pre>
<p>That worked for me on Ubuntu 14.10.</p>
<p><strong>UPDATE 2017-12-16</strong>: The details will vary by Linux distro and version. So for example, <a href="https://stackoverflow.com/a/31088492/115145">this answer</a> covers newer Ubuntu versions.</p> | {
"question_id": 29241640,
"question_date": "2015-03-24T19:53:11.917Z",
"question_score": 216,
"tags": "java|android|android-studio",
"answer_id": 29242123,
"answer_date": "2015-03-24T20:20:42.427Z",
"answer_score": 313
} |
Please answer the following Stack Overflow question:
Title: What is the recommended way to install Node.js, nvm and npm on MacOS X?
<p>I am trying to use <a href="https://brew.sh" rel="noreferrer">Homebrew</a> as much as possible. What's the recommended way to install <a href="https://nodejs.org/en/" rel="noreferrer">Node.js</a>, <a href="https://github.com/nvm-sh/nvm" rel="noreferrer"><code>nvm</code></a> and <a href="https://www.npmjs.com" rel="noreferrer">npm</a> on MacOS X?</p> | <ol>
<li><p>Using <code>homebrew</code> install <code>nvm</code>:</p>
<pre><code>brew update
brew install nvm
source $(brew --prefix nvm)/nvm.sh
</code></pre>
<p>Add the last command to the <code>.profile</code>, <code>.bashrc</code> or <code>.zshrc</code> file to not run it again on every terminal start. So for example to add it to the <code>.profile</code> run:</p>
<pre><code>echo "source $(brew --prefix nvm)/nvm.sh" >> ~/.profile
</code></pre>
<p>If you have trouble with installing <code>nvm</code> using <code>brew</code> you can install it manually (see <a href="https://github.com/creationix/nvm#install-script">here</a>)</p></li>
<li><p>Using <code>nvm</code> install <code>node</code> or <code>iojs</code> (you can install any version you want):</p>
<pre><code>nvm install 0.10
# or
nvm install iojs-1.2.0
</code></pre></li>
<li><p><code>npm</code> is shipping with <code>node</code> (or <code>iojs</code>), so it will be available after installing <code>node</code> (or <code>iojs</code>). You may want to upgrade it to the latest version:</p>
<pre><code>$ npm install -g npm@latest
</code></pre>
<p><strong>UPD</strong> Previous version was <s><code>npm update -g npm</code></s>. Thanks to @Metallica for pointing to the correct way (look at the comment bellow).</p></li>
<li><p>Using <code>npm</code> install <code>ionic</code>:</p>
<pre><code>npm install -g ionic
</code></pre></li>
<li><p>What about <code>ngCordova</code>: you can install it using <code>npm</code> or <code>bower</code>. I don't know what variant is more fit for you, it depends on the package manager you want to use for the client side. So I'll describe them both:</p>
<ol>
<li><p><strong>Using <code>npm</code></strong>: Go to your project folder and install <code>ng-cordova</code> in it:</p>
<pre><code>npm install --save ng-cordova
</code></pre></li>
<li><p><strong>Using <code>bower</code></strong>: Install bower:</p>
<pre><code> npm install -g bower
</code></pre>
<p>And then go to your project folder and install <code>ngCordova</code> in it:</p>
<pre><code> bower install --save ngCordova
</code></pre></li>
</ol></li>
</ol>
<p><strong>PS</strong></p>
<ol>
<li>Some commands may require superuser privilege</li>
<li>Short variant of <code>npm install some_module</code> is <code>npm i some_module</code></li>
</ol> | {
"question_id": 28017374,
"question_date": "2015-01-19T03:03:08.297Z",
"question_score": 216,
"tags": "node.js|macos|npm|homebrew|nvm",
"answer_id": 28025834,
"answer_date": "2015-01-19T13:32:34.097Z",
"answer_score": 292
} |
Please answer the following Stack Overflow question:
Title: Parallel.ForEach vs Task.Run and Task.WhenAll
<p>What are the differences between using Parallel.ForEach or Task.Run() to start a set of tasks asynchronously?</p>
<p>Version 1:</p>
<pre><code>List<string> strings = new List<string> { "s1", "s2", "s3" };
Parallel.ForEach(strings, s =>
{
DoSomething(s);
});
</code></pre>
<p>Version 2:</p>
<pre><code>List<string> strings = new List<string> { "s1", "s2", "s3" };
List<Task> Tasks = new List<Task>();
foreach (var s in strings)
{
Tasks.Add(Task.Run(() => DoSomething(s)));
}
await Task.WhenAll(Tasks);
</code></pre> | <p>In this case, the second method will asynchronously wait for the tasks to complete instead of blocking.</p>
<p>However, there is a disadvantage to use <code>Task.Run</code> in a loop- With <code>Parallel.ForEach</code>, there is a <a href="http://msdn.microsoft.com/en-us/library/system.collections.concurrent.partitioner.aspx"><code>Partitioner</code></a> which gets created to avoid making more tasks than necessary. <code>Task.Run</code> will always make a single task per item (since you're doing this), but the <code>Parallel</code> class batches work so you create fewer tasks than total work items. This can provide significantly better overall performance, especially if the loop body has a small amount of work per item.</p>
<p>If this is the case, you can combine both options by writing:</p>
<pre><code>await Task.Run(() => Parallel.ForEach(strings, s =>
{
DoSomething(s);
}));
</code></pre>
<p>Note that this can also be written in this shorter form:</p>
<pre><code>await Task.Run(() => Parallel.ForEach(strings, DoSomething));
</code></pre> | {
"question_id": 19102966,
"question_date": "2013-09-30T20:13:06.960Z",
"question_score": 216,
"tags": "c#|async-await|parallel.foreach",
"answer_id": 19103047,
"answer_date": "2013-09-30T20:17:35.553Z",
"answer_score": 217
} |
Please answer the following Stack Overflow question:
Title: CSS Units - What is the difference between vh/vw and %?
<p>I just learned about a new and uncommon CSS unit. <code>vh</code> and <code>vw</code> measure the percentage of height and width of the viewport respectively.</p>
<p>I looked at this question from Stack Overflow, but it made the units look even more similar.</p>
<p><a href="https://stackoverflow.com/questions/24876368/how-does-vw-and-vh-unit-works">How does vw and vh unit works</a></p>
<p>The answer specifically says</p>
<blockquote>
<p>vw and vh are a percentage of the window width and height,
respectively: 100vw is 100% of the width, 80vw is 80%, etc.</p>
</blockquote>
<p>This seems like the exact same as the <code>%</code> unit, which is more common.</p>
<p>In Developer Tools, I tried changing the values from vw/vh to % and viceversa and got the same result.</p>
<p>Is there a difference between the two? If not, why were these new units introduced to <code>CSS3</code>?</p> | <p><code>100%</code> can be <code>100%</code> of the height of anything. For example, if I have a parent <code>div</code> that's <code>1000px</code> tall, and a child <code>div</code> that is at <code>100%</code> height, then that child <code>div</code> could theoretically be much taller than the height of the viewport, or much smaller than the height of the viewport, <em>even though that <code>div</code> is set at <code>100%</code> height</em>.</p>
<p>If I instead make that child <code>div</code> set at <code>100vh</code>, then it'll <em>only fill up <code>100%</code> of the height of the viewport</em>, and not necessarily the parent <code>div</code>.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>body,
html {
height: 100%;
}
.parent {
background: lightblue;
float: left;
height: 200px;
padding: 10px;
width: 50px;
}
.child {
background: pink;
height: 100%;
width: 100%;
}
.viewport-height {
background: gray;
float: right;
height: 100vh;
width: 50px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="parent">
<div class="child">
100% height
(parent is 200px)
</div>
</div>
<div class="viewport-height">
100vh height
</div></code></pre>
</div>
</div>
</p> | {
"question_id": 31039979,
"question_date": "2015-06-25T01:58:43.843Z",
"question_score": 216,
"tags": "css|viewport-units",
"answer_id": 31040007,
"answer_date": "2015-06-25T02:02:00.560Z",
"answer_score": 245
} |
Please answer the following Stack Overflow question:
Title: How to compare Lists in Unit Testing
<p>How can this test fail?</p>
<pre class="lang-cs prettyprint-override"><code>[TestMethod]
public void Get_Code()
{
var expected = new List<int>();
expected.AddRange(new [] { 100, 400, 200, 900, 2300, 1900 });
var actual = new List<int>();
actual.AddRange(new [] { 100, 400, 200, 900, 2300, 1900 });
Assert.AreEqual(expected, actual);
// Assert.AreSame(expected, actual) fails
// Assert.IsTrue(expected.Equals(actual)) fails
}
</code></pre> | <p>To make assertions about collections, you should use <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.collectionassert.aspx" rel="noreferrer"><code>CollectionAssert</code></a>:</p>
<pre><code>CollectionAssert.AreEqual(expected, actual);
</code></pre>
<p><code>List<T></code> doesn't override <code>Equals</code>, so if <code>Assert.AreEqual</code> just calls <code>Equals</code>, it will end up using reference equality.</p> | {
"question_id": 11055632,
"question_date": "2012-06-15T17:39:39.250Z",
"question_score": 216,
"tags": "c#|visual-studio-2010|unit-testing|mstest",
"answer_id": 11055686,
"answer_date": "2012-06-15T17:43:20.827Z",
"answer_score": 435
} |
Please answer the following Stack Overflow question:
Title: Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?
<p>From the <em>Immediate Window</em> in Visual Studio: </p>
<pre><code>> Path.Combine(@"C:\x", "y")
"C:\\x\\y"
> Path.Combine(@"C:\x", @"\y")
"\\y"
</code></pre>
<p>It seems that they should both be the same. </p>
<p>The old FileSystemObject.BuildPath() didn't work this way...</p> | <p>This is kind of a philosophical question (which perhaps only Microsoft can truly answer), since it's doing exactly what the documentation says.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx" rel="noreferrer">System.IO.Path.Combine</a></p>
<p>"If path2 contains an absolute path, this method returns path2."</p>
<p><a href="http://referencesource.microsoft.com/#mscorlib/system/io/path.cs,2d7263f86a526264" rel="noreferrer">Here's the actual Combine method</a> from the .NET source. You can see that it calls <a href="http://referencesource.microsoft.com/mscorlib/system/io/path.cs.html#16ed6da326ce4745" rel="noreferrer">CombineNoChecks</a>, which then calls <a href="http://referencesource.microsoft.com/mscorlib/system/io/path.cs.html#807960f08fca497d" rel="noreferrer">IsPathRooted</a> on path2 and returns that path if so:</p>
<pre><code>public static String Combine(String path1, String path2) {
if (path1==null || path2==null)
throw new ArgumentNullException((path1==null) ? "path1" : "path2");
Contract.EndContractBlock();
CheckInvalidPathChars(path1);
CheckInvalidPathChars(path2);
return CombineNoChecks(path1, path2);
}
internal static string CombineNoChecks(string path1, string path2)
{
if (path2.Length == 0)
return path1;
if (path1.Length == 0)
return path2;
if (IsPathRooted(path2))
return path2;
char ch = path1[path1.Length - 1];
if (ch != DirectorySeparatorChar && ch != AltDirectorySeparatorChar &&
ch != VolumeSeparatorChar)
return path1 + DirectorySeparatorCharAsString + path2;
return path1 + path2;
}
</code></pre>
<p>I don't know what the rationale is. I guess the solution is to strip off (or Trim) DirectorySeparatorChar from the beginning of the second path; maybe write your own Combine method that does that and then calls Path.Combine().</p> | {
"question_id": 53102,
"question_date": "2008-09-09T23:05:06.553Z",
"question_score": 216,
"tags": "c#|.net|file",
"answer_id": 53118,
"answer_date": "2008-09-09T23:16:02.253Z",
"answer_score": 232
} |
Please answer the following Stack Overflow question:
Title: Load multiple packages at once
<p>How can I load a bunch of packages at once with out retyping the require command over and over? I've tried three approaches all of which crash and burn.</p>
<p>Basically, I want to supply a vector of package names to a function that will load them.</p>
<pre><code>x<-c("plyr", "psych", "tm")
require(x)
lapply(x, require)
do.call("require", x)
</code></pre> | <p>Several permutations of your proposed functions do work -- but only if you specify the <code>character.only</code> argument to be <code>TRUE</code>. Quick example:</p>
<pre><code>lapply(x, require, character.only = TRUE)
</code></pre> | {
"question_id": 8175912,
"question_date": "2011-11-17T23:36:23.847Z",
"question_score": 216,
"tags": "r|package",
"answer_id": 8176099,
"answer_date": "2011-11-17T23:57:09.407Z",
"answer_score": 301
} |
Please answer the following Stack Overflow question:
Title: Bulk package updates using Conda
<p>Is there a way (using conda update) that I can list outdated packages and select or bulk update (compatible) packages in Anaconda?</p>
<p>It doesn't make much sense updating the packages individually as there are hundreds of them.</p> | <p>You want <code>conda update --all</code>.</p>
<p><code>conda search --outdated</code> will show outdated packages, and <code>conda update --all</code> will update them (note that the latter will not update you from Python 2 to Python 3, but the former will show Python as being outdated if you do use Python 2). </p> | {
"question_id": 24958833,
"question_date": "2014-07-25T15:06:50.353Z",
"question_score": 216,
"tags": "python|anaconda|conda",
"answer_id": 24965191,
"answer_date": "2014-07-25T22:05:17.467Z",
"answer_score": 357
} |
Please answer the following Stack Overflow question:
Title: How do I use a compound drawable instead of a LinearLayout that contains an ImageView and a TextView
<p>Ran the new Lint tool against my code. It came up with a lot of good suggestions, but this one I cannot understand.</p>
<blockquote>
<p>This tag and its children can be replaced by one and a compound drawable</p>
<p>Issue: Checks whether the current node can be replaced by a TextView using compound drawables.</p>
<p>A LinearLayout which contains an ImageView and a TextView can be more efficiently handled as a compound drawable</p>
</blockquote>
<p>And here is my layout</p>
<pre><code><LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_centerInParent="true">
<ImageView
android:id="@+id/upImage"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="center_vertical"
android:scaleType="centerInside"
android:src="@drawable/up_count_big">
</ImageView>
<TextView
android:id="@+id/LikeCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="2dp"
android:layout_marginBottom="1dp"
android:textColor="@color/gray"
android:textSize="16sp"
android:layout_gravity="center_vertical">
</TextView>
</LinearLayout>
</code></pre>
<p>Can someone provide a concrete example of how to make a compound drawable in this case?</p> | <p><code>TextView</code> comes with 4 compound drawables, one for each of left, top, right and bottom.</p>
<p>In your case, you do not need the <code>LinearLayout</code> and <code>ImageView</code> at all. Just add <code>android:drawableLeft="@drawable/up_count_big"</code> to your <code>TextView</code>.</p>
<p>See <a href="http://developer.android.com/reference/android/widget/TextView.html#setCompoundDrawablesWithIntrinsicBounds(int,%20int,%20int,%20int)" rel="noreferrer">TextView#setCompoundDrawablesWithIntrinsicBounds</a> for more info.</p> | {
"question_id": 8318765,
"question_date": "2011-11-29T22:39:03.813Z",
"question_score": 216,
"tags": "android|android-layout|android-linearlayout|textview|compound-drawables",
"answer_id": 8319158,
"answer_date": "2011-11-29T23:20:01.517Z",
"answer_score": 284
} |
Please answer the following Stack Overflow question:
Title: How do I raise a Response Forbidden in django
<p>I'd like to do the following:</p>
<pre><code>raise HttpResponseForbidden()
</code></pre>
<p>But I get the error:</p>
<pre><code>exceptions must be old-style classes or derived from BaseException, not HttpResponseForbidden
</code></pre>
<p>How should I do this?</p> | <p>Return it from the view as you would any other response.</p>
<pre><code>from django.http import HttpResponseForbidden
return HttpResponseForbidden()
</code></pre> | {
"question_id": 6618939,
"question_date": "2011-07-08T01:16:20.937Z",
"question_score": 216,
"tags": "django",
"answer_id": 6618964,
"answer_date": "2011-07-08T01:20:54.223Z",
"answer_score": 213
} |
Please answer the following Stack Overflow question:
Title: How to Animate Addition or Removal of Android ListView Rows
<p>In iOS, there is a very easy and powerful facility to animate the addition and removal of UITableView rows, <a href="http://www.youtube.com/watch?v=VhSWE6_ieyA#t=1m10s" rel="noreferrer">here's a clip from a youtube video</a> showing the default animation. Note how the surrounding rows collapse onto the deleted row. This animation helps users keep track of what changed in a list and where in the list they were looking at when the data changed.</p>
<p>Since I've been developing on Android I've found no equivalent facility to animate individual rows in a <a href="http://developer.android.com/reference/android/widget/ListView.html" rel="noreferrer">TableView</a>. Calling <a href="http://developer.android.com/reference/android/widget/BaseAdapter.html#notifyDataSetChanged()" rel="noreferrer"><code>notifyDataSetChanged()</code></a> on my Adapter causes the ListView to immediately update its content with new information. I'd like to show a simple animation of a new row pushing in or sliding out when the data changes, but I can't find any documented way to do this. It looks like <a href="http://LayoutAnimationController" rel="noreferrer">LayoutAnimationController</a> might hold a key to getting this to work, but when I set a LayoutAnimationController on my ListView (similar to <a href="http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/LayoutAnimation2.html" rel="noreferrer">ApiDemo's LayoutAnimation2</a>) and remove elements from my adapter after the list has displayed, the elements disappear immediately instead of getting animated out.</p>
<p>I've also tried things like the following to animate an individual item when it is removed:</p>
<pre><code>@Override
protected void onListItemClick(ListView l, View v, final int position, long id) {
Animation animation = new ScaleAnimation(1, 1, 1, 0);
animation.setDuration(100);
getListView().getChildAt(position).startAnimation(animation);
l.postDelayed(new Runnable() {
public void run() {
mStringList.remove(position);
mAdapter.notifyDataSetChanged();
}
}, 100);
}
</code></pre>
<p>However, the rows surrounding the animated row don't move position until they jump to their new positions when <code>notifyDataSetChanged()</code> is called. It appears ListView doesn't update its layout once its elements have been placed.</p>
<p>While writing my own implementation/fork of ListView has crossed my mind, this seems like something that shouldn't be so difficult.</p>
<p>Thanks!</p> | <pre><code>Animation anim = AnimationUtils.loadAnimation(
GoTransitApp.this, android.R.anim.slide_out_right
);
anim.setDuration(500);
listView.getChildAt(index).startAnimation(anim );
new Handler().postDelayed(new Runnable() {
public void run() {
FavouritesManager.getInstance().remove(
FavouritesManager.getInstance().getTripManagerAtIndex(index)
);
populateList();
adapter.notifyDataSetChanged();
}
}, anim.getDuration());
</code></pre>
<p>for top-to-down animation use :</p>
<pre><code><set xmlns:android="http://schemas.android.com/apk/res/android">
<translate android:fromYDelta="20%p" android:toYDelta="-20"
android:duration="@android:integer/config_mediumAnimTime"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0"
android:duration="@android:integer/config_mediumAnimTime" />
</set>
</code></pre> | {
"question_id": 3928193,
"question_date": "2010-10-13T21:29:01.617Z",
"question_score": 216,
"tags": "android|listview|animation",
"answer_id": 6857762,
"answer_date": "2011-07-28T10:51:11.927Z",
"answer_score": 127
} |
Please answer the following Stack Overflow question:
Title: What does it mean by buffer?
<p>I see the word <strong>"BUFFER"</strong> everywhere, but I am unable to grasp what it exactly is.</p>
<ol>
<li>Would anybody please explain what is buffer in <strong>layman's language</strong>?</li>
<li>When is it used?</li>
<li>How is it used?</li>
</ol> | <p>Imagine that you're eating candy out of a bowl. You take one piece regularly. To prevent the bowl from running out, someone might refill the bowl before it gets empty, so that when you want to take another piece, there's candy in the bowl. </p>
<p>The bowl acts as a buffer between you and the candy bag.</p>
<p>If you're watching a movie online, the web service will continually download the next 5 minutes or so into a buffer, that way your computer doesn't have to download the movie as you're watching it (which would cause hanging).</p> | {
"question_id": 648309,
"question_date": "2009-03-15T18:43:52.097Z",
"question_score": 216,
"tags": "buffer|terminology",
"answer_id": 648324,
"answer_date": "2009-03-15T18:50:03.657Z",
"answer_score": 403
} |
Please answer the following Stack Overflow question:
Title: Preserve HTML font-size when iPhone orientation changes from portrait to landscape
<p>I have a mobile web application with an unordered list containing multiple items with a hyperlink inside each <code>li</code>:</p>
<p>My question is: how can I format the hyperlinks so that they DON'T change size when viewed on an iPhone, and the accelerometer switches from portrait to landscape?</p>
<p>In portrait mode, I have the hyperlink font size set at <code>14px</code>, but when I switch the device to landscape, it blows way up to <code>20px</code>.</p>
<p>I would like the font-size to stay the same.</p>
<p>Here is the example code:</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>ul li a {
font-size:14px;
text-decoration: none;
color: #cc9999;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
<li id="home" class="active">
<a href="home.html">HOME</a>
</li>
<li id="home" class="active">
<a href="test.html">TEST</a>
</li>
</ul></code></pre>
</div>
</div>
</p> | <p>You can disable this behavior through the <code>-webkit-text-size-adjust</code> CSS property:</p>
<pre><code>html {
-webkit-text-size-adjust: 100%; /* Prevent font scaling in landscape while allowing user zoom */
}
</code></pre>
<p>The use of this property is described further in the <a href="https://developer.apple.com/library/content/documentation/AppleApplications/Reference/SafariWebContent/AdjustingtheTextSize/AdjustingtheTextSize.html#//apple_ref/doc/uid/TP40006510-SW16" rel="noreferrer">Safari Web Content Guide</a>.</p> | {
"question_id": 2710764,
"question_date": "2010-04-26T02:16:37.090Z",
"question_score": 216,
"tags": "iphone|html|css",
"answer_id": 2711132,
"answer_date": "2010-04-26T04:18:06.130Z",
"answer_score": 464
} |
Please answer the following Stack Overflow question:
Title: Why do you need explicitly have the "self" argument in a Python method?
<p>When defining a method on a class in Python, it looks something like this:</p>
<pre><code>class MyClass(object):
def __init__(self, x, y):
self.x = x
self.y = y
</code></pre>
<p>But in some other languages, such as C#, you have a reference to the object that the method is bound to with the "this" keyword without declaring it as an argument in the method prototype. </p>
<p>Was this an intentional language design decision in Python or are there some implementation details that require the passing of "self" as an argument?</p> | <p>I like to quote Peters' Zen of Python. "Explicit is better than implicit."</p>
<p>In Java and C++, '<code>this.</code>' can be deduced, except when you have variable names that make it impossible to deduce. So you sometimes need it and sometimes don't.</p>
<p>Python elects to make things like this explicit rather than based on a rule. </p>
<p>Additionally, since nothing is implied or assumed, parts of the implementation are exposed. <code>self.__class__</code>, <code>self.__dict__</code> and other "internal" structures are available in an obvious way.</p> | {
"question_id": 68282,
"question_date": "2008-09-16T00:39:55.150Z",
"question_score": 216,
"tags": "python|oop|methods|self",
"answer_id": 68324,
"answer_date": "2008-09-16T00:47:55.133Z",
"answer_score": 96
} |
Please answer the following Stack Overflow question:
Title: + operator for array in PHP?
<pre><code>$test = array('hi');
$test += array('test','oh');
var_dump($test);
</code></pre>
<p>What does <code>+</code> mean for array in PHP?</p> | <p>Quoting from the <a href="http://php.net/manual/en/language.operators.array.php" rel="noreferrer">PHP Manual on Language Operators</a></p>
<blockquote>
<p>The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored. </p>
</blockquote>
<p>So if you do</p>
<pre><code>$array1 = ['one', 'two', 'foo' => 'bar'];
$array2 = ['three', 'four', 'five', 'foo' => 'baz'];
print_r($array1 + $array2);
</code></pre>
<p>You will get</p>
<pre><code>Array
(
[0] => one // preserved from $array1 (left-hand array)
[1] => two // preserved from $array1 (left-hand array)
[foo] => bar // preserved from $array1 (left-hand array)
[2] => five // added from $array2 (right-hand array)
)
</code></pre>
<p>So the logic of <code>+</code> is equivalent to the following snippet:</p>
<pre><code>$union = $array1;
foreach ($array2 as $key => $value) {
if (false === array_key_exists($key, $union)) {
$union[$key] = $value;
}
}
</code></pre>
<p>If you are interested in the details of the C-level implementation head to </p>
<ul>
<li>php-src/Zend/<a href="https://github.com/php/php-src/blob/master/Zend/zend_operators.c" rel="noreferrer">zend_operators.c</a></li>
</ul>
<hr>
<p>Note, that <code>+</code> is different from how <a href="http://php.net/manual/en/function.array-merge.php" rel="noreferrer"><code>array_merge()</code></a> would combine the arrays:</p>
<pre><code>print_r(array_merge($array1, $array2));
</code></pre>
<p>would give you</p>
<pre><code>Array
(
[0] => one // preserved from $array1
[1] => two // preserved from $array1
[foo] => baz // overwritten from $array2
[2] => three // appended from $array2
[3] => four // appended from $array2
[4] => five // appended from $array2
)
</code></pre>
<p>See linked pages for more examples.</p> | {
"question_id": 2140090,
"question_date": "2010-01-26T14:46:17.823Z",
"question_score": 216,
"tags": "php|arrays",
"answer_id": 2140094,
"answer_date": "2010-01-26T14:47:03.863Z",
"answer_score": 300
} |
Please answer the following Stack Overflow question:
Title: How is set() implemented?
<p>I've seen people say that <code>set</code> objects in python have O(1) membership-checking. How are they implemented internally to allow this? What sort of data structure does it use? What other implications does that implementation have?</p>
<p>Every answer here was really enlightening, but I can only accept one, so I'll go with the closest answer to my original question. Thanks all for the info!</p> | <p>According to <a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/e3e9dfdb5cbe33c8/83361c0f975add77?lnk=raot&pli=1" rel="noreferrer">this thread</a>:</p>
<blockquote>
<p>Indeed, CPython's sets are implemented as something like dictionaries
with dummy values (the keys being the members of the set), with some
optimization(s) that exploit this lack of values</p>
</blockquote>
<p>So basically a <code>set</code> uses a hashtable as its underlying data structure. This explains the <code>O(1)</code> membership checking, since looking up an item in a hashtable is an <code>O(1)</code> operation, on average.</p>
<p>If you are so inclined you can even browse the <a href="https://github.com/python/cpython/blob/main/Objects/setobject.c" rel="noreferrer">CPython source code for <code>set</code></a> which, according to <a href="http://markmail.org/message/ktzomp4uwrmnzao6" rel="noreferrer">Achim Domma</a>, was <em>originally</em> mostly a cut-and-paste from the <code>dict</code> implementation.</p>
<p>Note: Nowadays, <code>set</code> and <code>dict</code>'s implementations have diverged <em>significantly</em>, so the precise behaviors (e.g. arbitrary order vs. insertion order) and performance in various use cases differs; they're still implemented in terms of hashtables, so average case lookup and insertion remains <code>O(1)</code>, but <code>set</code> is no longer just "<code>dict</code>, but with dummy/omitted keys".</p> | {
"question_id": 3949310,
"question_date": "2010-10-16T14:39:00.887Z",
"question_score": 216,
"tags": "python|data-structures|set|cpython",
"answer_id": 3949350,
"answer_date": "2010-10-16T14:47:43.110Z",
"answer_score": 200
} |
Please answer the following Stack Overflow question:
Title: How to delete a property from Google Analytics
<p>I want to delete a test property from Google Analytics, but there is no delete option on the property page. Does anyone know how to delete a property from Google Analytics? </p> | <p><strong>UPDATE/EDIT – December 5, 2014</strong> : Converted this to community wiki… feel invited to edit and update.</p>
<hr>
<p><strong>UPDATE/EDIT – AUGUST 1, 2014</strong> </p>
<p>Google has done it again… they changed the design. But they also made things a bit simpler and more logic. Go to <code>Administration → Property Settings</code> and look for the <code>Delete Property</code> link at the right-bottom of the page. Click that link to delete the property.</p>
<p>Here’s a schreenshot of the current (2014-08-01) interface, pointing to the link you’re looking for… </p>
<blockquote>
<p><img src="https://i.stack.imgur.com/9ohVQ.jpg" alt="screenshot"></p>
</blockquote>
<p>Note that the RGB noise is not part of the Google design. I added that to protect personal information. ;)</p>
<hr>
<h1>Stop reading here…</h1>
<p>What follows was my original answer, which has been rendered obsolete by Google’s design update on 2014-08-01. For potential reference purposes, I’ve decided to not yet remove that outdated info…</p>
<hr>
<p>Google decided to move that feature into the <code>View Settings</code>. To find it, go to the "View Settings" in your Admin area…</p>
<blockquote>
<p><img src="https://i.stack.imgur.com/bfnn5.png" alt="Step 1"></p>
</blockquote>
<p>Then click the link to delete it…</p>
<blockquote>
<p><img src="https://i.stack.imgur.com/thIuq.png" alt="Step 2"></p>
</blockquote> | {
"question_id": 17692636,
"question_date": "2013-07-17T06:28:07.320Z",
"question_score": 216,
"tags": "google-analytics",
"answer_id": 18815094,
"answer_date": "2013-09-15T17:07:57.157Z",
"answer_score": 376
} |
Please answer the following Stack Overflow question:
Title: How to attach file to a github issue?
<p>I migrated with a project from Bitbucket to Github and I can not find a way to attach a file to an issue (ex: screenshot, specs, etc)</p>
<p>How to do it? </p> | <p><s>You upload it somewhere and add the link in a comment. GitHub's Issues is rather primitive and doesn't allow attaching files.</s></p>
<p><strong>Update:</strong> You can post images to GitHub issues now. The easiest way is to copy the image (right click, Copy image) and then paste it into the text box where you describe the issue.</p>
<p><em>OR</em></p>
<p>Just drag and drop</p> | {
"question_id": 10963205,
"question_date": "2012-06-09T17:47:14.260Z",
"question_score": 216,
"tags": "github|attachment|github-issues",
"answer_id": 10963250,
"answer_date": "2012-06-09T17:53:51.910Z",
"answer_score": 243
} |
Please answer the following Stack Overflow question:
Title: disable maven download progress indication
<p>In our company in the CI machines maven local repository is purged before every build. As result my build logs always have a bunch of noise like this</p>
<pre><code>Downloading: http://.../artifactory/repo/com/codahale/metrics/metrics-core/3.0.1/metrics-core-3.0.1.jar
4/2122 KB
8/2122 KB
12/2122 KB
16/2122 KB
18/2122 KB
18/2122 KB 4/480 KB
18/2122 KB 8/480 KB
18/2122 KB 12/480 KB
18/2122 KB 16/480 KB
18/2122 KB 16/480 KB 4/1181 KB
18/2122 KB 16/480 KB 8/1181 KB
18/2122 KB 16/480 KB 12/1181 KB
</code></pre>
<p>Is there an option I to be able to disable the download progress indication?</p> | <p><code>mvn -B ..</code> or <code>mvn --batch-mode ...</code> will do the trick.</p>
<p><em>Update</em></p>
<ul>
<li>The documentation about batch mode see <a href="https://maven.apache.org/ref/3.6.1/maven-embedder/cli.html" rel="noreferrer">https://maven.apache.org/ref/3.6.1/maven-embedder/cli.html</a> </li>
<li>Starting with Maven 3.6.1 (released 2019-04-04) you can use <code>--no-transfer-progress</code> will suppress the output of downloading messages at all without suppressing the other output.</li>
</ul> | {
"question_id": 21638697,
"question_date": "2014-02-07T22:09:24.987Z",
"question_score": 216,
"tags": "maven",
"answer_id": 21638827,
"answer_date": "2014-02-07T22:19:18.930Z",
"answer_score": 278
} |
Please answer the following Stack Overflow question:
Title: Django: "projects" vs "apps"
<p>I have a fairly complex "product" I'm getting ready to build using Django. I'm going to avoid using the terms "project" and "application" in this context, because I'm not clear on their specific meaning in Django.</p>
<p>Projects can have many apps. Apps can be shared among many projects. Fine.</p>
<p>I'm not reinventing the blog or forum - I don't see any portion of my product being reusable in any context. Intuitively, I would call this one "application." Do I then do all my work in a single "app" folder?</p>
<p><em>If so</em>... in terms of Django's <code>project.app</code> namespace, my inclination is to use <code>myproduct.myproduct</code>, but of course this isn't allowed (but the application I'm building is my project, and my project is an application!). I'm therefore lead to believe that perhaps I'm supposed to approach Django by building one app per "significant" model, but I don't know where to draw the boundaries in my schema to separate it into apps - I have a lot of models with relatively complex relationships.</p>
<p>I'm hoping there's a common solution to this...</p> | <p>What is to stop you using <code>myproduct.myproduct</code>? What you need to achieve that roughly consists of doing this:</p>
<pre><code>django-admin.py startproject myproduct
cd myproduct
mkdir myproduct
touch myproduct/__init__.py
touch myproduct/models.py
touch myproduct/views.py
</code></pre>
<p>and so on. Would it help if I said <code>views.py</code> doesn't have to be called <code>views.py</code>? Provided you can name, on the python path, a function (usually package.package.views.function_name) it will get handled. Simple as that. All this "project"/"app" stuff is just python packages.</p>
<p>Now, how are you supposed to do it? Or rather, how might I do it? Well, if you create a significant piece of reusable functionality, like say a markup editor, that's when you create a "top level app" which might contain <code>widgets.py</code>, <code>fields.py</code>, <code>context_processors.py</code> etc - all things you might want to import.</p>
<p>Similarly, if you can create something like a blog in a format that is pretty generic across installs, you can wrap it up in an app, with its own template, static content folder etc, and configure an instance of a django project to use that app's content.</p>
<p>There are no hard and fast rules saying you must do this, but it is one of the goals of the framework. The fact that everything, templates included, allows you to include from some common base means your blog should fit snugly into any other setup, simply by looking after its own part.</p>
<p>However, to address your actual concern, yes, nothing says you can't work with the top level project folder. <em>That's what apps do</em> and you can do it if you really want to. I tend not to, however, for several reasons:</p>
<ul>
<li>Django's default setup doesn't do it.</li>
<li>Often, I want to create a main app, so I create one, usually called <code>website</code>. However, at a later date I might want to develop original functionality just for this site. With a view to making it removable (whether or not I ever do) I tend to then create a separate directory. This also means I can drop said functionality just by unlinking that package from the config and removing the folder, rather than a complex delete the right urls from a global urls.py folder.</li>
<li>Very often, even when I want to make something independent, it needs somewhere to live whilst I look after it / make it independent. Basically the above case, but for stuff I do intend to make generic.</li>
<li>My top level folder often contains a few other things, including but not limited to wsgi scripts, sql scripts etc.</li>
<li>django's <a href="http://docs.djangoproject.com/en/1.2/howto/custom-management-commands/">management extensions</a> rely on subdirectories. So it makes sense to name packages appropriately.</li>
</ul>
<p>In short, the reason there is a convention is the same as any other convention - it helps when it comes to others working with your project. If I see <code>fields.py</code> I immediately expect code in it to subclass django's field, whereas if I see <code>inputtypes.py</code> I might not be so clear on what that means without looking at it.</p> | {
"question_id": 4879036,
"question_date": "2011-02-02T19:41:49.830Z",
"question_score": 216,
"tags": "python|django|namespaces|project-organization",
"answer_id": 4879205,
"answer_date": "2011-02-02T19:58:21.073Z",
"answer_score": 58
} |
Please answer the following Stack Overflow question:
Title: How do I skip a match when using Ctrl+D for multiple selections in Sublime Text 2?
<p>I have some code like:</p>
<pre><code>testVar = { a: 1 };
testVariable1 = 2;
var c = testVar.a + testVariable2;
var d = testVar;
</code></pre>
<p>I want to rename "testVar" variable. When I set multiple cursors with <kbd>Ctrl</kbd>+<kbd>D</kbd> and edit variable, "testVariable" is also selected and edited. </p>
<p>Is there a way to skip some selections while setting multiple cursors with <kbd>Ctrl</kbd>+<kbd>D</kbd>?</p> | <p>Just use <kbd>Ctrl</kbd>+<kbd>K</kbd>, <kbd>Ctrl</kbd>+<kbd>D</kbd>.</p>
<p>(for OS X: <kbd>Cmd</kbd>+<kbd>K</kbd>, <kbd>Cmd</kbd>+<kbd>D</kbd>)</p>
<p>Needs a bit of practice, but gets the job done!</p> | {
"question_id": 11548308,
"question_date": "2012-07-18T18:49:31.970Z",
"question_score": 216,
"tags": "windows|sublimetext2",
"answer_id": 11549737,
"answer_date": "2012-07-18T20:27:23.433Z",
"answer_score": 300
} |
Please answer the following Stack Overflow question:
Title: How to prevent ifelse() from turning Date objects into numeric objects
<p>I am using the function <code>ifelse()</code> to manipulate a date vector. I expected the result to be of class <code>Date</code>, and was surprised to get a <code>numeric</code> vector instead. Here is an example:</p>
<pre><code>dates <- as.Date(c('2011-01-01', '2011-01-02', '2011-01-03', '2011-01-04', '2011-01-05'))
dates <- ifelse(dates == '2011-01-01', dates - 1, dates)
str(dates)
</code></pre>
<p>This is especially surprising because performing the operation across the entire vector returns a <code>Date</code> object.</p>
<pre><code>dates <- as.Date(c('2011-01-01', '2011-01-02', '2011-01-03', '2011-01-04','2011-01-05'))
dates <- dates - 1
str(dates)
</code></pre>
<p>Should I be using some other function to operate on <code>Date</code> vectors? If so, what function? If not, how do I force <code>ifelse</code> to return a vector of the same type as the input?</p>
<p>The help page for <code>ifelse</code> indicates that this is a feature, not a bug, but I'm still struggling to find an explanation for what I found to be surprising behavior.</p> | <p>You may use <code>data.table::fifelse</code> (<code>data.table >= 1.12.3</code>) or <code>dplyr::if_else</code>.</p>
<hr />
<h3><code>data.table::fifelse</code></h3>
<blockquote>
<p>Unlike <code>ifelse</code>, <code>fifelse</code> preserves the type and class of the inputs.</p>
</blockquote>
<pre><code>library(data.table)
dates <- fifelse(dates == '2011-01-01', dates - 1, dates)
str(dates)
# Date[1:5], format: "2010-12-31" "2011-01-02" "2011-01-03" "2011-01-04" "2011-01-05"
</code></pre>
<hr />
<h3><code>dplyr::if_else</code></h3>
<p>From <a href="https://blog.rstudio.org/2016/06/27/dplyr-0-5-0/" rel="noreferrer"><code>dplyr 0.5.0</code> release notes</a>:</p>
<blockquote>
<p>[<code>if_else</code>] have stricter semantics that <code>ifelse()</code>: the <code>true</code> and <code>false</code> arguments must be the same type. This gives a less surprising return type, and preserves S3 vectors like <em>dates</em>" .</p>
</blockquote>
<pre><code>library(dplyr)
dates <- if_else(dates == '2011-01-01', dates - 1, dates)
str(dates)
# Date[1:5], format: "2010-12-31" "2011-01-02" "2011-01-03" "2011-01-04" "2011-01-05"
</code></pre> | {
"question_id": 6668963,
"question_date": "2011-07-12T18:11:16.147Z",
"question_score": 216,
"tags": "r|date|datetime|if-statement",
"answer_id": 38093096,
"answer_date": "2016-06-29T07:31:35.690Z",
"answer_score": 179
} |
Please answer the following Stack Overflow question:
Title: iPad keyboard will not dismiss if modal ViewController presentation style is UIModalPresentationFormSheet
<p><strong>Note:</strong> </p>
<p>See accepted answer (not top voted one) for solution as of iOS 4.3.</p>
<p>This <strong>question</strong> is about a behavior discovered in the iPad keyboard, where it refuses to be dismissed if shown in a modal dialog with a navigation controller. </p>
<p>Basically, if I present the navigation controller with the following line as below:</p>
<pre><code>navigationController.modalPresentationStyle = UIModalPresentationFormSheet;
</code></pre>
<p>The keyboard refuses to be dismissed. If I comment out this line, the keyboard goes away fine. </p>
<p>...</p>
<p>I've got two textFields, username and password; username has a Next button and password has a Done button. The keyboard won't go away if I present this in a modal navigation controller.</p>
<p><strong>WORKS</strong></p>
<pre><code>broken *b = [[broken alloc] initWithNibName:@"broken" bundle:nil];
[self.view addSubview:b.view];
</code></pre>
<p><strong>DOES NOT WORK</strong></p>
<pre><code>broken *b = [[broken alloc] initWithNibName:@"broken" bundle:nil];
UINavigationController *navigationController =
[[UINavigationController alloc]
initWithRootViewController:b];
navigationController.modalPresentationStyle = UIModalPresentationFormSheet;
navigationController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:navigationController animated:YES];
[navigationController release];
[b release];
</code></pre>
<p>If I remove the navigation controller part and present 'b' as a modal view controller by itself, it works. Is the navigation controller the problem?</p>
<p><strong>WORKS</strong></p>
<pre><code>broken *b = [[broken alloc] initWithNibName:@"broken" bundle:nil];
b.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:b animated:YES];
[b release];
</code></pre>
<p><strong>WORKS</strong></p>
<pre><code>broken *b = [[broken alloc] initWithNibName:@"broken" bundle:nil];
UINavigationController *navigationController =
[[UINavigationController alloc]
initWithRootViewController:b];
[self presentModalViewController:navigationController animated:YES];
[navigationController release];
[b release];
</code></pre> | <p>In the view controller that is presented modally, just override <code>disablesAutomaticKeyboardDismissal</code> to return <code>NO</code>:</p>
<pre class="lang-c prettyprint-override"><code>- (BOOL)disablesAutomaticKeyboardDismissal {
return NO;
}
</code></pre> | {
"question_id": 3372333,
"question_date": "2010-07-30T14:17:55.573Z",
"question_score": 216,
"tags": "ios|iphone|objective-c|uitextfield|first-responder",
"answer_id": 5503637,
"answer_date": "2011-03-31T17:12:58.900Z",
"answer_score": 117
} |
Please answer the following Stack Overflow question:
Title: In SQL, what's the difference between count(column) and count(*)?
<p>I have the following query:</p>
<pre><code>select column_name, count(column_name)
from table
group by column_name
having count(column_name) > 1;
</code></pre>
<p>What would be the difference if I replaced all calls to <code>count(column_name)</code> to <code>count(*)</code>?</p>
<p>This question was inspired by <a href="https://stackoverflow.com/questions/59232/how-do-i-find-duplicate-values-in-a-table-in-oracle">How do I find duplicate values in a table in Oracle?</a>.</p>
<hr>
<p>To clarify the accepted answer (and maybe my question), replacing <code>count(column_name)</code> with <code>count(*)</code> would return an extra row in the result that contains a <code>null</code> and the count of <code>null</code> values in the column.</p> | <p><code>count(*)</code> counts NULLs and <code>count(column)</code> does not</p>
<p>[edit] added this code so that people can run it</p>
<pre><code>create table #bla(id int,id2 int)
insert #bla values(null,null)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,null)
select count(*),count(id),count(id2)
from #bla
</code></pre>
<p>results
7 3 2</p> | {
"question_id": 59294,
"question_date": "2008-09-12T15:27:17.253Z",
"question_score": 216,
"tags": "sql",
"answer_id": 59302,
"answer_date": "2008-09-12T15:28:15.127Z",
"answer_score": 247
} |
Please answer the following Stack Overflow question:
Title: In Vim/Vi, how do you move the cursor to the end of the previous word?
<p>In Vim's normal mode:</p>
<ul>
<li><kbd>e</kbd> goes to the end of the next word</li>
<li><kbd>w</kbd> goes to the beginning of the next word</li>
<li><kbd>b</kbd> goes to the beginning of the previous word</li>
</ul>
<p>How do you move the cursor to the <em>end</em> of the <em>previous</em> word?</p> | <p>Unfortunately it's not a single key... but <kbd>g</kbd><kbd>e</kbd> is what you're looking for, I think.</p> | {
"question_id": 5125270,
"question_date": "2011-02-26T05:31:28.620Z",
"question_score": 216,
"tags": "vim|vi",
"answer_id": 5125292,
"answer_date": "2011-02-26T05:37:50.760Z",
"answer_score": 289
} |
Please answer the following Stack Overflow question:
Title: Do spurious wakeups in Java actually happen?
<p>Seeing various locking related question and (almost) always finding the 'loop because of spurious wakeups' terms<sup>1</sup> I wonder, has anyone experienced such kind of a wakeup (assuming a decent hardware/software environment for example)?</p>
<p>I know the term 'spurious' means no apparent reason but what can be the reasons for such kind of an event?</p>
<p>(<sup>1</sup> Note: I'm not questioning the looping practice.)</p>
<p><strong>Edit:</strong> A helper question (for those who like code samples):</p>
<p>If I have the following program, and I run it:</p>
<pre><code>public class Spurious {
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Condition cond = lock.newCondition();
lock.lock();
try {
try {
cond.await();
System.out.println("Spurious wakeup!");
} catch (InterruptedException ex) {
System.out.println("Just a regular interrupt.");
}
} finally {
lock.unlock();
}
}
}
</code></pre>
<p>What can I do to wake this <code>await</code> up spuriously without waiting forever for a random event?</p> | <p>The Wikipedia <a href="http://en.wikipedia.org/wiki/Spurious_wakeup" rel="noreferrer">article on spurious wakeups</a> has this tidbit:</p>
<blockquote>
<p>The <code>pthread_cond_wait()</code> function in Linux is implemented using the <code>futex</code> system call. Each blocking system call on Linux returns abruptly with <code>EINTR</code> when the process receives a signal. ... <code>pthread_cond_wait()</code> can't restart the waiting because it may miss a real wakeup in the little time it was outside the <code>futex</code> system call. This race condition can only be avoided by the caller checking for an invariant. A POSIX signal will therefore generate a spurious wakeup.</p>
</blockquote>
<p><strong>Summary</strong>: If a Linux process is signaled its waiting threads will each enjoy a nice, hot <em>spurious wakeup</em>.</p>
<p>I buy it. That's an easier pill to swallow than the typically vague "it's for performance" reason often given.</p> | {
"question_id": 1050592,
"question_date": "2009-06-26T18:42:03.350Z",
"question_score": 216,
"tags": "java|multithreading|locking|spurious-wakeup",
"answer_id": 1051816,
"answer_date": "2009-06-27T00:28:52.950Z",
"answer_score": 211
} |
Please answer the following Stack Overflow question:
Title: How much of ‘What Every Programmer Should Know About Memory’ is still valid?
<p>I am wondering how much of Ulrich Drepper's <a href="http://lwn.net/Articles/250967/" rel="noreferrer">What Every Programmer Should Know About Memory</a> from 2007 is still valid. Also I could not find a newer version than 1.0 or an errata.</p>
<p>(Also in PDF form on Ulrich Drepper's own site: <a href="https://www.akkadia.org/drepper/cpumemory.pdf" rel="noreferrer">https://www.akkadia.org/drepper/cpumemory.pdf</a>)</p> | <p>As far as I remember Drepper's content describes fundamental concepts about memory: how CPU cache works, what are physical and virtual memory and how Linux kernel deals that zoo. Probably there are outdated API references in some examples, but it doesn't matter; that won't affect the relevance of the fundamental concepts.</p>
<p>So, any book or article that describes something fundamental cannot be called outdated. "What every programmer should know about memory" is definitely worth to read, but, well, I don't think it's for "every programmer". It's more suitable for system/embedded/kernel guys.</p> | {
"question_id": 8126311,
"question_date": "2011-11-14T18:30:09.493Z",
"question_score": 216,
"tags": "optimization|memory|x86|cpu-architecture|cpu-cache",
"answer_id": 8126441,
"answer_date": "2011-11-14T18:40:44.270Z",
"answer_score": 134
} |
Please answer the following Stack Overflow question:
Title: In what areas might the use of F# be more appropriate than C#?
<p>Over the last few years F# has evolved into one of Microsoft's fully supported languages employing many ideas incubated in OCaml, ML and Haskell.</p>
<p>Over the last several years C# has extended its general purpose features by introducing more and more functional language features: LINQ (list comprehension), Lambdas, Closures, Anonymous Delegates and more...</p>
<p>Given C#'s adoption of these functional features and F#'s taxonomy as an impure functional language (it allows YOU to access framework libraries or change shared state when a function is called if you want to) there is a strong similarity between the two languages although each has its own polar opposite primary emphasis.</p>
<p>I'm interested in any successful models employing these two languages in your production polyglot programs and also the areas within production software (web apps, client apps, server apps) you have written in F# in the past year or so that you would previously have written in C#.</p> | <p>I have written an application to balance the national power generation schedule for a portfolio of power stations to a trading position for an energy company. The client and server components were in C# but the calculation engine was written in F#. </p>
<p>The use of F# to address the complexity at the heart of this application clearly demonstrates a sweet spot for the language within enterprise software, namely algorithmically complex analysis of large data sets. My experience has been a very positive one. In particular:</p>
<p><strong>Units of measure</strong> The industry I work in is littered with units. The equations I implemented (often of a geometric nature) dealt with units of time, power and energy. Having the type system verify the correctness of the units of the inputs and outputs of functions is a huge time saver, both in terms of testing and reading/understanding the code. It eradicates a whole class of errors that previous systems were prone to.</p>
<p><strong>Exploratory programming</strong> Working with script files and the REPL (F# Interactive) allowed me to explore the solution space more effectively before committing to an implementation than the more traditional edit/compile/run/test loop. It is a very natural way for a programmer to build their understanding of the problem and the design tensions in play.</p>
<p><strong>Unit testing</strong> Code written using non-side effecting functions and immutable data structures is a joy to test. There are no complex time-dependent interactions to screw things up or large sets of dependencies to be mocked.</p>
<p><strong>Interoperation</strong> I defined the interface to the calculation engine in C# and implemented the calculation in F#. The calculation engine could then be injected into any C# module that needed to use it without any concerns at all about interoperability. Seamless. The C# programmer need never know.</p>
<p><strong>Code reduction</strong> Much of the data fed into the calculation engine was in the form of vectors and matrices. Higher order functions eat these for breakfast with minimal fuss, minimal code. Beautiful.</p>
<p><strong>Lack of bugs</strong> Functional programming can feel strange. I can be working on an algorithm, trying hard to get the code to pass the type checker but once the type checker is satisfied thats it, it works. Its almost binary, either it wont compile or its correct. Weird edge case errors are minimised, recursion and higher order functions remove a lot of book-keeping code that introduces edge case errors.</p>
<p><strong>Parallelism</strong> The functional purity of the resulting implementation makes it ripe for exploiting the inherent parallelism in processing vectors of data. Maybe this is where I will go next now that .NET 4 is out. </p> | {
"question_id": 2785029,
"question_date": "2010-05-06T22:45:10.910Z",
"question_score": 216,
"tags": "c#|f#",
"answer_id": 2787342,
"answer_date": "2010-05-07T08:59:12.147Z",
"answer_score": 266
} |
Please answer the following Stack Overflow question:
Title: How to search for a string in text files?
<p>I want to check if a string is in a text file. If it is, do X. If it's not, do Y. However, this code always returns <code>True</code> for some reason. Can anyone see what is wrong?</p>
<pre><code>def check():
datafile = file('example.txt')
found = False
for line in datafile:
if blabla in line:
found = True
break
check()
if True:
print "true"
else:
print "false"
</code></pre> | <p>The reason why you always got <code>True</code> has already been given, so I'll just offer another suggestion:</p>
<p>If your file is not too large, you can read it into a string, and just use that (easier and often faster than reading and checking line per line):</p>
<pre><code>with open('example.txt') as f:
if 'blabla' in f.read():
print("true")
</code></pre>
<p>Another trick: you can alleviate the possible memory problems by using <a href="http://docs.python.org/library/mmap.html" rel="noreferrer"><code>mmap.mmap()</code></a> to create a "string-like" object that uses the underlying file (instead of reading the whole file in memory):</p>
<pre><code>import mmap
with open('example.txt') as f:
s = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if s.find('blabla') != -1:
print('true')
</code></pre>
<p>NOTE: in python 3, mmaps behave like <code>bytearray</code> objects rather than strings, so the subsequence you look for with <code>find()</code> has to be a <code>bytes</code> object rather than a string as well, eg. <code>s.find(b'blabla')</code>:</p>
<pre><code>#!/usr/bin/env python3
import mmap
with open('example.txt', 'rb', 0) as file, \
mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ) as s:
if s.find(b'blabla') != -1:
print('true')
</code></pre>
<p>You could also use regular expressions on <code>mmap</code> e.g., case-insensitive search: <code>if re.search(br'(?i)blabla', s):</code></p> | {
"question_id": 4940032,
"question_date": "2011-02-09T00:09:48.030Z",
"question_score": 215,
"tags": "python",
"answer_id": 4944929,
"answer_date": "2011-02-09T12:39:29.450Z",
"answer_score": 485
} |
Please answer the following Stack Overflow question:
Title: Python: finding an element in a list
<p>What is a good way to find the index of an element in a list in Python?<br>
Note that the list may not be sorted.</p>
<p>Is there a way to specify what comparison operator to use?</p> | <p>The best way is probably to use the <a href="https://docs.python.org/tutorial/datastructures.html#more-on-lists" rel="noreferrer">list method .index</a>. </p>
<p>For the objects in the list, you can do something like:</p>
<pre><code>def __eq__(self, other):
return self.Value == other.Value
</code></pre>
<p>with any special processing you need.</p>
<p>You can also use a for/in statement with enumerate(arr)</p>
<p>Example of finding the index of an item that has value > 100.</p>
<pre><code>for index, item in enumerate(arr):
if item > 100:
return index, item
</code></pre>
<p><a href="http://www.daniweb.com/forums/thread174502.html" rel="noreferrer">Source</a></p> | {
"question_id": 604802,
"question_date": "2009-03-03T01:45:02.990Z",
"question_score": 215,
"tags": "python|list",
"answer_id": 604813,
"answer_date": "2009-03-03T01:51:56.983Z",
"answer_score": 70
} |
Please answer the following Stack Overflow question:
Title: How to see log files in MySQL?
<p>I've read that Mysql server creates a log file where it keeps a record of all activities - like when and what queries execute. </p>
<p>Can anybody tell me where it exists in my system? How can I read it?</p>
<p>Basically, I need to back up the database with different input [backup between two dates] so I think I need to use log file here, that's why I want to do it...</p>
<p>I think this log must be secured somehow because sensitive information such as usernames and password may be logged [if any query require this]; so may it be secured, not easily able to be seen?</p>
<p>I have root access to the system, how can I see the log? </p>
<p>When I try to open /var/log/mysql.log it is empty.</p>
<p>This is my config file:</p>
<pre><code>[client]
port = 3306
socket = /var/run/mysqld/mysqld.sock
[mysqld_safe]
socket = /var/run/mysqld/mysqld.sock
nice = 0
[mysqld]
log = /var/log/mysql/mysql.log
binlog-do-db=zero
user = mysql
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
skip-external-locking
bind-address = 127.0.0.1
#
# * Fine Tuning
#
key_buffer = 16M
max_allowed_packet = 16M
thread_stack = 192K
thread_cache_size = 8
general_log_file = /var/log/mysql/mysql.log
general_log = 1
</code></pre> | <p>Here is a simple way to enable them. In mysql we need to see often 3 logs which are mostly needed during any project development.</p>
<ul>
<li><p><code>The Error Log</code>. It contains information about errors that occur while
the server is running (also server start and stop)</p></li>
<li><p><code>The General Query Log</code>. This is a general record of what mysqld is
doing (connect, disconnect, queries)</p></li>
<li><p><code>The Slow Query Log</code>. Ιt consists of "slow" SQL statements (as
indicated by its name).</p></li>
</ul>
<p>By default no log files are enabled in MYSQL. All errors will be shown in the syslog (<code>/var/log/syslog</code>).</p>
<p>To Enable them just follow below steps:</p>
<p><strong>step1:</strong> Go to this file (<strong>/etc/mysql/conf.d/mysqld_safe_syslog.cnf</strong>) and remove or comment those line.</p>
<p><strong>step2:</strong> Go to mysql conf file (<code>/etc/mysql/my.cnf</code>) and add following lines</p>
<p><strong>To enable error log add following</strong> </p>
<pre><code>[mysqld_safe]
log_error=/var/log/mysql/mysql_error.log
[mysqld]
log_error=/var/log/mysql/mysql_error.log
</code></pre>
<p><strong>To enable general query log add following</strong></p>
<pre><code>general_log_file = /var/log/mysql/mysql.log
general_log = 1
</code></pre>
<p><strong>To enable Slow Query Log add following</strong></p>
<pre><code>log_slow_queries = /var/log/mysql/mysql-slow.log
long_query_time = 2
log-queries-not-using-indexes
</code></pre>
<p><strong>step3:</strong> save the file and restart mysql using following commands</p>
<pre><code>service mysql restart
</code></pre>
<p>To enable logs at runtime, login to mysql client (<code>mysql -u root -p</code>) and give:</p>
<pre><code>SET GLOBAL general_log = 'ON';
SET GLOBAL slow_query_log = 'ON';
</code></pre>
<p>Finally one thing I would like to mention here is <strong>I read this from a blog</strong>. Thanks. It works for me.</p>
<p>Click <a href="http://www.pontikis.net/blog/how-and-when-to-enable-mysql-logs" rel="noreferrer">here</a> to visit the blog</p> | {
"question_id": 5441972,
"question_date": "2011-03-26T11:21:48.990Z",
"question_score": 215,
"tags": "mysql|logging",
"answer_id": 29409969,
"answer_date": "2015-04-02T09:52:10.030Z",
"answer_score": 206
} |
Please answer the following Stack Overflow question:
Title: Use '=' or LIKE to compare strings in SQL?
<p>There's the (almost religious) discussion, if you should use LIKE or '=' to compare strings in SQL statements.</p>
<ul>
<li>Are there reasons to use LIKE?</li>
<li>Are there reasons to use '='?</li>
<li>Performance? Readability? </li>
</ul> | <p>To see the performance difference, try this:</p>
<pre><code>SELECT count(*)
FROM master..sysobjects as A
JOIN tempdb..sysobjects as B
on A.name = B.name
SELECT count(*)
FROM master..sysobjects as A
JOIN tempdb..sysobjects as B
on A.name LIKE B.name
</code></pre>
<p>Comparing strings with '=' is much faster.</p> | {
"question_id": 515039,
"question_date": "2009-02-05T08:35:04.393Z",
"question_score": 215,
"tags": "sql|comparison",
"answer_id": 515060,
"answer_date": "2009-02-05T08:41:09.823Z",
"answer_score": 148
} |
Please answer the following Stack Overflow question:
Title: BAT file: Open new cmd window and execute a command in there
<p>I'm trying to open a new command window in a BAT file:</p>
<pre><code>start %windir%\system32\cmd.exe
</code></pre>
<p>After it opens, I'd like to execute a BAT command in the new window:</p>
<pre><code>echo "test in new window"
</code></pre>
<p>How can I do this?</p> | <p>You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.</p>
<p>What I found out was to use the K switch like this:</p>
<pre><code>start cmd /k echo Hello, World!
</code></pre>
<p>start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.</p>
<p>You can also use the /C switch for something similar.</p>
<pre><code>start cmd /C pause
</code></pre>
<p>This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.</p> | {
"question_id": 9392874,
"question_date": "2012-02-22T10:18:22.467Z",
"question_score": 215,
"tags": "batch-file|command-line",
"answer_id": 11393481,
"answer_date": "2012-07-09T10:44:23.540Z",
"answer_score": 340
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.