title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags list |
|---|---|---|---|---|---|---|---|---|---|
Python and OpenSSL version reference issue on OS X | 37,690,054 | <p>Trying to resolve an OpenSSL version issue I'm having. </p>
<p>It seems that I have three different versions of OpenSSL on my Mac. </p>
<ol>
<li><p>Python 2.7.11 has version 0.9.7m:</p>
<pre><code>python -c "import ssl; print ssl.OPENSSL_VERSION"
OpenSSL 0.9.7m 23 Feb 2007
</code></pre></li>
<li><p>At the Termina... | 8 | 2016-06-07T21:54:04Z | 37,712,029 | <p>Use this as a workaround:</p>
<pre><code>export CRYPTOGRAPHY_ALLOW_OPENSSL_098=1
</code></pre>
<p>This appears to be a recent check of the hazmat cryptography library. You can see the source code at:</p>
<p><a href="https://github.com/pyca/cryptography/blob/master/src/cryptography/hazmat/bindings/openssl/binding... | 14 | 2016-06-08T20:11:08Z | [
"python",
"osx",
"ssl",
"openssl",
"version"
] |
Python and OpenSSL version reference issue on OS X | 37,690,054 | <p>Trying to resolve an OpenSSL version issue I'm having. </p>
<p>It seems that I have three different versions of OpenSSL on my Mac. </p>
<ol>
<li><p>Python 2.7.11 has version 0.9.7m:</p>
<pre><code>python -c "import ssl; print ssl.OPENSSL_VERSION"
OpenSSL 0.9.7m 23 Feb 2007
</code></pre></li>
<li><p>At the Termina... | 8 | 2016-06-07T21:54:04Z | 37,757,206 | <p>You can install a version of python that uses a newer version of openssl.</p>
<p>First you can brew install a new version of open SSL</p>
<pre><code>brew update
brew install openssl
brew link --force openssl
</code></pre>
<p>You should see a newer version with</p>
<pre><code>openssl version -a
</code></pre>
<p>... | 5 | 2016-06-10T21:10:19Z | [
"python",
"osx",
"ssl",
"openssl",
"version"
] |
Python and OpenSSL version reference issue on OS X | 37,690,054 | <p>Trying to resolve an OpenSSL version issue I'm having. </p>
<p>It seems that I have three different versions of OpenSSL on my Mac. </p>
<ol>
<li><p>Python 2.7.11 has version 0.9.7m:</p>
<pre><code>python -c "import ssl; print ssl.OPENSSL_VERSION"
OpenSSL 0.9.7m 23 Feb 2007
</code></pre></li>
<li><p>At the Termina... | 8 | 2016-06-07T21:54:04Z | 38,868,592 | <p>This problem almost kills me!!!!
Finally my guy solved this only by lowering the version of the package "paramiko" from 2.* to 1.*ï¼like 1.15.4 I setï¼can solve!</p>
| 0 | 2016-08-10T08:55:41Z | [
"python",
"osx",
"ssl",
"openssl",
"version"
] |
Django Query Filter Menu | 37,690,081 | <p>I want to build a similar, but significantly simpler User list page with a query filter menu:</p>
<p><a href="http://i.stack.imgur.com/Wl2nL.png" rel="nofollow">Player List from nhl.com</a></p>
<p>User can apply individual filters, or chain them. I prefer AJAX, but am happy to start off an 'apply filters' submit b... | 0 | 2016-06-07T21:55:47Z | 37,691,946 | <p>One way to apply filters is by using GET parameters. (The parts after the '?' in URLs [e.g. <code>https://search.yahoo.com/search?p=test+search</code>]). So create a form in your template with <code>method='GET'</code> and handle the GET parameters via <code>self.request.GET</code> (I think you have to enable the Re... | 0 | 2016-06-08T01:36:25Z | [
"python",
"django",
"filter",
"jquery-filter"
] |
Pandas groupby two columns then get dict for values | 37,690,092 | <p>I have a pandas dataframe:</p>
<pre><code>banned_titles =
TitleId RelatedTitleId
0 89989 32598
1 89989 3085083
2 95281 3085083
</code></pre>
<p>when I apply groupby as following</p>
<pre><code>In [84]: banned_titles.groupby('TitleId').groups
Out[84]: {89989: [0, 1], 95281: [2]... | 3 | 2016-06-07T21:56:31Z | 37,690,273 | <p>try this:</p>
<pre><code>In [8]: x.groupby('TitleId')['RelatedTitleId'].apply(lambda x: x.tolist()).to_dict()
Out[8]: {89989: [32598, 3085083], 95281: [3085083]}
</code></pre>
<p>or as series of lists:</p>
<pre><code>In [10]: x.groupby('TitleId')['RelatedTitleId'].apply(lambda x: x.tolist())
Out[10]:
TitleId
8998... | 6 | 2016-06-07T22:12:28Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
Pandas groupby two columns then get dict for values | 37,690,092 | <p>I have a pandas dataframe:</p>
<pre><code>banned_titles =
TitleId RelatedTitleId
0 89989 32598
1 89989 3085083
2 95281 3085083
</code></pre>
<p>when I apply groupby as following</p>
<pre><code>In [84]: banned_titles.groupby('TitleId').groups
Out[84]: {89989: [0, 1], 95281: [2]... | 3 | 2016-06-07T21:56:31Z | 37,691,106 | <p>Try list one line (no lambda): </p>
<pre><code>dict(df.groupby('TitleId')['RelatedTitleId'].apply(list))
# {89989: [32598, 3085083], 95281: [3085083]}
</code></pre>
| 2 | 2016-06-07T23:36:03Z | [
"python",
"pandas",
"dataframe",
"group-by"
] |
Pandas .asfreq is giving a repeated index error | 37,690,119 | <p>I'm trying to make some regular time series with <code>ffill</code> with Pandas, but I'm getting a non-unique index error.</p>
<p>Here's my code:</p>
<pre><code>for d in data_types:
series = df[df['datatype'] == d]['measurementvalue'].values
times = df[df['datatype'] == d]['displaydate'].values
data_se... | -2 | 2016-06-07T21:58:48Z | 37,690,378 | <p>Try something like this, But since you havent included any data this is just a starter. </p>
<pre><code>for d in data_types:
rawDf = df[df['datatype'] == d]
data_series = rawDf[['measurementvalue','displaydate']]
data_series.set_index('displaydate',drop=False, inplace = True)
d... | 0 | 2016-06-07T22:22:39Z | [
"python",
"pandas"
] |
Pandas .asfreq is giving a repeated index error | 37,690,119 | <p>I'm trying to make some regular time series with <code>ffill</code> with Pandas, but I'm getting a non-unique index error.</p>
<p>Here's my code:</p>
<pre><code>for d in data_types:
series = df[df['datatype'] == d]['measurementvalue'].values
times = df[df['datatype'] == d]['displaydate'].values
data_se... | -2 | 2016-06-07T21:58:48Z | 37,707,391 | <p>If you want to keep the maximum for each date-time. First make date_time a column and use</p>
<pre><code>df.groupby('date_time').max()
</code></pre>
<p>If you want to always keep the first or last entry, <a href="http://stackoverflow.com/questions/13035764/remove-rows-with-duplicate-indices-pandas-dataframe-and-ti... | 0 | 2016-06-08T15:56:29Z | [
"python",
"pandas"
] |
Cannot serialize data when patching to a field that has a 'valueschema' that is of type 'dict' in Eve | 37,690,142 | <p>So say i have the following document:</p>
<pre><code>test_obj = {
'my_things':{
'id17': {
'blah': 3,
'weird': 'yay',
'thechallenge': ObjectId('5712d06fdb4d0856551300d2')
},
'id32': {
'blah': 62,
'weird': 'hoorah',
't... | 1 | 2016-06-07T22:00:40Z | 37,706,787 | <p>This has been fixed with Eve v0.6.4, which has just been released.</p>
| 1 | 2016-06-08T15:26:31Z | [
"python",
"eve",
"cerberus"
] |
Finding connectedness from a list of nodes and a list of edges | 37,690,227 | <p>(tl;dr)</p>
<blockquote>
<p>Given a collection of nodes defined as a dictionary of points, and a collection of edges defined as a dictionary of key tuples, is there an algorithm in python to easily find consecutive segments?</p>
</blockquote>
<p>(context:)</p>
<p>I have two files that model segments of a road n... | 2 | 2016-06-07T22:07:54Z | 37,736,704 | <p>Let's not get too brutish. I think we can do well by building a simple list of lists, such that <strong>edge[i]</strong> is a list of up to three elements, the nodes to which node <strong>i</strong> is connected. If your node numbers are dense and start near 0, you can use a list; in case they're not, I'll use a ... | 2 | 2016-06-09T21:45:47Z | [
"python",
"graph-theory",
"hierarchical-clustering"
] |
Can I download a lazy load image? | 37,690,294 | <p>I'm trying to download some images from tripadvisor using urllib but all that I get for the url in the src field from the html is <a href="http://static.tacdn.com/img2/x.gif" rel="nofollow">this</a></p>
<p>I've done some research and I found out that those are lazy load images... Is there any way to download them??... | 0 | 2016-06-07T22:14:02Z | 37,696,136 | <p>You can extract a list of images from Javascript using the <a href="https://www.crummy.com/software/BeautifulSoup/" rel="nofollow">Beautiful Soup</a> and <a href="https://docs.python.org/2/library/json.html" rel="nofollow">json</a> modules, then iterate over the list and retrieve the images you are interested in.</p... | 0 | 2016-06-08T07:37:41Z | [
"python",
"html",
"xpath",
"lazy-loading",
"urllib"
] |
error 10055: 'no buffer space available' while populating database | 37,690,331 | <p>I am currently using python 3.4 and am getting an error 10055 when running my code. The code is below.</p>
<p>I have tried putting a "time.sleep(10)" and it that allows my database to gather more entries, but eventually my program always gets the error. </p>
<p>I understand that when I "sock.close()" my socket, th... | 0 | 2016-06-07T22:18:55Z | 37,834,220 | <p>The problem was within the amount of times I kept connecting and disconnecting from the MongoDB. I changed the database_addition function and that removed the problem.
I have posted both ways the function can be changed in order to remove this problem. The first, is changing the position of connecting to the databas... | 0 | 2016-06-15T11:31:19Z | [
"python",
"mongodb",
"sockets",
"python-3.x",
"urllib"
] |
Prepending 1d array onto each 2d array of a 3d array | 37,690,338 | <p>Say I have the size <code>(2,3,2)</code> array <code>a</code> and the size <code>(2)</code> array b below.</p>
<pre><code>import numpy as np
a = np.array([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]])
b = np.array([0.2, 0.8])
</code></pre>
<p>Array <code>a</code> looks like this:</p>
<p><a href="http:/... | 1 | 2016-06-07T22:19:28Z | 37,690,524 | <p>Try this:</p>
<pre><code>np.concatenate(([[b]]*2,a),axis=1)
# Result:
array([[[ 0.2, 0.8],
[ 1. , 2. ],
[ 3. , 4. ],
[ 5. , 6. ]],
[[ 0.2, 0.8],
[ 7. , 8. ],
[ 9. , 10. ],
[ 11. , 12. ]]])
</code></pre>
| 2 | 2016-06-07T22:37:14Z | [
"python",
"numpy"
] |
Prepending 1d array onto each 2d array of a 3d array | 37,690,338 | <p>Say I have the size <code>(2,3,2)</code> array <code>a</code> and the size <code>(2)</code> array b below.</p>
<pre><code>import numpy as np
a = np.array([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]])
b = np.array([0.2, 0.8])
</code></pre>
<p>Array <code>a</code> looks like this:</p>
<p><a href="http:/... | 1 | 2016-06-07T22:19:28Z | 37,690,644 | <p>This works:</p>
<pre><code>np.insert(a.astype(float), 0, b, 1)
</code></pre>
<p>Output:</p>
<pre><code>array([[[ 0.2, 0.8],
[ 1. , 2. ],
[ 3. , 4. ],
[ 5. , 6. ]],
[[ 0.2, 0.8],
[ 7. , 8. ],
[ 9. , 10. ],
[ 11. , 12. ]]])
</code></pre>
... | 1 | 2016-06-07T22:48:36Z | [
"python",
"numpy"
] |
Why must we declare that a variable is a global variable BEFORE the assignment of that variable? | 37,690,361 | <p>Why do we have to do this:</p>
<pre><code>global x
x = "Hello World!"
</code></pre>
<p>When this is more <em>"readable"</em>:</p>
<pre><code>global x = "Hello World"
</code></pre>
<p><strong><em>Why</em></strong> is this, is there a reason behind it?</p>
| 6 | 2016-06-07T22:21:28Z | 37,690,657 | <p>I like to think it puts your focus squarely on the fact that <em>you are using globals</em>, always a questionable practice in software engineering.
Python definitely isn't about representing a problem solution in the most compact way. Next you'll be saying that we should only indent one space, or use tabs! ;-)</p>
| 0 | 2016-06-07T22:49:36Z | [
"python",
"python-3.x",
"global-variables",
"global"
] |
Why must we declare that a variable is a global variable BEFORE the assignment of that variable? | 37,690,361 | <p>Why do we have to do this:</p>
<pre><code>global x
x = "Hello World!"
</code></pre>
<p>When this is more <em>"readable"</em>:</p>
<pre><code>global x = "Hello World"
</code></pre>
<p><strong><em>Why</em></strong> is this, is there a reason behind it?</p>
| 6 | 2016-06-07T22:21:28Z | 37,690,992 | <p>The <a href="https://docs.python.org/2/reference/simple_stmts.html#the-global-statement" rel="nofollow">document</a> writes that</p>
<blockquote>
<p>Names listed in a <code>global</code> statement must <em>not</em> be used in the same code block textually <em>preceding</em> that global statement.</p>
<p>CPyt... | 1 | 2016-06-07T23:22:34Z | [
"python",
"python-3.x",
"global-variables",
"global"
] |
Why must we declare that a variable is a global variable BEFORE the assignment of that variable? | 37,690,361 | <p>Why do we have to do this:</p>
<pre><code>global x
x = "Hello World!"
</code></pre>
<p>When this is more <em>"readable"</em>:</p>
<pre><code>global x = "Hello World"
</code></pre>
<p><strong><em>Why</em></strong> is this, is there a reason behind it?</p>
| 6 | 2016-06-07T22:21:28Z | 37,691,412 | <p>The goal of Python is to be as readable as possible. To reach this goal the user must be forced act in a clear defined way - e.g. you must use exactly four spaces. And just like this it defines that the <code>global</code> keyword is a simple statment. This means:</p>
<blockquote>
<p>A simple statement is compris... | 2 | 2016-06-08T00:14:08Z | [
"python",
"python-3.x",
"global-variables",
"global"
] |
How to remove text between variables | 37,690,395 | <p>I currently have a string that has variables in it.</p>
<pre><code>domain.com/?hello=randomtext&thingy=randotext2&stuff=1231kjh
</code></pre>
<p>I'm trying to delete</p>
<pre><code>&thingy=(all text that is in here)
</code></pre>
<p>The order might not always be that, and the text after the <code>=</... | 0 | 2016-06-07T22:24:18Z | 37,690,472 | <p>You can substitute using regex. </p>
<pre><code>import re
p = re.compile(ur'(&thingy=.*)&')
test_str = u"domain.com/?hello=randomtext&thingy=randotext2&stuff=1231kjh"
subst = u"&"
result = re.sub(p, subst, test_str)
>>> result
u'domain.com/?hello=randomtext&stuff=1231kjh'
</code>... | 0 | 2016-06-07T22:31:56Z | [
"python"
] |
How to remove text between variables | 37,690,395 | <p>I currently have a string that has variables in it.</p>
<pre><code>domain.com/?hello=randomtext&thingy=randotext2&stuff=1231kjh
</code></pre>
<p>I'm trying to delete</p>
<pre><code>&thingy=(all text that is in here)
</code></pre>
<p>The order might not always be that, and the text after the <code>=</... | 0 | 2016-06-07T22:24:18Z | 37,690,480 | <p>I don't know Python, but from experience with other programming languages, the question I think you should have asked is "How do you parse a URL in Python?" or "How do you parse a url query string in Python?" </p>
<p>Just Googling this I got the following info that may help:</p>
<pre><code>from urlparse import url... | 3 | 2016-06-07T22:32:50Z | [
"python"
] |
How to remove text between variables | 37,690,395 | <p>I currently have a string that has variables in it.</p>
<pre><code>domain.com/?hello=randomtext&thingy=randotext2&stuff=1231kjh
</code></pre>
<p>I'm trying to delete</p>
<pre><code>&thingy=(all text that is in here)
</code></pre>
<p>The order might not always be that, and the text after the <code>=</... | 0 | 2016-06-07T22:24:18Z | 37,690,552 | <p>If I get your question right then you're trying the delete all the string which is <code>"&thingy=randotext2&stuff=1231kjh "</code> </p>
<p>This can be easily achieved by doing something like this:</p>
<pre><code>current_str = "domain.com/?hello=randomtext&thingy=randotext2&stuff=1231kjh"
cursor ... | -1 | 2016-06-07T22:39:02Z | [
"python"
] |
How to remove text between variables | 37,690,395 | <p>I currently have a string that has variables in it.</p>
<pre><code>domain.com/?hello=randomtext&thingy=randotext2&stuff=1231kjh
</code></pre>
<p>I'm trying to delete</p>
<pre><code>&thingy=(all text that is in here)
</code></pre>
<p>The order might not always be that, and the text after the <code>=</... | 0 | 2016-06-07T22:24:18Z | 37,690,814 | <p>If you wish to delete only a query string argument value, such as <code>&thingy=</code>, in a regular expression it's like this:</p>
<pre><code>import re
domain = "domain.com/?hello=randomtext&thingy=randotext2&stuff=1231kjh"
x = re.sub(r'(&thingy=)[^&]*(&?.*)$', r'\1\2', domain)
</code></pr... | -1 | 2016-06-07T23:04:09Z | [
"python"
] |
Add a list to a numpy array | 37,690,440 | <p>Right now I'm writing a function that reads data from a file, with the goal being to add that data to a numpy array and return said array.</p>
<p>I would like to return the array as a 2D array, however I'm not sure what the complete shape of the array will be (I know the amount of columns, but not rows).
What I ha... | 1 | 2016-06-07T22:27:59Z | 37,690,569 | <p>If your file <code>data.txt</code> is </p>
<pre><code>1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
1 2 3 4
</code></pre>
<p>All you need to do is</p>
<pre><code>>>> import numpy as n
>>> data_array = n.loadtxt("data.txt")
>>> data_array
array([[1., 2., 3., 4.],
[1., 2., 3., 4.],
... | 1 | 2016-06-07T22:40:37Z | [
"python",
"numpy"
] |
Add a list to a numpy array | 37,690,440 | <p>Right now I'm writing a function that reads data from a file, with the goal being to add that data to a numpy array and return said array.</p>
<p>I would like to return the array as a 2D array, however I'm not sure what the complete shape of the array will be (I know the amount of columns, but not rows).
What I ha... | 1 | 2016-06-07T22:27:59Z | 37,690,586 | <p>Look at the common way of constructing an array:</p>
<pre><code>np.array([[1,2,3],[4,5,6],[7,8,9]])
np.array([[1,2,3],
[4,5,6],
[7,8,9]])
</code></pre>
<p>The input is a list of lists. Your reader could imitate that</p>
<p>Roughly:</p>
<pre><code>data = []
for line in f.readline():
value... | 0 | 2016-06-07T22:43:13Z | [
"python",
"numpy"
] |
WebApp becomes unresponsive after initiating Remote desktop Connection | 37,690,493 | <p>My becomes unresponsive after creating a batch file and calling mstc to execute a remote desktop connection. I would have thought that this is an independent process and does not rely in any way to my python scrypt.</p>
<pre><code>import os
def rdp_session(server, user, temporary_pass):
"""create Batch file t... | 0 | 2016-06-07T22:34:04Z | 37,690,584 | <p>In order for your session to continue you need to spawn another process, independent of the one that will terminate immediately after executing your script.</p>
| 0 | 2016-06-07T22:42:58Z | [
"python",
"python-2.7",
"rdp"
] |
WebApp becomes unresponsive after initiating Remote desktop Connection | 37,690,493 | <p>My becomes unresponsive after creating a batch file and calling mstc to execute a remote desktop connection. I would have thought that this is an independent process and does not rely in any way to my python scrypt.</p>
<pre><code>import os
def rdp_session(server, user, temporary_pass):
"""create Batch file t... | 0 | 2016-06-07T22:34:04Z | 37,798,905 | <p>After reading a bit on subprocesses, I managed find that none of these options were immediately effective since I needed to not only run a subprocess with Popen but additionally needed to use <a href="https://docs.python.org/2/library/os.path.html#os.path.expanduser" rel="nofollow">Pathname expansion</a></p>
<p>fro... | 0 | 2016-06-13T20:51:23Z | [
"python",
"python-2.7",
"rdp"
] |
Find and Replace in Python- based on unknown characters | 37,690,529 | <p>I've been stumped on finding a way to find and replace characters based on position.
Basically what I am looking to do it go into a document and replace</p>
<pre><code><gco:DateTime>2016-04-20T11:27:34.8677919-06:00</gco:DateTime>
</code></pre>
<p>With</p>
<pre><code><gco:DateTime>2016-04-20T11:... | 0 | 2016-06-07T22:37:47Z | 37,690,619 | <p>One way:</p>
<pre><code>s = "<gco:DateTime>2016-04-20T11:27:34.8677919-06:00</gco:DateTime>"
split_on_dot = s.split('.')
split_on_angle = split_on_dot[1].split('<')
new_s = "".join([split_on_dot[0], "<", split_on_angle[1]])
>>> new_s
'<gco:DateTime>2016-04-20T11:27:34</gco:DateT... | 0 | 2016-06-07T22:46:16Z | [
"python",
"xml",
"python-2.7"
] |
Find and Replace in Python- based on unknown characters | 37,690,529 | <p>I've been stumped on finding a way to find and replace characters based on position.
Basically what I am looking to do it go into a document and replace</p>
<pre><code><gco:DateTime>2016-04-20T11:27:34.8677919-06:00</gco:DateTime>
</code></pre>
<p>With</p>
<pre><code><gco:DateTime>2016-04-20T11:... | 0 | 2016-06-07T22:37:47Z | 37,691,613 | <p>Consider <a href="https://www.w3.org/Style/XSL/" rel="nofollow">XSLT</a> (the special-purpose declarative language designed to transform XML documents) which has a very convenient function (shared with its sibling, XPath) for your needs <a href="https://developer.mozilla.org/en-US/docs/Web/XPath/Functions/substring-... | 0 | 2016-06-08T00:42:34Z | [
"python",
"xml",
"python-2.7"
] |
Where liveth declared but undefined global variables in Python? | 37,690,583 | <p>When you state that a variable is global, it does not create it for you (if it doesn't already exist). What does the global statement <strong>actually</strong> do to the variable? It obviously doesn't merely modify it since it does not have to exist for it to be modified. Once this goes out of scope, can </p>
<pre>... | 0 | 2016-06-07T22:42:55Z | 37,690,758 | <blockquote>
<p>What does the global statement <strong>actually</strong> do to the variable?</p>
</blockquote>
<p>Absolutely nothing.</p>
<p><code>global foo</code> means that any occurrences of the variable name <code>foo</code> in the scope of the function refer to a module-global <code>foo</code> variable instea... | 2 | 2016-06-07T22:59:33Z | [
"python",
"cpython"
] |
Where liveth declared but undefined global variables in Python? | 37,690,583 | <p>When you state that a variable is global, it does not create it for you (if it doesn't already exist). What does the global statement <strong>actually</strong> do to the variable? It obviously doesn't merely modify it since it does not have to exist for it to be modified. Once this goes out of scope, can </p>
<pre>... | 0 | 2016-06-07T22:42:55Z | 37,690,860 | <blockquote>
<p>The global is a directive to the parser. </p>
</blockquote>
<p>as written in the <a href="https://docs.python.org/2/reference/simple_stmts.html#grammar-token-global_stmt" rel="nofollow">doc</a>. This means it doesn't change anything. Also notice that "it applies only to code parsed at the same time a... | 1 | 2016-06-07T23:08:10Z | [
"python",
"cpython"
] |
Tuple index out of range in string formatting | 37,690,615 | <p>I have a tuple:</p>
<pre><code>('ORF eins', '20:15', '21:05', 'soko-donau.html', 'Soko Donau', 'Schöne neue Welt')
</code></pre>
<p>that has six elements (index 0-5).</p>
<p>If I print with string formatting, like this:</p>
<pre><code>print("""Entry {}
Title: {}
Station: {}
Start Time: {}
End Time: {}""".format... | 0 | 2016-06-07T22:45:51Z | 37,690,667 | <p>You have a closing bracket after <code>details[1]</code> which messes up your code.</p>
| 1 | 2016-06-07T22:50:33Z | [
"python"
] |
Tuple index out of range in string formatting | 37,690,615 | <p>I have a tuple:</p>
<pre><code>('ORF eins', '20:15', '21:05', 'soko-donau.html', 'Soko Donau', 'Schöne neue Welt')
</code></pre>
<p>that has six elements (index 0-5).</p>
<p>If I print with string formatting, like this:</p>
<pre><code>print("""Entry {}
Title: {}
Station: {}
Start Time: {}
End Time: {}""".format... | 0 | 2016-06-07T22:45:51Z | 37,690,669 | <p>It looks like you have a parenthesis in the wrong place:</p>
<pre><code>print("""Entry {}
Title: {}
Station: {}
Start Time: {}
End Time: {}""".format(programID, details[4], details[0], details[1]), details[2])
# ^
</code></pre>
<p>So your format sta... | 3 | 2016-06-07T22:50:37Z | [
"python"
] |
Numpy: Find from matrix based on one of the columns | 37,690,678 | <p>I have Xy:</p>
<pre><code>matrix([[1, 1, 1, 1],
[1, 2, 2, 2],
[2, 3, 3, 3],
[2, 4, 4, 4]])
</code></pre>
<p>How do I return all rows with first column == 1?</p>
<p>Answer should be:</p>
<pre><code>matrix([[1, 1, 1, 1],
[1, 2, 2, 2]])
</code></pre>
| 0 | 2016-06-07T22:51:29Z | 37,690,817 | <p>The <code>matrix</code> type should generally be avoided in favour of <code>numpy.array</code>. However, if you feel you <strong>need</strong> to use it then you can filter a matrix using <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.compress.html#numpy.compress" rel="nofollow"><code>nump... | 2 | 2016-06-07T23:04:14Z | [
"python",
"numpy"
] |
How to kill a subprocess started in a thread? | 37,690,704 | <p>I am trying to run the <code>Robocopy</code> command (but I am curious about any subprocess) from Python in windows. The code is pretty simple and works well. It is:</p>
<pre><code>def copy():
with Popen(['Robocopy', media_path, destination_path, '/E', '/mir', '/TEE', '/log+:' + log_path], stdout=PIPE, bufsiz... | 0 | 2016-06-07T22:53:57Z | 37,690,888 | <p>We fought with reliably killing subprocesses on Windows for a while and eventually came across this:</p>
<pre><code>https://github.com/andreisavu/python-process/blob/master/killableprocess.py
</code></pre>
<p>It implements a <code>kill()</code> method for killing your subprocess. We've had really good results wit... | 1 | 2016-06-07T23:11:04Z | [
"python",
"windows",
"multithreading",
"python-3.x",
"subprocess"
] |
How to kill a subprocess started in a thread? | 37,690,704 | <p>I am trying to run the <code>Robocopy</code> command (but I am curious about any subprocess) from Python in windows. The code is pretty simple and works well. It is:</p>
<pre><code>def copy():
with Popen(['Robocopy', media_path, destination_path, '/E', '/mir', '/TEE', '/log+:' + log_path], stdout=PIPE, bufsiz... | 0 | 2016-06-07T22:53:57Z | 37,758,602 | <p>If the process doesn't start other processes then <code>process.kill()</code> should work:</p>
<pre><code>import subprocess
class InterruptableProcess:
def __init__(self, *args):
self._process = subprocess.Popen(args)
def interrupt(self):
self._process.kill()
</code></pre>
<p>I don't ... | 1 | 2016-06-10T23:52:47Z | [
"python",
"windows",
"multithreading",
"python-3.x",
"subprocess"
] |
Get a list of all private channels with Slack API | 37,690,761 | <p>I've been trying to get a list of all "groups" in my Slack team. However, even with admin privs, <code>groups.list</code> only provides the groups that the token owner's account belongs to.</p>
<p>The closest solution I've seen in my research involves getting a bot to sit in the channel. The bot's membership allows... | 3 | 2016-06-07T22:59:45Z | 37,691,079 | <p>slacks <a href="https://slack.com/privacy-policy" rel="nofollow">privacy policy</a> does not support this.</p>
<blockquote>
<p>The most fundamental privacy principle we follow is that by default,
anything you post to Slack is private to your team. That is, viewing
the messages and files shared within a specif... | 1 | 2016-06-07T23:33:40Z | [
"python",
"slack-api"
] |
Why does 'abc'[-1] result in 'c' rather than 'b'? | 37,690,792 | <p>I thought that it started counting backwards from the start, so A is 0, B is -1 and C is -2.</p>
| 0 | 2016-06-07T23:02:31Z | 37,690,827 | <p>As Henry pointed out, negative indices indicate counting from the right.</p>
<p>Naturally, <code>A</code> is <code>0</code>, <code>B</code> is <code>1</code> and <code>C</code> is <code>2</code>, when counting from the left:</p>
<pre><code>-> -> ->
A | B | C
0 | 1 | 2
</code></pre>
<p>When going back... | 6 | 2016-06-07T23:05:04Z | [
"python",
"string"
] |
Why does 'abc'[-1] result in 'c' rather than 'b'? | 37,690,792 | <p>I thought that it started counting backwards from the start, so A is 0, B is -1 and C is -2.</p>
| 0 | 2016-06-07T23:02:31Z | 37,690,837 | <p>A negative index means "start counting from the right". </p>
<hr>
<p>Put another way: <code>sequence[0]</code> is the start of the sequence, why would you expect <code>sequence[-1]</code> to be anything other than the end of the sequence?</p>
<pre><code> 0 1 2
a b c
-3 -2 -1
a b c
</code>... | 4 | 2016-06-07T23:05:55Z | [
"python",
"string"
] |
group data by date based on values using pandas | 37,690,859 | <p>How can I group the following data into by month using pandas:</p>
<pre><code>17/1/2001 800
7/1/2001 1300
2/1/2001 400
1/1/2001 200
25/3/2001 1800
8/3/2001 1300
</code></pre>
<p>and then have the following output with first and last days of the month and the corresponding first and last values:</p>... | 4 | 2016-06-07T23:07:54Z | 37,690,959 | <p>try this:</p>
<pre><code>In [102]: res = df.sort_values('date').groupby(df.date.dt.month).agg(['first','last'])
In [104]: res.columns = ['date_first', 'date_last', 'first', 'last']
In [105]: res
Out[105]:
date_first date_last first last
date
1 2001-01-01 2001-01-17 200 800
3 2001-03-08 2001-03-... | 5 | 2016-06-07T23:18:22Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
group data by date based on values using pandas | 37,690,859 | <p>How can I group the following data into by month using pandas:</p>
<pre><code>17/1/2001 800
7/1/2001 1300
2/1/2001 400
1/1/2001 200
25/3/2001 1800
8/3/2001 1300
</code></pre>
<p>and then have the following output with first and last days of the month and the corresponding first and last values:</p>... | 4 | 2016-06-07T23:07:54Z | 37,691,377 | <p>Use <code>idxmin</code> and <code>idxmax</code> to identify indices for which to grab the appropriate rows.</p>
<pre><code>def get_min(x):
return x.loc[x.date.idxmin(), :]
def get_max(x):
return x.loc[x.date.idxmax(), :]
def app_by_month(df, f):
return df.groupby(df.date.dt.month).apply(f)
df2 = pd.c... | 2 | 2016-06-08T00:09:43Z | [
"python",
"python-2.7",
"pandas",
"dataframe"
] |
Target WSGI script '/opt/python/current/app/application.py' does not contain WSGI application 'application' | 37,690,918 | <p>Pulling my hair out! I am trying to deploy a Python FLask application to AWS Elastic Beanstalk and I am getting the error </p>
<p>Target WSGI script '/opt/python/current/app/application.py' does not contain WSGI application 'application'</p>
<p>The web page is just returning a 500 Server error</p>
<p>the content ... | 0 | 2016-06-07T23:13:48Z | 37,691,163 | <p>Try to move the line <code>if __name__ == '__main__'</code> after <code>application=...</code>, because the launcher may <em>import</em> your script instead of exec it. In that case <code>__name__</code> will not be defined as <code>__main__</code>. See this <a href="http://docs.aws.amazon.com/elasticbeanstalk/lates... | 0 | 2016-06-07T23:43:13Z | [
"python",
"amazon-web-services",
"flask",
"elastic-beanstalk"
] |
How can I recreate the following using list comprehensions? | 37,690,974 | <p>I am pretty new to Python, and I have just started to get the hang of list comprehensions. However, I cannot rewrite the following code using them. Any help with that would be appreciated.</p>
<pre><code>for i in range(len(table)):
table[i*2] += " |"
table.insert(2*i + 1, "-"*(len(table[0])))
</code></pre>
... | 0 | 2016-06-07T23:20:06Z | 37,691,063 | <p>Your code is equivalent to just concatenating:</p>
<pre><code>In [1]: table = ["foo","bar", "foobar","foob","barf"]
In [2]:
In [2]: for i in range(len(table)):
...: table[i*2] += " |"
...: table.insert(2*i + 1, "-"*(len(table[0])))
...:
In [3]: print("".join(table))
foo |-----bar |... | 0 | 2016-06-07T23:31:21Z | [
"python",
"list-comprehension"
] |
How can I recreate the following using list comprehensions? | 37,690,974 | <p>I am pretty new to Python, and I have just started to get the hang of list comprehensions. However, I cannot rewrite the following code using them. Any help with that would be appreciated.</p>
<pre><code>for i in range(len(table)):
table[i*2] += " |"
table.insert(2*i + 1, "-"*(len(table[0])))
</code></pre>
... | 0 | 2016-06-07T23:20:06Z | 37,691,066 | <pre><code>table = [ "a", "b", "c", "d"]
table[:] = [x for i in table for x in [i + ' |', '-'*(2+len(table[0]))]]
print (table)
# Result:
# ['a |', '---', 'b |', '---', 'c |', '---', 'd |', '---']
</code></pre>
<p>As a readable alternative to what you've written, try this:</p>
<pre><code>newtable = []
for i in tab... | 3 | 2016-06-07T23:31:57Z | [
"python",
"list-comprehension"
] |
How to set LD_LIBRARY_PATH for apache+wsgi website | 37,690,980 | <p>I'm trying to use a python library in my wsgi( apache + flask) based website. </p>
<p>While using the library in a standalone command script, I have to add the library path to LD_LIBRARY_PATH</p>
<p>So this works for standalone script:</p>
<pre><code># export LD_LIBRARY_PATH=/usr/local/lib:/usr/local/lib64
# pyth... | 0 | 2016-06-07T23:20:43Z | 37,691,499 | <p>Is the library required by a Python module extension you have compiled and installed? If it was, set <code>LD_RUN_PATH</code> environment variable to the directory the library is in when compiling and installing that Python module. That way the location is embedded in the Python module extension itself and you don't... | 1 | 2016-06-08T00:25:55Z | [
"python",
"apache",
"environment-variables",
"mod-wsgi"
] |
What does the following re code mean? | 37,691,057 | <p>I don't understand this code in Python. I know what the function does but I don't get how and what those <code>\\</code> do in the replacement string.</p>
<pre><code>import re
caps="([A-Z])"
pre="(Mr|mr|Mr|St|st|ST|Mrs|MRS|mrs|Ms|MS|ms|Dr|DR|dr|miss|Miss|MISS)[\.\.\.]"
def tokenize_sentence(text):
text=re.sub("... | -1 | 2016-06-07T23:30:16Z | 37,691,140 | <p>The <code>\1</code>, <code>\2</code>, etc refer to matched subexpressions (enclosed in parentheses) in a regular expression. <code>\1</code> is the first expression matched, <code>\2</code> is the second, etc. They are used in the replacement string to mark where matched subexpressions are to be modified.</p>
<p... | 2 | 2016-06-07T23:39:31Z | [
"python",
"regex",
"replace"
] |
DataFrame of means of top N most correlated columns | 37,691,075 | <p>I have a dataframe <code>df1</code> where each column represents a time series of returns. I want to create a new dataframe <code>df2</code> with columns that corresponds to each of the columns in <code>df1</code> where the column in <code>df2</code> is defined to be the average of the top 5 most correlated columns... | 2 | 2016-06-07T23:32:54Z | 37,691,076 | <h3>Setup</h3>
<pre><code>import pandas as pd
import numpy as np
from string import ascii_letters
np.random.seed([3,1415])
df1 = pd.DataFrame(np.random.randn(100, 10).round(2),
columns=list(ascii_letters[26:36]))
</code></pre>
<h3>Solution</h3>
<pre><code>corr = df.corr()
# I don't want a securi... | 1 | 2016-06-07T23:32:54Z | [
"python",
"pandas"
] |
DataFrame of means of top N most correlated columns | 37,691,075 | <p>I have a dataframe <code>df1</code> where each column represents a time series of returns. I want to create a new dataframe <code>df2</code> with columns that corresponds to each of the columns in <code>df1</code> where the column in <code>df2</code> is defined to be the average of the top 5 most correlated columns... | 2 | 2016-06-07T23:32:54Z | 37,691,603 | <p>For each column in the correlation matrix, take the six largest and ignore the first one (i.e. 100% correlated with itself). Use a dictionary comprehension to do this for each column.</p>
<p>Use another dictionary comprehension to located this columns in <code>df1</code> and take their mean. Create a dataframe fr... | 3 | 2016-06-08T00:40:09Z | [
"python",
"pandas"
] |
Delete N random objects Django orm | 37,691,146 | <p>How can I delete 100 randomly selected objects in Django?</p>
<p>Example:</p>
<pre><code>Book.objects.all()[:100].delete()
</code></pre>
| 1 | 2016-06-07T23:40:48Z | 37,691,300 | <p>I can't understand when this would be useful, but here's one way</p>
<pre><code>import random
ids = random.sample(Book.objects.values_list('pk', flat=True), 100)
Book.objects.filter(pk__in=ids).delete()
</code></pre>
| 2 | 2016-06-08T00:00:53Z | [
"python",
"django",
"orm"
] |
How to dynamically assign arguments to itertools.product in python | 37,691,169 | <p>I am trying to work out how to pass itertools.product a dynamic number of arguments.</p>
<p>I have the following code which worked as expected printing out lines with each line having 4 characters in a different order:</p>
<pre><code>#!/usr/bin/env python3.5
import sys, itertools, multiprocessing, functools
alpha... | 1 | 2016-06-07T23:44:08Z | 37,691,302 | <p>Is this what you are trying to do? </p>
<pre><code>import sys, itertools, multiprocessing, functools
alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ12234567890!@#$%^&*?,()-=+[]/;"
repeats = 5
... | 0 | 2016-06-08T00:01:07Z | [
"python",
"itertools"
] |
How to dynamically assign arguments to itertools.product in python | 37,691,169 | <p>I am trying to work out how to pass itertools.product a dynamic number of arguments.</p>
<p>I have the following code which worked as expected printing out lines with each line having 4 characters in a different order:</p>
<pre><code>#!/usr/bin/env python3.5
import sys, itertools, multiprocessing, functools
alpha... | 1 | 2016-06-07T23:44:08Z | 37,691,323 | <p>You can just multiply the list of strings:</p>
<pre><code> def do_job(first_bits):
for x in itertools.product(first_bits, *[alphabet] * 3):
</code></pre>
<p>You could also use <em>itertools.repeat</em>:</p>
<pre><code>from itertools import repeat
def do_job(first_bits, times):
for x in itertools.product... | 1 | 2016-06-08T00:03:10Z | [
"python",
"itertools"
] |
Problems logging into site with jsf login using Python Requests | 37,691,170 | <p>I know that this is similar to other Requests login problems, but for some reason nothing seems to be working with my code.
I'm attempting to login to <a href="https://pacer.login.uscourts.gov/csologin/login.jsf" rel="nofollow">https://pacer.login.uscourts.gov/csologin/login.jsf</a>
and I am using the following code... | 1 | 2016-06-07T23:44:11Z | 37,691,212 | <p>You are missing some post data:</p>
<pre><code>data = {"login":"login",
"login:loginName":uName,
"login:password":pWord,
"login:clientCode":"",
"login:fbtnLogin":"",
"javax.faces.ViewState":"stateless"}
headers = {"User-Agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (... | 0 | 2016-06-07T23:49:12Z | [
"python",
"post",
"login",
"python-requests"
] |
Tree details in random forest | 37,691,178 | <p>I'm looking for a random forest package in python or R that will let me get some fine-grained details on the final forest that was built. In particular, I would like to:</p>
<ol>
<li>Get some representation of the trees created;</li>
<li>For each tree in the forest, get an overall measure of how well it fits the da... | 0 | 2016-06-07T23:44:44Z | 37,691,269 | <p>Try This:</p>
<blockquote>
<p>Package for interpreting scikit-learn's decision tree and random
forest predictions. Allows decomposing each prediction into bias and
feature contribution components as described in
<a href="http://blog.datadive.net/interpreting-random-forests/" rel="nofollow">http://blog.datad... | 0 | 2016-06-07T23:57:00Z | [
"python",
"machine-learning",
"random-forest"
] |
Ordering a query set based on the length of another query set | 37,691,211 | <p>I have these models:</p>
<pre><code>class Team(models.Model):
# stuff
class Alliance(models.Model):
teams = models.ManyToManyField(Team)
class Match(models.Model):
alliances = models.ManyToManyField(Alliance)
winner = models.ForeignKey(Alliance, null=True, related_name='winner')
</code></pre>
<p>... | 0 | 2016-06-07T23:48:56Z | 37,693,510 | <p>It looks like you are trying to sort the teams based on their number of wins. In this case, you could annotate each <code>Team</code> object with the number of wins their related alliances have and then sort on those number of wins in decreasing order:</p>
<pre><code>from django.db.models import Count
teams = Team.... | 1 | 2016-06-08T04:51:41Z | [
"python",
"mysql",
"django",
"performance",
"python-3.x"
] |
Moving a Sprite in PyGame | 37,691,270 | <p>I'm currently working on a school project, but I'm stuck trying to get my sprite to move. My error message is saying that I'm missing 1 required positional argument: 'self' in Mario.handle_keys().</p>
<p>Here's my main code:</p>
<pre><code>import pygame
import sys
from pygame.locals import*
from Mario import Mari... | 0 | 2016-06-07T23:57:07Z | 37,691,395 | <p><code>Mario</code> is a class. The method <code>handle_keys(self)</code> is an instance method -- meaning it can only be called against an <code>Mario</code> instance. (It is possible to have a <code>classmethod</code>, but that's not what you want here since you need to modify <code>self</code>.)</p>
<p>At the t... | 0 | 2016-06-08T00:12:16Z | [
"python",
"pygame",
"sprite"
] |
Problems of MORSE Simulator installation with python version on ubuntu 14.04 | 37,691,523 | <p>My problem:
Blender is compiled for Python 3.5.1 but MORSE has been compiled for Python 3.3.6! Check your MORSE build configuration or the selected Blender version.</p>
<ul>
<li><p>Bad Python version</p></li>
<li><p>Your environment is not correctly setup to run MORSE!
It seems that both of them are compulsory for... | 0 | 2016-06-08T00:29:45Z | 38,215,113 | <p>I had the same issue, except it was a much narrower version gap:</p>
<pre><code>Blender is compiled for Python 3.4.2 but MORSE has been compiled for Python 3.4.3! Check your MORSE build configuration or the selected Blender version.
</code></pre>
<p>This was for Blender <code>2.76</code>. You may get this to work ... | 0 | 2016-07-06T01:18:07Z | [
"python",
"ubuntu",
"install",
"simulator"
] |
How to get all pool.apply_async processes to stop once any one process has found a match in python | 37,691,552 | <p>I have the following code that is leveraging multiprocessing to iterate through a large list and find a match. How can I get all processes to stop once a match is found in any one processes? I have seen examples but I none of them seem to fit into what I am doing here.</p>
<pre><code>#!/usr/bin/env python3.5
impo... | 0 | 2016-06-08T00:34:11Z | 37,692,251 | <p><code>multiprocessing</code> isn't really designed to cancel tasks, but you can simulate it for your particular case by using <code>pool.imap_unordered</code> and terminating the pool when you get a hit:</p>
<pre><code>def do_job(first_bits):
for x in itertools.product(first_bits, *itertools.repeat(alphabet, nu... | 0 | 2016-06-08T02:21:55Z | [
"python",
"python-3.x",
"multiprocessing"
] |
How to get all pool.apply_async processes to stop once any one process has found a match in python | 37,691,552 | <p>I have the following code that is leveraging multiprocessing to iterate through a large list and find a match. How can I get all processes to stop once a match is found in any one processes? I have seen examples but I none of them seem to fit into what I am doing here.</p>
<pre><code>#!/usr/bin/env python3.5
impo... | 0 | 2016-06-08T00:34:11Z | 37,700,081 | <p>You can check <a href="http://stackoverflow.com/questions/33447055/python-multiprocess-pool-how-to-exit-the-script-when-one-of-the-worker-process/33450972#33450972">this question</a> to see an implementation example solving your problem.</p>
<p>This works also with concurrent.futures pool.</p>
<p>Just replace the ... | 1 | 2016-06-08T10:36:19Z | [
"python",
"python-3.x",
"multiprocessing"
] |
How to cache views in django | 37,691,589 | <p>I am currently using django and I'm attempting to cache my view like so </p>
<pre><code>from django.views.decorators.cache import cache_page
@cache_page(60 * 15)
def index(request):
# This method takes time to run, which is why I need to cache this view
a_method_that_preforms_heavy_db_transactions()
cont... | 0 | 2016-06-08T00:39:04Z | 37,691,610 | <p>You'll need to add a <code>caching service</code>, e.g Memcached</p>
<pre><code>CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211/A_ROUTE_WITH_A_HEAVY_TRANSACTION',
}
}
</code></pre>
<p>You'll find everything you need here... | 2 | 2016-06-08T00:42:08Z | [
"python",
"django"
] |
How to cache views in django | 37,691,589 | <p>I am currently using django and I'm attempting to cache my view like so </p>
<pre><code>from django.views.decorators.cache import cache_page
@cache_page(60 * 15)
def index(request):
# This method takes time to run, which is why I need to cache this view
a_method_that_preforms_heavy_db_transactions()
cont... | 0 | 2016-06-08T00:39:04Z | 37,691,612 | <p>Have you <a href="https://docs.djangoproject.com/en/1.9/topics/cache/" rel="nofollow">set caching up</a>? You need to define <code>CACHES</code> in your <code>settings.py</code> file. You can use memcached, Redis, your database or a file system. The simplest setup is with local memory as it doesn't require any exter... | 1 | 2016-06-08T00:42:26Z | [
"python",
"django"
] |
Prevent pandas read_table from dropping tab characters | 37,691,609 | <p>In pandas, let's say I have the following string that I want to read with read_table:</p>
<p><code>A\tB\tC\t\t\tD\t\tE\t\t\t\t\t\t\t</code></p>
<p>Where \t are tab characters. If I use read_table like so:</p>
<pre><code>with open('file.dat') as f:
df = pd.read_table(f, delimiter = '\r\n\')
</code></pre>
<p>It... | 1 | 2016-06-08T00:41:34Z | 37,692,028 | <p>The default is:</p>
<pre><code>read_table(filepath_or_buffer, sep='\t', delimiter=None,
</code></pre>
<p>Try changing the separator: </p>
<pre><code>pd.read_table(f, delimiter = '\r\n\', sep=',' )
</code></pre>
| 0 | 2016-06-08T01:49:21Z | [
"python",
"pandas"
] |
Apply custom function on text on a pandas dataframe rather than iterating individual element | 37,691,658 | <p>My pandas dataframe is very large and so I want to be able to modify the textLower(frame) function so that it gets executed in one command and I dont have to iterate over each row to perform a sequence of string manipulations over each element.</p>
<pre><code># Function iterates over all the values of a pandas da... | 2 | 2016-06-08T00:50:36Z | 37,691,753 | <p>Try this: </p>
<pre><code>dfCities["Text"].str.lower()
</code></pre>
<p>or this:</p>
<pre><code>def textLower(x):
return x.lower()
dfCities = dfCities["Text"].apply(textLower)
dfCities
# 0 chicago
# 1 new york
# 2 portland
# 3 san francisco
# 4 austin
# ... | 2 | 2016-06-08T01:05:20Z | [
"python",
"pandas"
] |
How can I scrape this particulary jQuery site wih python? | 37,691,677 | <p>I want to scrape this site: <code>https://resultadoselecciones2016.onpe.gob.pe/PRP2V2016/Actas-por-Ubigeo.html</code></p>
<p>They are using jQuery so the data isn't on the "normal" html code. I see this on the Chrome developer console:</p>
<p><a href="http://i.stack.imgur.com/UYm8n.png" rel="nofollow"><img src="ht... | 0 | 2016-06-08T00:54:05Z | 37,708,642 | <p>I just solved this. I used the <code>requests</code> module instead <code>urllib</code> and just copy/paste the entire header, like this:</p>
<pre><code>import requests
from bs4 import BeautifulSoup
url2 = "https://resultadoselecciones2016.onpe.gob.pe/PRP2V2016/ajax.php"
head = "[my entire header]"
data_get_depart... | 0 | 2016-06-08T17:00:24Z | [
"jquery",
"python",
"web-scraping"
] |
cannot install tradingWithPython into Anaconda | 37,691,746 | <pre><code>C:\Users\gaucho-ucsb>pip install tradingWithPython
Collecting tradingWithPython
Using cached tradingWithPython-3.1.0.0.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "c:\users\gaucho~1\appdata\local... | 0 | 2016-06-08T01:04:56Z | 38,854,068 | <p>I just spoke with the author of the library and it seems that tradingwithPython only installs with Python3. It is not backwards compatible anymore. </p>
<p>I just tried this (because I had the same issue) and it seems to work now. </p>
| 1 | 2016-08-09T14:51:24Z | [
"python",
"pip",
"conda"
] |
How would I load multiple values in to an equation? | 37,691,751 | <p>If I have a set <code>x1 = [0, 0, 0, 1]</code> and <code>x2 =[1, 0, 0, 1]</code>, how would I iterate and print out an equation like </p>
<pre><code>zscore = 1*w0 + w1*x1 + w2*x2
</code></pre>
<p>w's are constants</p>
<p>Printing out the x1 as a column x2 as column and score as column?</p>
| 0 | 2016-06-08T01:05:18Z | 37,692,150 | <p>From what I understood, you want to calculate the zscore for each pair in x1 and x2 and print out the results in a column.</p>
<pre><code>x1 = [0,0,0,1]
x2 = [1,0,0,1]
for x,y in zip(x1,x2):
print(x1, x2, 1*w0 + w1*x + w2*y)
</code></pre>
<p>According to your comment, if the numbers in your list are strings, you... | 0 | 2016-06-08T02:07:33Z | [
"python"
] |
how do I sum pairwise dot products of columns | 37,691,756 | <p>I have a dataframe</p>
<pre><code>df = pd.DataFrame(np.random.rand(10, 10))
</code></pre>
<p>I want to take pairwise dot products of the odd columns with even columns then sum them up. So column 0 with column 1, column 2 with column 3, and so on.</p>
<p>I've done</p>
<pre><code>df.mul(df.shift(axis=1)).sum().su... | 3 | 2016-06-08T01:06:08Z | 37,691,758 | <p>try:</p>
<pre><code>(df.iloc[:, ::2].values * df.iloc[:, 1::2].values).sum()
</code></pre>
| 2 | 2016-06-08T01:06:36Z | [
"python",
"numpy",
"pandas"
] |
how do I sum pairwise dot products of columns | 37,691,756 | <p>I have a dataframe</p>
<pre><code>df = pd.DataFrame(np.random.rand(10, 10))
</code></pre>
<p>I want to take pairwise dot products of the odd columns with even columns then sum them up. So column 0 with column 1, column 2 with column 3, and so on.</p>
<p>I've done</p>
<pre><code>df.mul(df.shift(axis=1)).sum().su... | 3 | 2016-06-08T01:06:08Z | 37,694,936 | <p>That element-wise multiplication and sum reduction could be thought of as dot product reduction. In this case, we can do it with <a href="http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.tensordot.html" rel="nofollow"><code>NumPy's tensordot</code></a>, like so -</p>
<pre><code># Extract the element... | 2 | 2016-06-08T06:36:27Z | [
"python",
"numpy",
"pandas"
] |
Unmount OSX volumes when placed in trash | 37,691,770 | <p>I found this article...<a href="http://www.guidingtech.com/26874/eject-delete-dmg-files-automatically/" rel="nofollow">http://www.guidingtech.com/26874/eject-delete-dmg-files-automatically/</a> My question relates to the second part of the page.</p>
<p>It doesn't seem to work anymore in El Cap. Tried individual lin... | 0 | 2016-06-08T01:08:43Z | 38,088,207 | <pre><code>import string, os, sys
lines = os.popen("hdiutil info").readlines()
should_eject = False
for line in lines:
if line.startswith("image-alias"):
path = line.split(":")[1]
image_path = path.lstrip().rstrip()
if image_path in sys.argv:
should_eject = True
elif line.s... | 0 | 2016-06-29T00:05:36Z | [
"python",
"osx",
"unmount"
] |
Talk to Chrome extensions background conscole via webdriver | 37,691,836 | <p>I am new to web programming.
I am trying to add parameters to one of my Chrome extension. </p>
<p>I know I can enter, for example, "window.localStorage.setItem()" in the extension console. However, I cannot find a way to navigate my webdriver to that extension background page. I have seen, in the past, people woul... | 0 | 2016-06-08T01:18:13Z | 37,692,838 | <p>Probably one thing to correct here is that <code>chrome://extensions/</code> opens up the <strong><em>Extensions</em></strong> on Chrome browser. So this shall work fine :</p>
<pre><code>driver.get("chrome://extensions/")
</code></pre>
<p>Just a note now the <strong><em>chrome://extensions/extension_id</em></stron... | 0 | 2016-06-08T03:41:47Z | [
"python",
"google-chrome",
"selenium",
"selenium-webdriver",
"google-chrome-extension"
] |
Python - Ensuring that event notifications are not sent before a pre specified time | 37,691,903 | <p>I am trying to write a python code in which I'd want to send a notification to a user when a specific condition is met. The event can occur every second and I do not want to send notifications every second. </p>
<p>How do I program (pseudo code probably) so that my notifications are sent every 30 minutes, even if e... | 0 | 2016-06-08T01:29:06Z | 37,692,260 | <p>You'll need to specify what you want to do more precisely, e.g., will you notify the user after the first event, but then not again for 30 minutes? Or wait for 30 minutes after the first event, and then notify the user of all events in the previous 30 minutes? Or notify the user at 0 and 30 minutes past the hour if ... | 0 | 2016-06-08T02:22:46Z | [
"python"
] |
Python - Ensuring that event notifications are not sent before a pre specified time | 37,691,903 | <p>I am trying to write a python code in which I'd want to send a notification to a user when a specific condition is met. The event can occur every second and I do not want to send notifications every second. </p>
<p>How do I program (pseudo code probably) so that my notifications are sent every 30 minutes, even if e... | 0 | 2016-06-08T01:29:06Z | 37,710,144 | <p>Thank you man for sharing the code. I'll try to implement. </p>
<p>Actually I am trying to create an aquarium controller that'd eventually take care of lot of tasks for me. Right now, I am using a raspberry pi, along with few temperature sensors, to measure my tank temperature. As long as the temperature goes beyo... | 0 | 2016-06-08T18:25:25Z | [
"python"
] |
redirect while templating page | 37,691,910 | <p>In Flask, how do you redirect to a different page while rendering a template?</p>
<pre><code>@app.route('/foo.html', methods=['GET', 'POST'])
def foo():
if request.method == "POST":
x = request.form['x']
y = request.form['y']
if x > y:
return redirect(render_template("bar.... | -1 | 2016-06-08T01:29:47Z | 37,691,970 | <p>For redirecting you want a URL</p>
<pre><code>return redirect(url_for('bar'))
</code></pre>
<p>You'll need to import <code>url_for</code> from Flask. If you need to pass additional variables you should put them in as parameters</p>
<pre><code>somevalue = 1
return redirect(url_for('bar', somevar=somevalue) )
</cod... | 2 | 2016-06-08T01:39:22Z | [
"python",
"html5",
"web",
"flask"
] |
SolrClient not committing changes until restart of solr process | 37,691,973 | <p>I am having some trouble getting <a href="https://github.com/moonlitesolutions/SolrClient" rel="nofollow">SolrClient</a> to immediately reflect changes I am making. If I write to the index, I need to first restart the solr process I have running, and only then can I see the changes I am writing. Here is the code I a... | 0 | 2016-06-08T01:40:17Z | 37,721,205 | <p>The commit function of the library sets the parameters as follows:</p>
<pre><code>openSearcher=False
softCommit=False
waitSearcher=True
commit=True
</code></pre>
<p>Since its a hard commit and openSearch is false, caches are not invalidated and hence you cannot see new added records. You can refer <a href="https:/... | 0 | 2016-06-09T08:54:20Z | [
"python",
"solr",
"client",
"commit",
"restart"
] |
Regular expression returning None (python) | 37,691,988 | <p>I'm only a month into python and this basic exercise is driving me up the wall. I'm trying to make a search script that will search text I input and put the results on my clipboard. I've been stuck below for about a week. If i copy text directly from a site and input it, no results (I get a None output). But if i co... | 1 | 2016-06-08T01:42:30Z | 37,692,211 | <p>See changes inline</p>
<pre><code># -*- coding: utf-8 -*-
# 1. added above line
import re
def findphone(numbers):
numregex = re.compile(r'(\(\d\)\d\d\s\d+)') # 2. Added circular brackets around the regular expression
numregex1 = re.compile(r'(\(0\)11 123456)') # 3. Escaped circular brackets around 0
#... | 1 | 2016-06-08T02:16:03Z | [
"python",
"regex",
"search"
] |
climb ladder in pygame | 37,692,015 | <p>I'm relatively new to pygame and python as a whole, and I'm currently working on a school project. I'm trying to make it so that when my Mario sprite is overlapping with the ladder sprite, he can move up, and when he's not overlapping, subsequently cannot move up. Here's my code:</p>
<pre><code>import pygame
impo... | 1 | 2016-06-08T01:47:03Z | 37,692,799 | <p>You were on the right track with <code>pygame.Rect.colliderect</code> (you can also use <code>pygame.sprite.collide_rect(mario, ladder)</code>) but it can't work because you don't move the rects of the sprites which are used for the collision detection. You only change the <code>x</code> and <code>y</code> attribute... | 1 | 2016-06-08T03:36:33Z | [
"python",
"pygame",
"sprite"
] |
SageMathCell ValueError When Printing String (Sometimes) | 37,692,165 | <p>When I execute <a href="https://sagecell.sagemath.org/?z=eJzVV1tv2zYUfg-Q_3DqYKi0yK5lrMMWVAPSpO2yKQlQO-iDERiMTNtsJZImqabur98hJcWU4iQd1j7MQGKZ_Hgu37nw6ODg-3_29w7gRMwpHJdmJZQ-gmM-V_QWzimjCgif4442jMO5WKkIRsP4pT3T_lzQG0X0JwIfqM7phnC44uwzVUybjUW_pwuqKM_oEZxnf5NNBB8UW65MBJdf883XTyJymt6zbFUIPh9AR8WJ4NoQbmDCCgrvKKeKGCY4iAW8... | 1 | 2016-06-08T02:09:35Z | 38,361,736 | <p>Here's a workaround: Rather than print the output at each iteration of the loop, store the entire output in a single string and print once at the end of execution. This can be accomplished by replacing all instances of</p>
<pre><code>print heading
</code></pre>
<p>with</p>
<pre><code>output = output + '\n' + head... | 0 | 2016-07-13T21:08:14Z | [
"python",
"string",
"error-handling",
"sage"
] |
SageMathCell ValueError When Printing String (Sometimes) | 37,692,165 | <p>When I execute <a href="https://sagecell.sagemath.org/?z=eJzVV1tv2zYUfg-Q_3DqYKi0yK5lrMMWVAPSpO2yKQlQO-iDERiMTNtsJZImqabur98hJcWU4iQd1j7MQGKZ_Hgu37nw6ODg-3_29w7gRMwpHJdmJZQ-gmM-V_QWzimjCgif4442jMO5WKkIRsP4pT3T_lzQG0X0JwIfqM7phnC44uwzVUybjUW_pwuqKM_oEZxnf5NNBB8UW65MBJdf883XTyJymt6zbFUIPh9AR8WJ4NoQbmDCCgrvKKeKGCY4iAW8... | 1 | 2016-06-08T02:09:35Z | 38,440,425 | <p>It turned out that the problem was fixed in the past, but came back due to current ipykernel master having version 4.3.0dev while the latest release is 4.3.1. I've adjusted installation command and can no longer reproduce the issue - the error line is now properly wrapped. Thanks for reporting!</p>
| 1 | 2016-07-18T15:18:57Z | [
"python",
"string",
"error-handling",
"sage"
] |
python - understanding of for loop | 37,692,189 | <p>i have the following line in a python code:</p>
<pre><code>for tradeName, trade in data.iterrows():
...
</code></pre>
<p>"data" being a pandas dataframe in the following form:</p>
<pre><code>timestamp open high low close volume
2000-01-03 00:00:00 1481.50 1481.50 1480.50 1480.5... | 2 | 2016-06-08T02:12:48Z | 37,692,247 | <p>the tradeName and trade are just self defined "loop" variables to get the respective value that data.iterrows() will return. TradName being the index and trade being the series for the index.</p>
<p>These below should return the same result:</p>
<pre><code> for tradeName, trade in data.iterrows():
for x, y... | 2 | 2016-06-08T02:21:19Z | [
"python",
"pandas"
] |
python - understanding of for loop | 37,692,189 | <p>i have the following line in a python code:</p>
<pre><code>for tradeName, trade in data.iterrows():
...
</code></pre>
<p>"data" being a pandas dataframe in the following form:</p>
<pre><code>timestamp open high low close volume
2000-01-03 00:00:00 1481.50 1481.50 1480.50 1480.5... | 2 | 2016-06-08T02:12:48Z | 37,692,402 | <p>There are two things going on here, first is unpacking and second is looping.</p>
<p>You can unpack elements in a tuple and assign them simultaneously as follows:</p>
<pre><code>a,b,c = tuple([1,2,3])
print(b)
</code></pre>
<p>Further, if you have an iterable of tuples, you can unpack each one sequentially.</p>
... | 4 | 2016-06-08T02:45:16Z | [
"python",
"pandas"
] |
Python multiprocessing - AssertionError: can only join a child process | 37,692,262 | <p>I'm taking my first foray into the python mutliprocessing module and I'm running into some problems. I'm very familiar with the threading module but I need to make sure the processes I'm executing are running in parallel.</p>
<p>Here's an outline of what I'm trying to do. Please ignore things like undeclared variab... | 3 | 2016-06-08T02:22:51Z | 37,692,316 | <p>It seems to me that you are threading it one time too many. I would not thread it from <code>run_in_parallel</code>, but simply calling <code>run_server_client</code> with the proper arguments, because they will thread inside.</p>
| 0 | 2016-06-08T02:31:53Z | [
"python",
"python-2.7",
"unix",
"python-multiprocessing"
] |
Python multiprocessing - AssertionError: can only join a child process | 37,692,262 | <p>I'm taking my first foray into the python mutliprocessing module and I'm running into some problems. I'm very familiar with the threading module but I need to make sure the processes I'm executing are running in parallel.</p>
<p>Here's an outline of what I'm trying to do. Please ignore things like undeclared variab... | 3 | 2016-06-08T02:22:51Z | 37,709,169 | <blockquote>
<p>I can change the old code to not use <code>os.fork()</code> but I'd also like to know why this caused this problem and if there's a workable solution.</p>
</blockquote>
<p>The key to understanding the problem is knowing exactly what <code>fork()</code> does. CPython docs state "Fork a child process.... | 3 | 2016-06-08T17:31:13Z | [
"python",
"python-2.7",
"unix",
"python-multiprocessing"
] |
Getting javascript postback parameters with scrapy | 37,692,310 | <p>I have the following element:</p>
<pre><code><a class="html-attribute-value html-external-link" target="_blank" href='javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ResultsGrid$15", "", false, "", "webproperty.aspx?s=id&amp;s=15&amp;time=201606080118012&amp", false, true))'>... | 2 | 2016-06-08T02:31:09Z | 37,692,331 | <p>You can do it via <a href="http://doc.scrapy.org/en/latest/topics/selectors.html#using-selectors-with-regular-expressions" rel="nofollow"><code>re()</code> method</a> and multiple capturing groups:</p>
<pre><code>response.selector.xpath('//*[@id="ResultsGrid$15"]/@href').re(r'javascript:WebForm_DoPostBackWithOption... | 3 | 2016-06-08T02:35:11Z | [
"python",
"scrapy"
] |
Python :: NLTK concatenating list of sentences | 37,692,504 | <p><code>NLTK</code> <a href="http://www.nltk.org/" rel="nofollow">http://www.nltk.org/</a> is a toolkit for computational linguistics. </p>
<p>I am trying to manipulate sentences, using the <code>sents()</code> method:</p>
<pre><code>from nltk.corpus import gutenberg
</code></pre>
<p>it fetches texts by <code>filei... | 3 | 2016-06-08T02:59:07Z | 37,693,363 | <p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.chain.from_iterable" rel="nofollow"><code>itertools.chain</code></a> after appending to your list <code>shakespeare</code>:</p>
<pre><code>from itertools import chain
lis = list(chain.from_iterable(shakespeare))
# output:
# [
# ['['... | 0 | 2016-06-08T04:36:35Z | [
"python",
"list",
"nltk",
"nested-lists"
] |
Python :: NLTK concatenating list of sentences | 37,692,504 | <p><code>NLTK</code> <a href="http://www.nltk.org/" rel="nofollow">http://www.nltk.org/</a> is a toolkit for computational linguistics. </p>
<p>I am trying to manipulate sentences, using the <code>sents()</code> method:</p>
<pre><code>from nltk.corpus import gutenberg
</code></pre>
<p>it fetches texts by <code>filei... | 3 | 2016-06-08T02:59:07Z | 37,769,627 | <p>The best solution is to just fetch them all at once-- the sentences come the way you want them. The nltk's corpus readers accept either a single filename or a list of files:</p>
<pre><code>shakespeare = gutenberg.sents(['shakespeare-hamlet.txt',
'shakespeare-macbeth.txt', 'shakespeare-caesar.txt'])... | 1 | 2016-06-12T00:15:48Z | [
"python",
"list",
"nltk",
"nested-lists"
] |
How to test for an exception object with an `if` statement? | 37,692,511 | <p>How can I test if a function returned an exception object if I don't know in advance what type of exception has been raised?</p>
<pre><code>def func():
try:
bad_thing_happens # NameError("global name 'bad_thing_happens' is not defined",)
return True
except Exception as e:
return e
... | 2 | 2016-06-08T02:59:45Z | 37,692,528 | <p>If you cannot change the <code>func()</code> for some reason (for example, it is a part of a third-party library code), you can check the type of the returned value via <a href="https://docs.python.org/2/library/functions.html#isinstance" rel="nofollow"><code>isinstance()</code></a>:</p>
<pre><code>if isinstance(re... | 2 | 2016-06-08T03:02:14Z | [
"python",
"exception"
] |
How to test for an exception object with an `if` statement? | 37,692,511 | <p>How can I test if a function returned an exception object if I don't know in advance what type of exception has been raised?</p>
<pre><code>def func():
try:
bad_thing_happens # NameError("global name 'bad_thing_happens' is not defined",)
return True
except Exception as e:
return e
... | 2 | 2016-06-08T02:59:45Z | 37,692,533 | <p>Functions <em>returning</em> exceptions instead of raising them or letting them bubble is a Bad Thing.</p>
<p>That said, you can test if an object is an instance of a class using <code>isinstance(object, klass)</code>.</p>
| 6 | 2016-06-08T03:02:55Z | [
"python",
"exception"
] |
How to test for an exception object with an `if` statement? | 37,692,511 | <p>How can I test if a function returned an exception object if I don't know in advance what type of exception has been raised?</p>
<pre><code>def func():
try:
bad_thing_happens # NameError("global name 'bad_thing_happens' is not defined",)
return True
except Exception as e:
return e
... | 2 | 2016-06-08T02:59:45Z | 37,692,535 | <p>The proper way would be to catch the exception outside of the function. For example:</p>
<pre><code>def func():
bad_thing_happens
# NameError("global name 'bad_thing_happens' is not defined",)
return True
try:
result = func()
except NameError:
print("a bad thing happened")
</code></pre>
<p>Thi... | 5 | 2016-06-08T03:03:30Z | [
"python",
"exception"
] |
Storing User Events History in Google Cloud Datastore vs Google Cloud Bigtable | 37,692,577 | <p>I am trying to track user events in my android app by storing in a database in the backend. I am using Google App Engine for my mobile backend. I am trying to figure out whether Datastore in Google App Engine is suited for this. Also, I came across Bigtable (Billed functionality) for NoSQL. </p>
<p>What are the pro... | 2 | 2016-06-08T03:09:22Z | 37,702,544 | <p>Cloud Bigtable doesn't currently work on Google App Engine standard, but that feature is actively being worked on. Cloud Bigtable does current Google App Engine flexible.</p>
<p>To get user events into Bigtable, you'd have to use a slightly different architecture. Here's a talk about IoT which is similar to captu... | 2 | 2016-06-08T12:29:37Z | [
"python",
"google-app-engine",
"google-cloud-datastore",
"google-cloud-bigtable"
] |
Storing User Events History in Google Cloud Datastore vs Google Cloud Bigtable | 37,692,577 | <p>I am trying to track user events in my android app by storing in a database in the backend. I am using Google App Engine for my mobile backend. I am trying to figure out whether Datastore in Google App Engine is suited for this. Also, I came across Bigtable (Billed functionality) for NoSQL. </p>
<p>What are the pro... | 2 | 2016-06-08T03:09:22Z | 37,711,265 | <p>Have you considered Google Analytics?
<a href="https://developers.google.com/analytics/devguides/collection/android/v4/#set-up-your-project" rel="nofollow">https://developers.google.com/analytics/devguides/collection/android/v4/#set-up-your-project</a></p>
| 0 | 2016-06-08T19:28:42Z | [
"python",
"google-app-engine",
"google-cloud-datastore",
"google-cloud-bigtable"
] |
Properly formatting http.client.HTTPSConnection in Python | 37,692,592 | <p>Overall, I'm trying to invoke the MS Cognitive <a href="https://westus.dev.cognitive.microsoft.com/docs/services/TextAnalytics.V2.0/operations/56f30ceeeda5650db055a3c6/console" rel="nofollow">key phrases API</a> from Python 3.5.1 :: Anaconda 4.0.0 (32-bit). I looked everywhere and tried to incorporate this stackover... | 1 | 2016-06-08T03:10:45Z | 37,751,659 | <p>I made 2 changed to the code above that allow it to work. 1) I was getting my params and body mixed up. 2) I needed to add str(body_documents) in my post. Both beginner mistakes. </p>
| 0 | 2016-06-10T15:11:41Z | [
"python",
"python-3.x"
] |
Performing an indirect sort in numpy, preserving same indices for identical elements | 37,692,618 | <p>Let's assume I have an array like this:</p>
<pre><code>a = np.array([5, 2, 13, 13, 222])
</code></pre>
<p>I want to convert it to an array like this:</p>
<pre><code>b = np.array([1, 0, 2, 2, 3])
</code></pre>
<p>I've tried np.argsort, but returns</p>
<pre><code>np.argsort(np.array([5, 2, 13, 13, 222])) # = arra... | 2 | 2016-06-08T03:14:20Z | 37,692,892 | <p>This is what the <code>return_inverse</code> parameter to <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.unique.html" rel="nofollow"><code>numpy.unique</code></a> does:</p>
<pre><code>In [5]: np.unique(a, return_inverse=True)
Out[5]: (array([ 2, 5, 13, 222]), array([1, 0, 2, 2, 3]))
</code><... | 2 | 2016-06-08T03:48:15Z | [
"python",
"numpy",
"scipy"
] |
Performing an indirect sort in numpy, preserving same indices for identical elements | 37,692,618 | <p>Let's assume I have an array like this:</p>
<pre><code>a = np.array([5, 2, 13, 13, 222])
</code></pre>
<p>I want to convert it to an array like this:</p>
<pre><code>b = np.array([1, 0, 2, 2, 3])
</code></pre>
<p>I've tried np.argsort, but returns</p>
<pre><code>np.argsort(np.array([5, 2, 13, 13, 222])) # = arra... | 2 | 2016-06-08T03:14:20Z | 37,693,001 | <p>And in case you needed something similar but without the <code>numpy</code> library</p>
<pre><code>a = [5, 2, 13, 13, 222]
b = [1, 0, 2, 2, 3]
min_ranks = {}
for rank,key in enumerate(sorted(a)):
min_ranks[key] = min(rank, min_ranks[key]) if key in min_ranks else rank
c = [ min_ranks[k] for k in a]
print(c)
</... | 0 | 2016-06-08T04:00:59Z | [
"python",
"numpy",
"scipy"
] |
Unescape strings in Python | 37,692,629 | <p>I have an input file that contains a list of inputs, one per line. Each line of input is enclosed in double quotes. The inputs sometimes have a backslash or few double-quotes as within the enclosing double-quotes (check example below).</p>
<p>Sample inputs â</p>
<pre><code>"each line is enclosed in double-quotes... | 2 | 2016-06-08T03:15:29Z | 37,692,671 | <p>Add <code>+</code> after backslash.</p>
<pre><code>return re.sub(r'\\+"', '`', line)
</code></pre>
| 1 | 2016-06-08T03:20:40Z | [
"python",
"regex",
"string"
] |
Unescape strings in Python | 37,692,629 | <p>I have an input file that contains a list of inputs, one per line. Each line of input is enclosed in double quotes. The inputs sometimes have a backslash or few double-quotes as within the enclosing double-quotes (check example below).</p>
<p>Sample inputs â</p>
<pre><code>"each line is enclosed in double-quotes... | 2 | 2016-06-08T03:15:29Z | 37,692,718 | <p>This is not quite what you asked for as it replaces with <code>"</code> rather than `, but I'll mention it ... you could always leverage off <code>csv</code> to do <code>\"</code> conversion correctly for you:</p>
<pre><code>>>> for line in csv.reader(["each line is enclosed in double-quotes",
... ... | 2 | 2016-06-08T03:26:14Z | [
"python",
"regex",
"string"
] |
Adding a time.sleep to a multithreaded program solves a UnicodeDecodeError in python | 37,692,680 | <p>Here's a basic idea of the threads that I am creating in my program: </p>
<pre><code> Main thread
|
ListenerCreator(The WebSocketServer thread) ---> Several listener threads(using log())
</code></pre>
<p>So the main thread creates a ListenerCreator thread, which connects to a number of clients and c... | 1 | 2016-06-08T03:21:53Z | 37,692,850 | <p>Currently there is no information about how the listener is reading data off the socket. It seems likely however that this is being caused by the usual misunderstanding of sockets.</p>
<p>Data sent down a socket is not "framed" in any way by the socket. Imagine if I sent the message "hello" three times down a soc... | 0 | 2016-06-08T03:43:34Z | [
"python",
"multithreading",
"sockets",
"websocket"
] |
How to loop parse pattern from MySql table using python | 37,692,683 | <p>I'm trying to parse scrapy result with regex, the thing is my regex patterns located in MySQL table.. i have trouble to loop the pattern in sequence in order to return clean content without any html tags..
simply say html result scrapy -> parse with pattern in row1 (ex: clean html above content), parse with pattern ... | 0 | 2016-06-08T03:22:09Z | 37,714,631 | <p>@insecte, look at <a href="https://github.com/scalingexcellence/scrapybook/blob/master/ch05/generic/generic/spiders/fromcsv.py" rel="nofollow">this</a> nice little spider. It reads <a href="https://github.com/scalingexcellence/scrapybook/blob/master/ch05/generic/todo.csv" rel="nofollow">this</a> CSV file and does ge... | 1 | 2016-06-08T23:33:22Z | [
"python",
"mysql",
"regex",
"scrapy"
] |
How to loop parse pattern from MySql table using python | 37,692,683 | <p>I'm trying to parse scrapy result with regex, the thing is my regex patterns located in MySQL table.. i have trouble to loop the pattern in sequence in order to return clean content without any html tags..
simply say html result scrapy -> parse with pattern in row1 (ex: clean html above content), parse with pattern ... | 0 | 2016-06-08T03:22:09Z | 37,742,932 | <p>Your loop <code>for mbuh in response.xpath('//body')</code> only executes once as that xpath returns just one selector. Then you use <code>mmhtml = mbuh.xpath(etc)</code> which will always return the same data no matter what is in mbuh because the xpath starts with '//' which means 'search from the of the start of t... | 0 | 2016-06-10T07:57:46Z | [
"python",
"mysql",
"regex",
"scrapy"
] |
How to loop parse pattern from MySql table using python | 37,692,683 | <p>I'm trying to parse scrapy result with regex, the thing is my regex patterns located in MySQL table.. i have trouble to loop the pattern in sequence in order to return clean content without any html tags..
simply say html result scrapy -> parse with pattern in row1 (ex: clean html above content), parse with pattern ... | 0 | 2016-06-08T03:22:09Z | 37,781,349 | <p>I think i solved my own question, maybe i'm not good at describing my question above but all i want is make the result from first pattern to be the subject for the second pattern, and then continue to the next pattern from mysql table.. </p>
<p>all i did was just changed</p>
<pre><code>k1 = re.sub(fpattern , frepl... | 0 | 2016-06-13T03:19:08Z | [
"python",
"mysql",
"regex",
"scrapy"
] |
Suds Message is missing Element. Soapui creates the correct message from the WSDL | 37,692,721 | <p>I have seen related questions to this in posts that are 6 or 7 years old, but have not found a good answer. The DELV_NUM element is in the WSDL, but I believe it is marked as optional and mybe the reason suds ignores it.
I did not make the WSDL file and cannot make changes to it. If I can modify the suds message to... | 1 | 2016-06-08T03:26:31Z | 38,341,263 | <p>In order to add the element to the request, you can use the client.factory.create() method.</p>
<p>Solution could work like this:</p>
<pre><code># Create a Processing_Req object
processing_req = client.factory.create('{http://wackerneuson.com/wn/in/Conveyor_Belt/ConveyorBeltProcessing}Processing_Req')
# Create a... | 0 | 2016-07-13T01:28:53Z | [
"python",
"web-services",
"wsdl",
"suds",
"ignition"
] |
Re-write the for loop function in python, need help to understand better | 37,692,777 | <p>I'm new to python and I need help to re-write that for loop function with indentations below</p>
<pre><code>y = [g(x,y) for x in xs for y in xs if f(x,y)]
</code></pre>
<p>full code is here</p>
<pre><code>g = lambda x,y:(x-y)
f = lambda x,y: x>y
xs = [1,2,3,4]
y = [g(x,y) for x in xs for y in xs if f(x,y)]... | 1 | 2016-06-08T03:33:47Z | 37,692,888 | <pre><code>y = []
for a in xs:
for b in xs:
if f(a, b):
y.append(g(a, b))
</code></pre>
| 1 | 2016-06-08T03:47:44Z | [
"python"
] |
Error 28000: Login failed for user DOMAIN\\user with pyodbc | 37,692,780 | <p>I am trying to use Python to connect to a SQL database by using Window authentication. I looked at some of the posts here (e.g., <a href="http://stackoverflow.com/questions/10000256/failed-to-login-as-domain-computername-pyodbc-with-py2exe">here</a>), but the suggested methods didn't seem to work.</p>
<p>For exampl... | 4 | 2016-06-08T03:34:33Z | 37,692,988 | <p>Try this cxn string: </p>
<pre><code>cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;PORT=1433;DATABASE=testdb;UID=me;PWD=pass')
</code></pre>
<p><a href="http://mkleehammer.github.io/pyodbc/" rel="nofollow">http://mkleehammer.github.io/pyodbc/</a></p>
| 0 | 2016-06-08T03:59:34Z | [
"python",
"sql-server",
"pyodbc"
] |
Error 28000: Login failed for user DOMAIN\\user with pyodbc | 37,692,780 | <p>I am trying to use Python to connect to a SQL database by using Window authentication. I looked at some of the posts here (e.g., <a href="http://stackoverflow.com/questions/10000256/failed-to-login-as-domain-computername-pyodbc-with-py2exe">here</a>), but the suggested methods didn't seem to work.</p>
<p>For exampl... | 4 | 2016-06-08T03:34:33Z | 37,702,329 | <p><code>Trusted_connection=yes</code> tells the SQL Server to use "Windows Authentication" and your script will attempt to log in to the SQL Server using the Windows credentials of the user running the script. </p>
<p>If you want to use "SQL Server Authentication" with a specific SQL Server login specified by <code>U... | 2 | 2016-06-08T12:19:56Z | [
"python",
"sql-server",
"pyodbc"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.