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 |
|---|---|---|---|---|---|---|---|---|---|
How can one suppress evaluation while still being able to index? | 39,375,880 | <p>I have two small but very complicated matrices that I want to multiply. I've done this using sympy:</p>
<pre><code>C=sympy.MatMul(A,B,hold=True)
</code></pre>
<p>This gives me a MatMul object which saves a huge amount of time, and I'm not interested in a symbolic expression anyway, rather I want to evaluate at spe... | 2 | 2016-09-07T17:20:59Z | 39,376,135 | <p>You can index elements of <code>C</code>, e.g. <code>C[0,0]</code>. So this will give you the first row as a list:</p>
<pre><code>row0 = [C[0, k] for k in range(C.shape[1])]
</code></pre>
<p>Here's an example. <code>x</code> and <code>y</code> are sympy symbols.</p>
<pre><code>In [40]: A
Out[40]:
Matrix([
[2*x... | 3 | 2016-09-07T17:37:11Z | [
"python",
"numpy",
"math",
"indexing",
"sympy"
] |
How can one suppress evaluation while still being able to index? | 39,375,880 | <p>I have two small but very complicated matrices that I want to multiply. I've done this using sympy:</p>
<pre><code>C=sympy.MatMul(A,B,hold=True)
</code></pre>
<p>This gives me a MatMul object which saves a huge amount of time, and I'm not interested in a symbolic expression anyway, rather I want to evaluate at spe... | 2 | 2016-09-07T17:20:59Z | 39,419,050 | <p>To explain the error, normally, a single index indexes a matrix row-by-row:</p>
<pre><code>In [8]: M = Matrix([[1, 2], [3, 4]])
In [9]: M
Out[9]:
â¡1 2â¤
⢠â¥
â£3 4â¦
In [10]: M[0]
Out[10]: 1
In [11]: M[1]
Out[11]: 2
In [12]: M[2]
Out[12]: 3
In [14]: M[3]
Out[14]: 4
</code></pre>
<p>For a symbolic... | 1 | 2016-09-09T20:10:17Z | [
"python",
"numpy",
"math",
"indexing",
"sympy"
] |
Inserting an element before each element of a list | 39,375,906 | <p>I'm looking to insert a constant element before each of the existing element of a list, i.e. go from:</p>
<pre><code>['foo', 'bar', 'baz']
</code></pre>
<p>to:</p>
<pre><code>['a', 'foo', 'a', 'bar', 'a', 'baz']
</code></pre>
<p>I've tried using list comprehensions but the best thing I can achieve is an array of... | 4 | 2016-09-07T17:22:29Z | 39,375,937 | <p>Add another loop:</p>
<pre><code>[v for elt in stuff for v in ('a', elt)]
</code></pre>
<p>or use <a href="https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable"><code>itertools.chain.from_iterable()</code></a> together with <a href="https://docs.python.org/3/library/functions.html#zip"><c... | 8 | 2016-09-07T17:24:13Z | [
"python",
"list",
"python-3.x",
"list-comprehension"
] |
Inserting an element before each element of a list | 39,375,906 | <p>I'm looking to insert a constant element before each of the existing element of a list, i.e. go from:</p>
<pre><code>['foo', 'bar', 'baz']
</code></pre>
<p>to:</p>
<pre><code>['a', 'foo', 'a', 'bar', 'a', 'baz']
</code></pre>
<p>I've tried using list comprehensions but the best thing I can achieve is an array of... | 4 | 2016-09-07T17:22:29Z | 39,376,091 | <p>A simple generator function works nicely here too:</p>
<pre><code>def add_between(iterable, const):
# TODO: think of a better name ... :-)
for item in iterable:
yield const
yield item
list(add_between(['foo', 'bar', 'baz'], 'a')
</code></pre>
<p>This lets you avoid a nested list-comprehens... | 3 | 2016-09-07T17:34:01Z | [
"python",
"list",
"python-3.x",
"list-comprehension"
] |
Inserting an element before each element of a list | 39,375,906 | <p>I'm looking to insert a constant element before each of the existing element of a list, i.e. go from:</p>
<pre><code>['foo', 'bar', 'baz']
</code></pre>
<p>to:</p>
<pre><code>['a', 'foo', 'a', 'bar', 'a', 'baz']
</code></pre>
<p>I've tried using list comprehensions but the best thing I can achieve is an array of... | 4 | 2016-09-07T17:22:29Z | 39,376,122 | <p>You already have </p>
<pre><code> l = [['a', 'foo'], ['a', 'bar], ['a', 'baz']]
</code></pre>
<p>You can flatten it using </p>
<pre><code>[item for sublist in l for item in sublist]
</code></pre>
<p>this even works for arbitrary length nested list.</p>
| 1 | 2016-09-07T17:36:06Z | [
"python",
"list",
"python-3.x",
"list-comprehension"
] |
How to pass dictionary to functions? | 39,375,912 | <p>I want to pass dictionary to user defined functions and I need to do some calculation based on the dictionary values. It is not working for me with functions but works fine without using functions. I am not sure, what is wrong with code. Any help please? No error message.</p>
<p>Input:</p>
<blockquote>
<p>"13-07... | 0 | 2016-09-07T17:22:55Z | 39,376,027 | <p>When you write a function in Python using the <code>def</code> keyword, the function is not automatically executed. You are never calling your <code>setdict</code> or <code>display</code> functions, just defining them so they can be called later.</p>
<p>Add this line to the end of your script to actually call the f... | 1 | 2016-09-07T17:29:51Z | [
"python",
"dictionary"
] |
How to pass dictionary to functions? | 39,375,912 | <p>I want to pass dictionary to user defined functions and I need to do some calculation based on the dictionary values. It is not working for me with functions but works fine without using functions. I am not sure, what is wrong with code. Any help please? No error message.</p>
<p>Input:</p>
<blockquote>
<p>"13-07... | 0 | 2016-09-07T17:22:55Z | 39,376,067 | <p><strong>A:</strong> You should consider to call your functions at the end of the script:</p>
<pre><code>dico = setdict()
display(dico)
</code></pre>
<p>Without that, they are declared, but not used.</p>
<p><strong>B:</strong> You should also consider a better way to open your file:</p>
<pre><code>with open(file_... | 2 | 2016-09-07T17:32:46Z | [
"python",
"dictionary"
] |
Modify string in bash to contain new line character? | 39,375,977 | <p>I am using a bash script to call google-api's upload_video.py (<a href="https://developers.google.com/youtube/v3/guides/uploading_a_video" rel="nofollow">https://developers.google.com/youtube/v3/guides/uploading_a_video</a> )</p>
<p>I have a mp4 called output.mp4 which I would like to upload.</p>
<p>The problem is... | 0 | 2016-09-07T17:26:56Z | 39,376,935 | <p>This is much simpler than you are making it.</p>
<pre><code># Operator may change these
hold=100
location="Foo, Montana"
declare -a file_array=("unique_ID_0" "unique_ID_1")
upload_file=upload_file.txt
upload_movie=output.mp4
upload_title="$location - ${file_array[0]} - Hold $hold Sweeps"
upload_description="The s... | 0 | 2016-09-07T18:34:27Z | [
"python",
"bash",
"google-api"
] |
Modify string in bash to contain new line character? | 39,375,977 | <p>I am using a bash script to call google-api's upload_video.py (<a href="https://developers.google.com/youtube/v3/guides/uploading_a_video" rel="nofollow">https://developers.google.com/youtube/v3/guides/uploading_a_video</a> )</p>
<p>I have a mp4 called output.mp4 which I would like to upload.</p>
<p>The problem is... | 0 | 2016-09-07T17:26:56Z | 39,379,964 | <p>I figured it out with help from chepner's answer. My question hid the fact that I wanted to write new line characters into the video's description.</p>
<p>Instead of adding a new line character in the bash script, it is much easier to have a text file which contains the correctly formatted script and read it in, th... | 0 | 2016-09-07T22:31:29Z | [
"python",
"bash",
"google-api"
] |
Sorting words in a list of strings based on their relative frequencies, not regular sorting? | 39,376,043 | <p>Suppose I have a <code>pandas.Series</code> object:</p>
<pre><code>import pandas as pd
s = pd.Series(["hello there you would like to sort me",
"sorted i would like to be", "the banana does not taste like the orange",
"my friend said hello", "hello there amigo", "apple apple banana orange peach pear plum"... | 0 | 2016-09-07T17:30:38Z | 39,376,064 | <pre><code>print create_word_freq_dict(series).most_common()
</code></pre>
| 0 | 2016-09-07T17:32:34Z | [
"python",
"sorting"
] |
Sorting words in a list of strings based on their relative frequencies, not regular sorting? | 39,376,043 | <p>Suppose I have a <code>pandas.Series</code> object:</p>
<pre><code>import pandas as pd
s = pd.Series(["hello there you would like to sort me",
"sorted i would like to be", "the banana does not taste like the orange",
"my friend said hello", "hello there amigo", "apple apple banana orange peach pear plum"... | 0 | 2016-09-07T17:30:38Z | 39,376,255 | <h1>Python 2</h1>
<p>All you have to do is create custom comparator based on your counter and call sorting</p>
<pre><code>s = ["hello there you would like to sort me",
"sorted i would like to be", "the banana does not taste like the orange",
"my friend said hello", "hello there amigo", "apple apple banana o... | 1 | 2016-09-07T17:45:04Z | [
"python",
"sorting"
] |
python pandas binning incorrect column format list of lists | 39,376,070 | <p>I am working through an example to bin columns using pandas. I am trying to use the django graphos library to plot the distribution and in order to do this I need to convert the binned output into a list of lists. Below is a snippet of the data I start with. </p>
<pre><code> A
1 8.78
2 9.46
3 8.... | 0 | 2016-09-07T17:32:55Z | 39,383,389 | <p>I was doing pretty much what you were in the comments:</p>
<pre><code>binList = groups.index.tolist()
countList = [count[0] for count in groups.values.tolist()] # groups.values.tolist() comes as a list of lists
binList = [[binStr.replace('(', '').replace(']', ''), count] for binStr, count in zip(binList, countList)... | 1 | 2016-09-08T05:47:50Z | [
"python",
"pandas",
"numpy"
] |
Python 2.7 Argparse Optional and Required arguments | 39,376,095 | <p>So I've been frantically reading tutorials on argparse everywhere but can't seem to figure out why my program is getting an error. My code currently looks like this:</p>
<pre><code>parser = argparse.ArgumentParser()
parser.add_argument("-d", "-debug", required = False, help = "optional parameter")
parser.add_argume... | 0 | 2016-09-07T17:34:20Z | 39,376,148 | <p>The <a href="https://docs.python.org/2.7/library/argparse.html#action" rel="nofollow">default action</a> for an argument is <code>'store'</code>. <code>store</code> actions generally expect a <em>value</em> to be associated with the flag.</p>
<p>It looks like you want this to be a boolean switch type of flag in wh... | 2 | 2016-09-07T17:37:42Z | [
"python",
"python-2.7",
"command-line-arguments"
] |
Keras Convolution2D Input: Error when checking model input: expected convolution2d_input_1 to have shape | 39,376,169 | <p>I am working through <a href="https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html" rel="nofollow">this great tutorial</a> on creating an image classifier using Keras. Once I have trained the model, I save it to a file and then later reload it into a model in a test script... | 0 | 2016-09-07T17:38:57Z | 39,377,182 | <p>The issue was two-fold:</p>
<ol>
<li><p>The test image was the wrong size. It was 150 x 198, and needed to be 150 x 150.</p></li>
<li><p>I had to change the dense layer from <code>model.add(Dense(10))</code> to <code>model.add(Dense(1))</code>.</p></li>
</ol>
<p>I don't yet understand how to get the model to give... | 0 | 2016-09-07T18:50:33Z | [
"python",
"numpy",
"machine-learning",
"theano",
"keras"
] |
Not able to download pyxplorer package using pip? | 39,376,231 | <p>I referring url to profile data and to profile the data we need pyxplorer inside of python interpreter but when i try to install pyxplorer package it gives me error like:</p>
<p>Collecting pyxplorer
Could not find a version that satisfies the requirement pyxplorer (from versions: ) No matching distribution found ... | 3 | 2016-09-07T17:43:03Z | 39,376,884 | <p>It looks like the <code>pyxplorer</code> package on PyPI is invalid and doesn't actually contain any release data. Have a look at the releases key of the <a href="https://pypi.python.org/pypi/pyxplorer/json" rel="nofollow">JSON for <code>pyxplorer</code></a> - it's an empty array, but normal packages look more like ... | 1 | 2016-09-07T18:30:53Z | [
"python"
] |
Django ManyToMany Field with field name values | 39,376,243 | <p><a href="http://i.stack.imgur.com/3KSpq.png" rel="nofollow"><img src="http://i.stack.imgur.com/3KSpq.png" alt="ManyToMany Field Coming as object"></a></p>
<h1>model.py</h1>
<pre><code>class MedtechProductCategory(models.Model):
name = models.CharField(max_length=128, null=False, blank=False)
type = models.CharFiel... | 3 | 2016-09-07T17:43:48Z | 39,376,312 | <p>Add a <code>__unicode__</code> method to your model which will return the string that you want to use.</p>
<p>For python 3, use <code>__str__</code> instead.</p>
<pre><code># on ProductsInfo model
def __str__(self):
return self.category.name
</code></pre>
| 3 | 2016-09-07T17:48:41Z | [
"python",
"django",
"django-models",
"django-forms",
"django-admin"
] |
linear regression model prediction in scikit-learn is inconsistent | 39,376,410 | <p>So I built a simple linear regression model with a handful of features. When I try to predict for new input, the output is inconsistent. For example:</p>
<pre><code>In [1]: model.predict(X_new)
Out[1]: array([ 7.15993216e+08, 1.13548305e+09])
</code></pre>
<p>But if I tack it onto the original training sample... | 0 | 2016-09-07T17:54:39Z | 39,417,345 | <p>This seems to be an issue with the sorting order of the pandas data frame. A solution for this is to pre-sort both training and testing data sets by the same column order. Something along the lines of:</p>
<pre><code>model.fit(np.array(X_training.sort_index(1)))
model.predict(np.array(new_input.sort_index(1)))
</... | 0 | 2016-09-09T18:04:48Z | [
"python",
"scikit-learn"
] |
AttributeError: type object has no attribute "id" PYTHON | 39,376,420 | <p>So I was trying to make a basic python pong game when this error came up:
It seems to say that AttributeError: type object has no attribute "id" which I have no idea what it means.</p>
<pre><code>C:\Users\****\AppData\Local\Programs\Python\Python35-32\python.exe C:/Users/****/untitled/src/testing.py
Traceback (most... | -1 | 2016-09-07T17:55:08Z | 39,376,459 | <pre><code>paddle = Paddle(canvas, 'blue')
ball = Ball(canvas, paddle, Paddle2, 'red')
paddle2 = Paddle2(canvas, 'blue')
</code></pre>
<p>should you pass in the paddle2 instance? like this? </p>
<pre><code>paddle = Paddle(canvas, 'blue')
paddle2 = Paddle2(canvas, 'blue')
ball = Ball(canvas, paddle, paddle2, 'red')
</... | 1 | 2016-09-07T17:58:36Z | [
"python"
] |
AttributeError: type object has no attribute "id" PYTHON | 39,376,420 | <p>So I was trying to make a basic python pong game when this error came up:
It seems to say that AttributeError: type object has no attribute "id" which I have no idea what it means.</p>
<pre><code>C:\Users\****\AppData\Local\Programs\Python\Python35-32\python.exe C:/Users/****/untitled/src/testing.py
Traceback (most... | -1 | 2016-09-07T17:55:08Z | 39,376,463 | <p>You need to pass instances of <code>Paddle</code> and <code>Paddle2</code> to <code>Ball</code> constructor.</p>
<pre><code>paddle = Paddle(canvas, 'blue')
paddle2 = Paddle2(canvas, 'blue')
ball = Ball(canvas, paddle, paddle2, 'red')
</code></pre>
| 2 | 2016-09-07T17:58:53Z | [
"python"
] |
Python copy parts of dictionary into a new dictionary | 39,376,563 | <p>I have a python dictionary which looks like this:</p>
<pre><code>old_dict={"payment_amt": "20",
"chk_nr": "321749",
"clm_list": {"dtl": [{"clm_id": "1A2345", "name": "John"},
{"clm_id": "9999", "name": "Jack"}]}}
</code></pre>
<p>I need to parse the above and stor... | 1 | 2016-09-07T18:05:50Z | 39,376,706 | <p>Yes, there are many "<em>right pythonic ways to do it</em>".
Here is one such way:</p>
<pre><code>old_dict = {
"payment_amt": "20",
"chk_nr": "321749",
"clm_list": {
"dtl": [
{"clm_id": "1A2345", "name": "John"},
{"clm_id": "9999", "name": "Jack"}]}}
new_dict = {
'pa... | 2 | 2016-09-07T18:16:58Z | [
"python",
"dictionary"
] |
Python copy parts of dictionary into a new dictionary | 39,376,563 | <p>I have a python dictionary which looks like this:</p>
<pre><code>old_dict={"payment_amt": "20",
"chk_nr": "321749",
"clm_list": {"dtl": [{"clm_id": "1A2345", "name": "John"},
{"clm_id": "9999", "name": "Jack"}]}}
</code></pre>
<p>I need to parse the above and stor... | 1 | 2016-09-07T18:05:50Z | 39,376,899 | <p>You could create a "template" dictionary/list/whatever and define a recursive method that traverses both the input object (some sort of nested list/dictionary thing) and the template in parallel and just keeps those elements that are in the respective place in the template. In a basic version, this could look like t... | 1 | 2016-09-07T18:32:00Z | [
"python",
"dictionary"
] |
Python copy parts of dictionary into a new dictionary | 39,376,563 | <p>I have a python dictionary which looks like this:</p>
<pre><code>old_dict={"payment_amt": "20",
"chk_nr": "321749",
"clm_list": {"dtl": [{"clm_id": "1A2345", "name": "John"},
{"clm_id": "9999", "name": "Jack"}]}}
</code></pre>
<p>I need to parse the above and stor... | 1 | 2016-09-07T18:05:50Z | 39,376,926 | <p>Personally, I would go with a straightforward copy of the exact keys you want to keep in the example you posted (see Rob's answer), if the input is always exactly like you listed. Keep it simple.</p>
<p>However, if you can't rely on the input to always have the same exact structure, you can still reduce it to only ... | 2 | 2016-09-07T18:33:59Z | [
"python",
"dictionary"
] |
Edited - Python plot persistence windows | 39,376,670 | <p>Each time I launch my program, my plots are erased after each execution.</p>
<p>I would like the following situation:</p>
<ol>
<li>Launch program 1 and plot in figure 1</li>
<li>Stop the execution of program 1</li>
<li>Lauch program 2 and plot in figure 1</li>
<li>Retrieve a pdf file where the plot of program 1 an... | 2 | 2016-09-07T18:13:57Z | 39,376,911 | <p><code>plt.show(block=True)</code> should work.</p>
<p>Other hack would be using pause function as shown below:</p>
<pre><code>from matplotlib import pylab
pylab.plot(range(10), range(10))
pylab.pause(2**31-1)
</code></pre>
| 0 | 2016-09-07T18:32:51Z | [
"python",
"python-2.7",
"matplotlib"
] |
append columns to pandas dataframe with duplicate rows | 39,376,755 | <p>How can I append the columns from the <code>data</code> dataframe to the <code>q</code> dataframe, while maintaining the same order and number of rows in <code>q</code>? The challenge is that there can be duplicates in <code>data</code> and <code>q</code>.</p>
<pre><code>In [2]: data = pd.DataFrame([[3,4,333],[5,6,... | 0 | 2016-09-07T18:21:18Z | 39,376,909 | <p>One possible solution without drop duplicates is create new columns in both <code>DataFrames</code> by <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.GroupBy.cumcount.html" rel="nofollow"><code>cumcount</code></a> and then <a href="http://pandas.pydata.org/pandas-docs/stable/gener... | 0 | 2016-09-07T18:32:41Z | [
"python",
"pandas"
] |
append columns to pandas dataframe with duplicate rows | 39,376,755 | <p>How can I append the columns from the <code>data</code> dataframe to the <code>q</code> dataframe, while maintaining the same order and number of rows in <code>q</code>? The challenge is that there can be duplicates in <code>data</code> and <code>q</code>.</p>
<pre><code>In [2]: data = pd.DataFrame([[3,4,333],[5,6,... | 0 | 2016-09-07T18:21:18Z | 39,376,979 | <p>You could use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow"><code>join</code></a> to join the columns of the two dataframes on a common index, <code>id</code>. Then, drop the duplicated values along with dropping off <code>Nans</code> if present as shown:</... | 1 | 2016-09-07T18:37:19Z | [
"python",
"pandas"
] |
In Python, how to deep copy the Namespace obj "args" from argparse | 39,376,763 | <p>I got "args" from argparse:</p>
<blockquote>
<p>args = parser.parse_args()</p>
</blockquote>
<p>I want to pass it to two different functions with slight modifications each. That's why I want to deep copy the args, modify the copy and pass them to each function. </p>
<p>However, the copy.deepcopy just doesn't wo... | 0 | 2016-09-07T18:21:40Z | 39,378,639 | <p>I myself just figured out a way to do it:</p>
<pre><code>args_copy = Namespace(**vars(args))
</code></pre>
<p>Not real deep copy. But at least "deeper" than:</p>
<pre><code>args_copy = args
</code></pre>
| 0 | 2016-09-07T20:40:08Z | [
"python",
"copy",
"argparse"
] |
Convert length 1 nested lists into strings | 39,376,830 | <p>I have this list, in Python, with some nested lists inside with length 1:</p>
<p>[<strong>['7746']</strong>, '12', '1929', '8827', <strong>['7']</strong>, '8837', '128']</p>
<p>I want to get rid of the lists and just keep the string inside and get:</p>
<p>[<strong>'7746'</strong>, '12', '1929', '8827', <strong>'7... | -2 | 2016-09-07T18:26:05Z | 39,383,553 | <p>You can use a <a class='doc-link' href="http://stackoverflow.com/documentation/python/196/comprehensions/737/list-comprehensions#t=201609080600574325476">list comprehension</a> and a ternary conditional:</p>
<pre><code>empty = [(x[0] if isinstance(x, list) else x) for x in nested]
</code></pre>
<p>Alternatively, t... | 0 | 2016-09-08T06:03:30Z | [
"python",
"list"
] |
Python3, json causes TypeError but simplejson doesn't | 39,376,847 | <p>I'm running the latest Python3 (with the Anaconda distribution) and have a problem with the standard library installed json which causes the Traceback:</p>
<pre><code> Traceback (most recent call last):
File "C:\Users\Think\Anaconda3\lib\site-packages\werkzeug\serving.py", line 193, in run_wsgi
exe... | 0 | 2016-09-07T18:27:27Z | 39,376,874 | <p>Use <code>str.decode('utf-8')</code> before passing to <code>json.loads</code></p>
<p>I think this line:</p>
<pre><code>return json.loads(data)
</code></pre>
<p>is causing the problem. Decode data before passing it to this function.</p>
| 1 | 2016-09-07T18:30:15Z | [
"python",
"json",
"python-3.x"
] |
How to separate thousands with commas using Facet Grid in Seaborn | 39,376,888 | <p>I have the following code:</p>
<pre><code> d = sns.FacetGrid(data = df,
col = 'Company',
sharex = False,
sharey = False,
col_wrap = 4)
d.map(sns.distplot, 'Volume', kde = False, rug = True, fit = stats.norm)
d.set_xla... | 0 | 2016-09-07T18:31:31Z | 39,377,865 | <p>Specify the <code>ax</code> inside the <code>FacetGrid</code>:</p>
<pre><code>df = random((5, 5))
d = sns.FacetGrid(data=df)
dir(d.ax.get_xaxis())
</code></pre>
<p>and aha, <code>get_major_formatter</code> is in that list. </p>
| 0 | 2016-09-07T19:41:02Z | [
"python",
"matplotlib",
"seaborn",
"facet"
] |
Why is numpy's sine function so inaccurate at some points? | 39,376,891 | <p>I just checked <code>numpy</code>'s <code>sine</code> function. Apparently, it produce highly inaccurate results around pi. </p>
<pre><code>In [26]: import numpy as np
In [27]: np.sin(np.pi)
Out[27]: 1.2246467991473532e-16
</code></pre>
<p>The expected result is 0. Why is <code>numpy</code> so inaccurate there?<... | -1 | 2016-09-07T18:31:38Z | 39,376,999 | <p>The value is dependent upon the algorithm used to compute it. A typical implementation will use some quickly-converging infinite series, carried out until it converges within one machine epsilon. Many modern chips (starting with the Intel 960, I think) had such functions in the instruction set.</p>
<p>To get 0 re... | -1 | 2016-09-07T18:38:51Z | [
"python",
"numpy",
"floating-point"
] |
Why is numpy's sine function so inaccurate at some points? | 39,376,891 | <p>I just checked <code>numpy</code>'s <code>sine</code> function. Apparently, it produce highly inaccurate results around pi. </p>
<pre><code>In [26]: import numpy as np
In [27]: np.sin(np.pi)
Out[27]: 1.2246467991473532e-16
</code></pre>
<p>The expected result is 0. Why is <code>numpy</code> so inaccurate there?<... | -1 | 2016-09-07T18:31:38Z | 39,377,219 | <p>The main problem here is that <code>np.pi</code> is not exactly Ï, it's a finite binary floating point number that is close to the true irrational real number Ï but still off by ~1e-16. <code>np.sin(np.pi)</code> is actually returning a value closer to the true infinite-precision result for <code>sin(np.pi)</code>... | 6 | 2016-09-07T18:53:20Z | [
"python",
"numpy",
"floating-point"
] |
Creating a NumPy array directly from __array_interface__ | 39,376,892 | <p>Suppose I have an <code>__array_interface__</code> dictionary and I would like to create a numpy view of this data from the dictionary itself. For example:</p>
<pre><code>buff = {'shape': (3, 3), 'data': (140546686381536, False), 'typestr': '<f8'}
view = np.array(buff, copy=False)
</code></pre>
<p>However, this... | 2 | 2016-09-07T18:31:40Z | 39,377,877 | <p>correction - with the right 'data' value your <code>holder</code> works in <code>np.array</code>:</p>
<p><code>np.array</code> is definitely not going to work since it expects an iterable, some things like a list of lists, and parses the individual values.</p>
<p>There is a low level constructor, <code>np.ndarray<... | 2 | 2016-09-07T19:41:49Z | [
"python",
"numpy",
"pybinding"
] |
NaNs suddenly appearing for sklearn KFolds | 39,376,967 | <p>I'm trying to run cross validation on my data set. The data appears to be clean, but then when I try to run it, some of my data gets replaced by NaNs. I'm not sure why. Has anybody seen this before?</p>
<pre><code>y, X = np.ravel(df_test['labels']), df_test[['variation', 'length', 'tempo']]
X_train, X_test, y_train... | 0 | 2016-09-07T18:36:31Z | 39,379,816 | <p>To solve use <code>.iloc</code> instead of <code>.ix</code> to index your pandas dataframe</p>
<pre><code>for train_index, val_index in kf:
cv_train_x = X_train.iloc[train_index]
cv_val_x = X_train.iloc[val_index]
cv_train_y = y_train[train_index]
cv_val_y = y_train[val_index]
print cv_train_x
... | 1 | 2016-09-07T22:15:41Z | [
"python",
"machine-learning",
"scikit-learn",
"cross-validation"
] |
Web Scraping Javascript Using Python | 39,376,972 | <p>I am used to using BeautifulSoup to scrape a website, however this website is different. Upon soup.prettify() I get back Javascript code, lots of stuff. I want to scrape this website for the data on the actual website (company name, telephone number etc). Is there a way of scraping these scripts such as Main.js to ... | -3 | 2016-09-07T18:36:44Z | 39,377,235 | <p>You're asking if you can scrape text generated at runtime by Javascript. The answer is sort-of.</p>
<p>You'd need to run some kind of <a href="https://github.com/dhamaniasad/HeadlessBrowsers" rel="nofollow">headless browser</a>, like PhantomJS, in order to let the Javascript execute and populate the page. You'd the... | 1 | 2016-09-07T18:54:08Z | [
"python",
"python-2.7"
] |
Compute all ways to bin a series of integers into N bins, where each bin only contains contiguous numbers | 39,376,987 | <p>I want find all possible ways to map a series of (contiguous) integers M = {0,1,2,...,m} to another series of integers N = {0,1,2,...,n} where m > n, <em>subject to the constraint that only contiguous integers in M map to the same integer in N.</em> </p>
<p>The following piece of python code comes close (<code>star... | 1 | 2016-09-07T18:37:56Z | 39,378,085 | <p>This does what I want; I will gladly accept simpler, more elegant solutions:</p>
<pre><code>def _split(start, stop, nbins):
if (nbins > 1):
out = []
for ii in range(start+1, stop-nbins+2):
iterator = itertools.product([range(start, ii)], _split(ii, stop, nbins-1))
for ... | 0 | 2016-09-07T19:58:49Z | [
"python",
"combinatorics"
] |
Compute all ways to bin a series of integers into N bins, where each bin only contains contiguous numbers | 39,376,987 | <p>I want find all possible ways to map a series of (contiguous) integers M = {0,1,2,...,m} to another series of integers N = {0,1,2,...,n} where m > n, <em>subject to the constraint that only contiguous integers in M map to the same integer in N.</em> </p>
<p>The following piece of python code comes close (<code>star... | 1 | 2016-09-07T18:37:56Z | 39,378,895 | <p>I suggest a different approach: a partitioning into <code>n</code> non-empty bins is uniquely determined by the <code>n-1</code> distinct indices marking the boundaries between the bins, where the first marker is after the first element, and the final marker before the last element. <code>itertools.combinations()<... | 1 | 2016-09-07T20:58:50Z | [
"python",
"combinatorics"
] |
Why no colors in bokeh plot's legend | 39,376,990 | <p>In Bokeh 0.12.2, I was able to make a stacked bar chart with various hover tooltips using plotting and VBars. I also enabled a legend for the plot. However, my vbars are colored and the colors for each vbar (each stack) are not appearing in the legend. Only the names for the stack in the legend are appearing. Is thi... | 0 | 2016-09-07T18:38:11Z | 39,708,656 | <p>This was due to a bug in the bokeh source code which is being fixed if not fixed already.</p>
| 0 | 2016-09-26T17:15:07Z | [
"python",
"colors",
"legend",
"bokeh"
] |
Pandas - Creating multiple columns similar to pd.get_dummies | 39,377,164 | <p>Let's say my data looks like this:</p>
<pre><code>df = pd.DataFrame({'color': ['red', 'blue', 'green', 'red', 'blue', 'blue'], 'line': ['sunday', 'sunday', 'monday', 'monday', 'monday', 'tuesday'],
'group': ['1', '1', '2', '1', '1', '1'], 'value': ['a', 'b', 'a', 'c', 'a', 'b']})
color group ... | 4 | 2016-09-07T18:49:40Z | 39,378,883 | <p>Drop the column you don't need and add a column to get a unique subindex per color:</p>
<pre><code>df = df.drop('group', axis=1)
df['index_by_color'] = df.groupby('color').cumcount()
color line value index_by_color
0 red sunday a 0
1 blue sunday b 0
2 green m... | 0 | 2016-09-07T20:57:35Z | [
"python",
"pandas",
"dataframe"
] |
Pandas - Creating multiple columns similar to pd.get_dummies | 39,377,164 | <p>Let's say my data looks like this:</p>
<pre><code>df = pd.DataFrame({'color': ['red', 'blue', 'green', 'red', 'blue', 'blue'], 'line': ['sunday', 'sunday', 'monday', 'monday', 'monday', 'tuesday'],
'group': ['1', '1', '2', '1', '1', '1'], 'value': ['a', 'b', 'a', 'c', 'a', 'b']})
color group ... | 4 | 2016-09-07T18:49:40Z | 39,382,285 | <p>Consider a merge on two pivoted dfs with column name handling:</p>
<pre><code>df['count'] = df.groupby('color').cumcount() + 1
pvt1 = df.pivot(columns='count', index='color', values='line').reset_index().fillna('')
pvt1.columns = ['color'] + ['line_'+str(c) for c in pvt1.columns[1:]]
pvt2 = df.pivot(columns='coun... | 0 | 2016-09-08T03:46:02Z | [
"python",
"pandas",
"dataframe"
] |
Applying a custom function on a Pandas series using groupby and pd.isnull | 39,377,195 | <p>I have a sample dataframe which generically looks like this:</p>
<pre><code>df = pd.Dataframe({'Class': [1, 2, 3, 2, 1, 2, 3, 2],
'Sex': [1, 0, 0, 0, 1, 1, 0, 1],
'Age': [15, 24, 13, 28, 29, NaN, 34, 27]})
</code></pre>
<p>Which displays as:</p>
<pre><code> Age Class Sex... | 1 | 2016-09-07T18:51:42Z | 39,377,312 | <p>One option would be to use <code>transform</code> to replace null values with median for the <code>Age</code> column:</p>
<pre><code>df['Age'] = df.groupby(['Class', 'Sex']).Age.transform(lambda col: col.where(col.notnull(), col.median()))
df
# Age Class Sex
#0 15.0 1 1
#1 24.0 2 0
#2 13.0 3 ... | 2 | 2016-09-07T18:58:22Z | [
"python",
"pandas"
] |
csv file to numpy array via Python | 39,377,229 | <p>I have a csv file of the following format that I am trying to normalise. The numbers represent the counts for associated strings. The file contains close to 100K entries.</p>
<pre><code>159028,CASSVDGSYEQYFGPG
86832,CASSLQLYFGEG
74720,CASSQDQDTQYFGPG
71701,CASSRVGSDYTFGSG
69360,CARNVTPPKSYAVFFGKG
52458,CAAEQFFGPG
5... | 1 | 2016-09-07T18:53:44Z | 39,377,421 | <p>Use Numpy loadtxt to import, then use a dict comprehension if you need it as a dict.</p>
<pre><code>import numpy as np
arr = np.loadtxt('data.csv', dtype=str, delimiter=",")
b = dict([(y, x) for (x, y) in arr])
</code></pre>
| 1 | 2016-09-07T19:07:32Z | [
"python",
"list",
"csv",
"numpy",
"dictionary"
] |
csv file to numpy array via Python | 39,377,229 | <p>I have a csv file of the following format that I am trying to normalise. The numbers represent the counts for associated strings. The file contains close to 100K entries.</p>
<pre><code>159028,CASSVDGSYEQYFGPG
86832,CASSLQLYFGEG
74720,CASSQDQDTQYFGPG
71701,CASSRVGSDYTFGSG
69360,CARNVTPPKSYAVFFGKG
52458,CAAEQFFGPG
5... | 1 | 2016-09-07T18:53:44Z | 39,377,540 | <p><a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html" rel="nofollow"><code>genfromtxt</code></a> has many arguments, and it can take a while to learn the right incantation to read any given file.</p>
<p>Here's how you can do it with your file. The array <code>data</code> returned by <... | 0 | 2016-09-07T19:16:50Z | [
"python",
"list",
"csv",
"numpy",
"dictionary"
] |
Storing a service account with Flask-SQLAlchemy | 39,377,249 | <p>I'm writing a small HipChat plugin using Flask and Flask-SQLAlchemy with local database. I want the admin to be able to setup a service account for an external service this is meant to integrate with.</p>
<p>Because the username/password of the service accounts needs to be stored so they can be used by the integrat... | 2 | 2016-09-07T18:54:54Z | 39,377,369 | <p>You can encrypt your data before storing them in your database. <a href="https://www.dlitz.net/software/pycrypto/" rel="nofollow"><code>pycrypto</code></a> is one of the libraries that you can utilize.</p>
<blockquote>
<p>It is easy to encrypt text using DES/ECB with pycrypto. The key
â10234567â is 8 bytes ... | 0 | 2016-09-07T19:02:38Z | [
"python",
"security",
"password-encryption"
] |
Kivy layout not rendering as expected | 39,377,373 | <p>I am trying to create an interface with the KV lang provided by the Kivy framework. I want to stack two <strong>BoxLayout</strong> widgets on top of each other. When the first layout is rendered it is has a default height of 350. I need this to be reduced otherwise. </p>
<p>Below is my layout</p>
<pre><code><Ro... | 0 | 2016-09-07T19:02:59Z | 39,380,161 | <p>You could do. Try using size_hint cause it makes your app responsive, looking alike in all screen resolutions. </p>
<pre><code> BoxLayout:
orientation: 'vertical'
BoxLayout:
id: 'letterBox'
size_hint: 1, .15
BoxLayout:
id: 'contentBox'
size_hin... | 1 | 2016-09-07T22:53:02Z | [
"python",
"kivy"
] |
Nested SQL queries too slow | 39,377,422 | <p>I have following code, where I execute another query within the loop of result set from first query
Table1 has 35K records, while table2 has 4M</p>
<pre><code>db = MySQLdb.connect("localhost","root","root","test" )
cursor1 = db.cursor(MySQLdb.cursors.DictCursor)
cursor2 = db.cursor(MySQLdb.cursors.DictCursor)
sql... | 3 | 2016-09-07T19:07:34Z | 39,377,548 | <p>Nesting queries within a web application is never a good idea. As you've found, it kills performance.</p>
<p>Try using a single query which joins table1 and table2. Then, programmatically keep track of when your parent data changes to handle line breaks or display changes.</p>
| -1 | 2016-09-07T19:17:55Z | [
"python",
"mysql"
] |
Nested SQL queries too slow | 39,377,422 | <p>I have following code, where I execute another query within the loop of result set from first query
Table1 has 35K records, while table2 has 4M</p>
<pre><code>db = MySQLdb.connect("localhost","root","root","test" )
cursor1 = db.cursor(MySQLdb.cursors.DictCursor)
cursor2 = db.cursor(MySQLdb.cursors.DictCursor)
sql... | 3 | 2016-09-07T19:07:34Z | 39,377,864 | <p>1)Use left join for table1 to get desired results from table2</p>
<p>2)Fetch results and do something you want.</p>
<p>3)* if you don't have indices, add them(just in case) </p>
<p>Some advice: SQL is created on union theory. However, Cursor is set up for looping. So if you use for loop too many times. It will ca... | -1 | 2016-09-07T19:40:59Z | [
"python",
"mysql"
] |
Quadratic formula solver in python | 39,377,432 | <p>I'm somewhat new to python, but I'm trying my best to learn. My code is</p>
<pre><code>import math
a = 5
b = 5
c = 5
def quad_solve(a, b, c):
q1 = b*b
q2 = 4*a*c
q3 = 2*a
q4 = q1-q2
sqr = math.sqrt(q4)
sol1p1 = b+sqr
sol1p2 = sol1p1/2
sol2p1 = b-sqr
sol2p2 = sol2p1/2
print ... | 3 | 2016-09-07T19:08:53Z | 39,377,472 | <p>b^2 has to be greater than 4ac, So right now, that <code>sqrt()</code> function is getting a negative number. </p>
| 1 | 2016-09-07T19:11:47Z | [
"python",
"math",
"compiler-errors"
] |
Quadratic formula solver in python | 39,377,432 | <p>I'm somewhat new to python, but I'm trying my best to learn. My code is</p>
<pre><code>import math
a = 5
b = 5
c = 5
def quad_solve(a, b, c):
q1 = b*b
q2 = 4*a*c
q3 = 2*a
q4 = q1-q2
sqr = math.sqrt(q4)
sol1p1 = b+sqr
sol1p2 = sol1p1/2
sol2p1 = b-sqr
sol2p2 = sol2p1/2
print ... | 3 | 2016-09-07T19:08:53Z | 39,377,516 | <p>This is my version of the answer in the fewest lines of code:</p>
<pre><code>import cmath
#Your Variables
a = 5
b = 5
c = 5
#The Discriminant
d = (b**2) - (4*a*c)
#The Solutions
solution1 = (-b-cmath.sqrt(d))/(2*a)
solution2 = (-b+cmath.sqrt(d))/(2*a)
print (solution1)
print (solution2)
</code></pre>
| 3 | 2016-09-07T19:14:39Z | [
"python",
"math",
"compiler-errors"
] |
Quadratic formula solver in python | 39,377,432 | <p>I'm somewhat new to python, but I'm trying my best to learn. My code is</p>
<pre><code>import math
a = 5
b = 5
c = 5
def quad_solve(a, b, c):
q1 = b*b
q2 = 4*a*c
q3 = 2*a
q4 = q1-q2
sqr = math.sqrt(q4)
sol1p1 = b+sqr
sol1p2 = sol1p1/2
sol2p1 = b-sqr
sol2p2 = sol2p1/2
print ... | 3 | 2016-09-07T19:08:53Z | 39,377,991 | <p>If you're just interested in getting a result (and not in learning how to do this), you can use <a href="http://sympy.org" rel="nofollow">sympy</a>:</p>
<pre><code>from sympy import var, solve
x = var("x")
print(solve(5*x**2 + 5*x + 5))
# prints [-1/2 - sqrt(3)*I/2, -1/2 + sqrt(3)*I/2]
</code></pre>
| 1 | 2016-09-07T19:50:05Z | [
"python",
"math",
"compiler-errors"
] |
Quadratic formula solver in python | 39,377,432 | <p>I'm somewhat new to python, but I'm trying my best to learn. My code is</p>
<pre><code>import math
a = 5
b = 5
c = 5
def quad_solve(a, b, c):
q1 = b*b
q2 = 4*a*c
q3 = 2*a
q4 = q1-q2
sqr = math.sqrt(q4)
sol1p1 = b+sqr
sol1p2 = sol1p1/2
sol2p1 = b-sqr
sol2p2 = sol2p1/2
print ... | 3 | 2016-09-07T19:08:53Z | 39,378,435 | <p>There are two ways to do this (I figured this out thanks to the great hints given by Code-Apprentice, Pablo Iocco, and Tom Pitts).</p>
<pre><code>import cmath
import math
a = 1
b = 3
c = 2
def quad_solve_exact(a, b, c):
d = (b*b)-(4*a*c)
solution1 = (-b-cmath.sqrt(d))/(2*a)
solution2 = (-b+cmath.sqrt(... | 0 | 2016-09-07T20:25:38Z | [
"python",
"math",
"compiler-errors"
] |
args python parser, a whitespace and Spark | 39,377,451 | <p>I have this code in <code>foo.py</code>:</p>
<pre><code>from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--label', dest='label', type=str, default=None, required=True, help='label')
args = parser.parse_args()
</code></pre>
<p>and when I execute:</p>
<blockquote>
<p>spark-submit... | 2 | 2016-09-07T19:10:06Z | 39,379,156 | <p>Here is a nasty workaround:</p>
<pre><code>from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('--label', dest='label', type=str, default=None, required=True, help='label', nargs="+")
args = parser.parse_args()
args = ' '.join(args.label)
print args
</code></pre>
<p>where I am using <... | 0 | 2016-09-07T21:19:09Z | [
"python",
"linux",
"apache-spark",
"io",
"redhat"
] |
Smart Sheet Row calls not getting information or working | 39,377,478 | <p>I'm trying to use the row attribute created_by accessing it with the Python SDK and it keeps throwing an error. I'm not sure if I'm missing something.</p>
<p>Every time I try to use it I get the error:</p>
<pre><code> File "C:\Python27\lib\site-packages\smartsheet\models\row.py", line 166, in __getattr__ raise A... | 2 | 2016-09-07T19:12:14Z | 39,395,884 | <p>Via the API, if you want the <strong>Get Sheet</strong> response to include the <strong>createdBy</strong> attribute for each Row, you must specify the <strong>include</strong> parameter on the request with a value that includes the string <strong>rowWriterInfo</strong>. (See the <a href="http://smartsheet-platform.... | 0 | 2016-09-08T16:18:01Z | [
"python",
"smartsheet-api"
] |
How to change the font size of a QInputDialog in PyQt? | 39,377,515 | <p><strong>The case of a simple message box</strong></p>
<p>I have figured out how to change the font size in simple PyQt dialog windows. Take this example:</p>
<pre><code> # Create a custom font
# ---------------------
font = QFont()
font.setFamily("Arial")
font.setPointSize(10)
# Show simple... | 1 | 2016-09-07T19:14:30Z | 39,387,037 | <p>Thanks to the comments of @denvaar and @ekhumoro, I got the solution. Here it is:</p>
<pre><code> # Create a custom font
# ---------------------
font = QFont()
font.setFamily("Arial")
font.setPointSize(10)
# Create and show the input dialog
# ---------------------------------
inputDi... | 1 | 2016-09-08T09:16:58Z | [
"python",
"python-3.x",
"pyqt",
"pyqt5"
] |
Data from 2 pages as one item | 39,377,671 | <p>I am crawling a site with products the currency that product's price is shown is it set via the url <code>/en-GB/</code> for GBP and <code>/en-AU/</code> for AUD my client wants both prices in one item.</p>
<p>I would like to be able to use pipelines to put it into their DB so combining it afterwards is not viable.... | 2 | 2016-09-07T19:27:12Z | 39,379,944 | <p><a href="http://doc.scrapy.org/en/latest/topics/request-response.html#passing-additional-data-to-callback-functions" rel="nofollow">http://doc.scrapy.org/en/latest/topics/request-response.html#passing-additional-data-to-callback-functions</a></p>
<pre><code>def parse_page1(self, response):
item = MyItem()
i... | 2 | 2016-09-07T22:29:13Z | [
"python",
"python-2.7",
"scrapy"
] |
Retrieving result from celery worker constantly | 39,377,751 | <p>I have an web app in which I am trying to use celery to load background tasks from a database. I am currently loading the database upon request, but would like to load the tasks on an hourly interval and have them work in the background. I am using flask and am coding in python.I have redis running as well. </p>
<p... | 8 | 2016-09-07T19:33:28Z | 39,430,468 | <p>The Celery <a href="http://docs.celeryproject.org/en/latest/userguide/tasks.html#tasks">Task</a> is being executed by a Worker, and it's Result is being stored in the <a href="http://docs.celeryproject.org/en/latest/getting-started/first-steps-with-celery.html#keeping-results">Celery Backend</a>.</p>
<p>If I get yo... | 7 | 2016-09-10T20:50:47Z | [
"python",
"database",
"celery"
] |
How to recode line so an exact sentence must be in the list for it to match | 39,377,790 | <pre><code>x = ["Cookie flavored water is yummy 6", "Coding complicated 16", "Help 7"]
for i in x:
if "flavored" in x:
print ("Yes")
else:
print ("No")
</code></pre>
<p>I want the exact string "Cookie flavored water is yummy" to be in the list for it to be acceptable but I don't want the 6 par... | -1 | 2016-09-07T19:36:38Z | 39,377,889 | <p>Well if the string is always the one you specified you could do this:</p>
<pre><code>yourString = "Cookie flavored water is yummy"
for item in x:
if yourString in item:
print 'Yes'
else:
print 'No'
</code></pre>
<p>This check each list item for the specified string. In your example "Cookie ... | 0 | 2016-09-07T19:42:25Z | [
"python",
"list"
] |
How to recode line so an exact sentence must be in the list for it to match | 39,377,790 | <pre><code>x = ["Cookie flavored water is yummy 6", "Coding complicated 16", "Help 7"]
for i in x:
if "flavored" in x:
print ("Yes")
else:
print ("No")
</code></pre>
<p>I want the exact string "Cookie flavored water is yummy" to be in the list for it to be acceptable but I don't want the 6 par... | -1 | 2016-09-07T19:36:38Z | 39,377,897 | <p>you're iterating on <code>x</code> with <code>i</code> but you check if string belongs to the list, not the element, which is always false.</p>
<p>to check if an element of x contains <code>"Cookie flavored water is yummy"</code></p>
<pre><code>x = ["Cookie flavored water is yummy 6", "Coding complicated 16", "Hel... | 0 | 2016-09-07T19:43:27Z | [
"python",
"list"
] |
How to recode line so an exact sentence must be in the list for it to match | 39,377,790 | <pre><code>x = ["Cookie flavored water is yummy 6", "Coding complicated 16", "Help 7"]
for i in x:
if "flavored" in x:
print ("Yes")
else:
print ("No")
</code></pre>
<p>I want the exact string "Cookie flavored water is yummy" to be in the list for it to be acceptable but I don't want the 6 par... | -1 | 2016-09-07T19:36:38Z | 39,377,992 | <p>What do you mean by "acceptable?" Additionally, when you say you don't want the number at the end of the items in the list to be included, do you mean for your comparison? I agree with the other answers, and if you happen to want to remove the numbers from the list:</p>
<pre><code>x = [' '.join(i.split(' ')[:-1]) f... | 0 | 2016-09-07T19:50:05Z | [
"python",
"list"
] |
How to use multiple core with a webservice based on Python Klein | 39,377,856 | <p>I am writing a web service based on Klein framework</p>
<p><a href="https://klein.readthedocs.io/en/latest/index.html" rel="nofollow">https://klein.readthedocs.io/en/latest/index.html</a></p>
<p>At this stage I am stress testing my service, it can handles about 70 requests per second on amazon t2.medium instance. ... | 2 | 2016-09-07T19:40:36Z | 39,391,548 | <p>It's certainly possible to use <code>multiprocessing</code> and it sure as heck is easy to spin up processes.</p>
<pre><code>from multiprocessing import Process
from klein import Klein
def runserver(interface, port, logFile):
app = Klein()
@app.route('/')
def heyEarth(request):
return 'Hey Eart... | 1 | 2016-09-08T12:55:10Z | [
"python",
"multithreading",
"web-services",
"twisted",
"klein-mvc"
] |
How to pass a list of objects to a thread function | 39,377,862 | <p>I have to pass a list of objects to a function that executes in a thread in python. I need to be able to call functions of those objects, such as <code>animal.bite()</code>. I created a generic test class:</p>
<pre><code>class test_class:
def f(self):
print 'hello'
</code></pre>
<p>and created a li... | 2 | 2016-09-07T19:40:49Z | 39,378,176 | <p>Two changes had to be made for this to work (thanks to Scott Mermelstein):</p>
<p>In the main loop, <code>threadScheduler(strlist)</code> had to be changed to <code>threadScheduler(*strlist)</code>. I verified this by adding the following line to the <code>threadScheduler()</code> function:</p>
<pre><code>print 'i... | 1 | 2016-09-07T20:05:35Z | [
"python",
"multithreading"
] |
Does numpy internally store size of an array? | 39,377,866 | <p>From specification of a numpy array at <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/c-api.types-and-structures.html#c.PyArrayObject" rel="nofollow">here</a>:</p>
<pre><code>typedef struct PyArrayObject {
PyObject_HEAD
char *data;
int nd;
npy_intp *dimensions;
npy_intp *strides;
... | 3 | 2016-09-07T19:41:13Z | 39,377,943 | <p>Look at <code>PyArray_ArrayDescr *PyArray_Descr.subarray</code>:</p>
<blockquote>
<p>If this is non- NULL, then this data-type descriptor is a C-style
contiguous array of another data-type descriptor. In other-words, each
element that this descriptor describes is actually an array of some
other base descrip... | 2 | 2016-09-07T19:46:37Z | [
"python",
"c",
"numpy"
] |
Does numpy internally store size of an array? | 39,377,866 | <p>From specification of a numpy array at <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/c-api.types-and-structures.html#c.PyArrayObject" rel="nofollow">here</a>:</p>
<pre><code>typedef struct PyArrayObject {
PyObject_HEAD
char *data;
int nd;
npy_intp *dimensions;
npy_intp *strides;
... | 3 | 2016-09-07T19:41:13Z | 39,378,201 | <p>The size (that is, the total number of elements in the array) is computed as the product of the values in the array <code>dimensions</code>. The length of that array is <code>nd</code>.</p>
<p>In the C code that implements the core of numpy, you'll find many uses of the macro <code>PyArray_SIZE(obj)</code>. Here'... | 5 | 2016-09-07T20:07:44Z | [
"python",
"c",
"numpy"
] |
OSError when trying to pip install shapely inside docker container | 39,377,911 | <p>Could not find library geos_c or load any of its variants ['libgeos_c.so.1', 'libgeos_c.so']</p>
<p>using the python:3.5.1 image I am trying to run a container that includes among other things it installs in requirements.txt shapely. When the docker container tries to install shapely I get the above error.</p>
<p>... | 2 | 2016-09-07T19:44:41Z | 39,399,690 | <p>I found a solution from: <a href="https://github.com/calendar42/docker-python-geos/blob/master/Dockerfile" rel="nofollow">https://github.com/calendar42/docker-python-geos/blob/master/Dockerfile</a></p>
<pre><code>ENV PYTHONUNBUFFERED 1
#### Install GEOS ####
# Inspired by: https://hub.docker.com/r/cactusbone/postg... | 1 | 2016-09-08T20:30:36Z | [
"python",
"docker-compose",
"shapely",
"geos"
] |
Combine every two lines while reading .txt file in python | 39,377,936 | <p>I'm currently working with very large files in Python that look like</p>
<pre><code>junk
junk
junk
--- intermediate:
1489 pi0 111 [686] (1491,1492)
0.534 -0.050 -0.468 0.724 0.135
1499 pi0 111 [690] (1501,1502)
-1.131 ... | 2 | 2016-09-07T19:46:25Z | 39,378,360 | <p>A quick and dirty way of merging every other line:</p>
<pre><code>for i in range(0,len(lines),2):
fields1 = lines[i].strip().split()
fields2 = lines[i+1].strip().split()
print("\t".join(fields1[:4]+fields2))
</code></pre>
<p>Note that I considered here that all the lines to be merged are extracted and... | 0 | 2016-09-07T20:19:40Z | [
"python"
] |
Combine every two lines while reading .txt file in python | 39,377,936 | <p>I'm currently working with very large files in Python that look like</p>
<pre><code>junk
junk
junk
--- intermediate:
1489 pi0 111 [686] (1491,1492)
0.534 -0.050 -0.468 0.724 0.135
1499 pi0 111 [690] (1501,1502)
-1.131 ... | 2 | 2016-09-07T19:46:25Z | 39,378,417 | <p>as long as you know the exact lines that surround the section you want:</p>
<pre><code>#split the large text into lines
lines = large_text.split('\n')
#get the indexes of the beginning and end of your target section
idx_start = lines.index("--- final:")
idx_finish= lines.index("-------------------------------------... | 0 | 2016-09-07T20:24:22Z | [
"python"
] |
Combine every two lines while reading .txt file in python | 39,377,936 | <p>I'm currently working with very large files in Python that look like</p>
<pre><code>junk
junk
junk
--- intermediate:
1489 pi0 111 [686] (1491,1492)
0.534 -0.050 -0.468 0.724 0.135
1499 pi0 111 [690] (1501,1502)
-1.131 ... | 2 | 2016-09-07T19:46:25Z | 39,378,595 | <p>You could solve your problem with the newer <a href="https://pypi.python.org/pypi/regex" rel="nofollow"><strong><code>regex</code></strong></a> module and some regular expressions:</p>
<pre><code>import regex as re
rx = re.compile(r'''(?V1)
(?:^---\ final:[\n\r])|(?:\G(?!\A))
^(\ *\d+.+?)\ *$[\n\r]... | 0 | 2016-09-07T20:37:21Z | [
"python"
] |
Responding to new_session_created messages in the telegram.org API | 39,377,938 | <p>In my telegram client I go through the seemingly typical process of creating a valid session:</p>
<ol>
<li>Generate a random session_id</li>
<li>Create an auth key</li>
<li>Call <code>initConnection</code> with <code>getNearestDc</code></li>
<li>Switch to the nearest DC, which involves a new random session_id and
a... | 2 | 2016-09-07T19:46:27Z | 39,378,210 | <p>Save and re-use this new salt you just received for your next requests in this session.</p>
<p>To do a subsequest login all you need is the <code>session_id</code>, <code>recent_salt</code> and the <code>auth_key</code>.</p>
<p><code>Auth_key_id</code> is computed from the <code>auth_key</code> so you may, or may ... | 1 | 2016-09-07T20:08:55Z | [
"python",
"telegram"
] |
Why does Python's set difference method take time with an empty set? | 39,378,043 | <p>Here is what I mean:</p>
<pre><code>> python -m timeit "set().difference(xrange(0,10))"
1000000 loops, best of 3: 0.624 usec per loop
> python -m timeit "set().difference(xrange(0,10**4))"
10000 loops, best of 3: 170 usec per loop
</code></pre>
<p>Apparently python iterates through the whole argument, ev... | 12 | 2016-09-07T19:55:12Z | 39,397,175 | <p>IMO it's a matter of specialisation, consider:</p>
<pre><code>In [18]: r = range(10 ** 4)
In [19]: s = set(range(10 ** 4))
In [20]: %time set().difference(r)
CPU times: user 387 µs, sys: 0 ns, total: 387 µs
Wall time: 394 µs
Out[20]: set()
In [21]: %time set().difference(s)
CPU times: user 10 µs, sys: 8 µs,... | 4 | 2016-09-08T17:42:54Z | [
"python",
"performance",
"set",
"operators"
] |
Why does Python's set difference method take time with an empty set? | 39,378,043 | <p>Here is what I mean:</p>
<pre><code>> python -m timeit "set().difference(xrange(0,10))"
1000000 loops, best of 3: 0.624 usec per loop
> python -m timeit "set().difference(xrange(0,10**4))"
10000 loops, best of 3: 170 usec per loop
</code></pre>
<p>Apparently python iterates through the whole argument, ev... | 12 | 2016-09-07T19:55:12Z | 39,431,151 | <p>When Python core developers add new features, the first priority is correct code with thorough test coverage. That is hard enough in itself. Speedups often come later as someone has the idea and inclination. I opened a tracker issue <a href="https://bugs.python.org/issue28071" rel="nofollow">28071</a> summarizing... | 2 | 2016-09-10T22:29:47Z | [
"python",
"performance",
"set",
"operators"
] |
Why does Python's set difference method take time with an empty set? | 39,378,043 | <p>Here is what I mean:</p>
<pre><code>> python -m timeit "set().difference(xrange(0,10))"
1000000 loops, best of 3: 0.624 usec per loop
> python -m timeit "set().difference(xrange(0,10**4))"
10000 loops, best of 3: 170 usec per loop
</code></pre>
<p>Apparently python iterates through the whole argument, ev... | 12 | 2016-09-07T19:55:12Z | 39,441,283 | <blockquote>
<p>Is there any good reason for this? </p>
</blockquote>
<p>Having a special path for the empty set had not come up before.</p>
<blockquote>
<p>Even for nonempty sets, if you find that you've removed all of the first set's elements midway through the iteration, it makes sense to stop right away.</p>
... | 4 | 2016-09-11T22:32:19Z | [
"python",
"performance",
"set",
"operators"
] |
Django error: NoReverseMatch | 39,378,074 | <p>I'm using Django 1.10 and python 3.4</p>
<p>The precise error is</p>
<pre><code>NoReverseMatch at /movies/movie/Twilight/
Reverse for 'movie-details' with arguments '(8,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['movies/movie/(?P<movie_id>\\d+)|(?P<movie_name>[a-zA-Z\\ ]+)/$']
</code... | 3 | 2016-09-07T19:57:57Z | 39,378,334 | <p>Django's <code>reverse()</code> cannot handle disjunctive patterns (using a <code>|</code>) outside of a capturing group. It's one of those things you'd hope someone would've fixed somewhere in the past 10 or so years, but this limitation has been around <a href="https://github.com/django/django/blob/978a00e39fee25c... | 1 | 2016-09-07T20:17:56Z | [
"python",
"django"
] |
Django error: NoReverseMatch | 39,378,074 | <p>I'm using Django 1.10 and python 3.4</p>
<p>The precise error is</p>
<pre><code>NoReverseMatch at /movies/movie/Twilight/
Reverse for 'movie-details' with arguments '(8,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['movies/movie/(?P<movie_id>\\d+)|(?P<movie_name>[a-zA-Z\\ ]+)/$']
</code... | 3 | 2016-09-07T19:57:57Z | 39,378,358 | <p>You are only sending one parameter to your view, though it expects two. If you want to stick with one that can be interpreted as an id or a name, why not accept an alpha-numeric parameter </p>
<pre><code>urlpatterns = [
url(r'^movie/(?P<movie_id>[A-z0-9]+)/$', view_movie, name = 'movie-details'),
]
</code></p... | 0 | 2016-09-07T20:19:21Z | [
"python",
"django"
] |
Django error: NoReverseMatch | 39,378,074 | <p>I'm using Django 1.10 and python 3.4</p>
<p>The precise error is</p>
<pre><code>NoReverseMatch at /movies/movie/Twilight/
Reverse for 'movie-details' with arguments '(8,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['movies/movie/(?P<movie_id>\\d+)|(?P<movie_name>[a-zA-Z\\ ]+)/$']
</code... | 3 | 2016-09-07T19:57:57Z | 39,378,517 | <p>You can add parentheses around capturing groups:</p>
<pre><code>urlpatterns = [
url(r'^movie/((?P<movie_id>\d+)|(?P<movie_name>[a-zA-Z\ ]+))/$', view_movie, name = 'movie-details'),
]
</code></pre>
<p>and add defaults to view parameters:</p>
<pre><code>def view_movie(request, movie_id=None, movie_... | 0 | 2016-09-07T20:31:43Z | [
"python",
"django"
] |
Parsing XML from websites and save the code? | 39,378,160 | <p>I would like to parse the xml code from a website like
<a href="http://ops.epo.org/3.1/rest-services/published-data/publication/docdb/EP1000000/biblio" rel="nofollow">http://ops.epo.org/3.1/rest-services/published-data/publication/docdb/EP1000000/biblio</a>
and save it in another xml or csv file.</p>
<p>I tried it... | 1 | 2016-09-07T20:03:54Z | 39,378,426 | <p><code>read()</code> returns data as <code>bytes</code> but you can save data without converting to <code>str()</code>. You have to open file in <code>byte</code> mode - <code>"wb"</code> - and write data.</p>
<pre><code>import urllib.request
web_data = urllib.request.urlopen("http://ops.epo.org/3.1/rest-services/p... | 0 | 2016-09-07T20:24:37Z | [
"python",
"xml",
"python-3.5"
] |
Parsing XML from websites and save the code? | 39,378,160 | <p>I would like to parse the xml code from a website like
<a href="http://ops.epo.org/3.1/rest-services/published-data/publication/docdb/EP1000000/biblio" rel="nofollow">http://ops.epo.org/3.1/rest-services/published-data/publication/docdb/EP1000000/biblio</a>
and save it in another xml or csv file.</p>
<p>I tried it... | 1 | 2016-09-07T20:03:54Z | 39,378,491 | <p>If you write the xml file in binary mode, you don't need to convert the data read into a string of characters first. Also, if you process the data a line at a time, that should get rid of <code>'\n'</code> problem. The logic of your code could also be structured a little better IMO, as shown below:</p>
<pre><code>i... | 1 | 2016-09-07T20:30:05Z | [
"python",
"xml",
"python-3.5"
] |
Absolute path error when building wheel | 39,378,247 | <p><strong>OVERVIEW</strong></p>
<p>I'm trying to learn how to build wheels on my windows dev box so hopefully I'll have a nice way to deploy django websites on linux boxes. But right now I'm stuck with a little error.</p>
<p>Here's my setup.py:</p>
<pre><code>from setuptools import setup, find_packages
setup(name=... | 1 | 2016-09-07T20:11:27Z | 39,417,056 | <p>Wheels should be used for bundling Python code. It's not for configuration management (where Nginx configurations would typically be handled).</p>
<p>See also: <a href="http://stackoverflow.com/a/34204582/116042">http://stackoverflow.com/a/34204582/116042</a></p>
| 1 | 2016-09-09T17:42:56Z | [
"python",
"django",
"python-wheel"
] |
How to convert "12:45pm - 01:00pm Today, September 7" into UTC | 39,378,313 | <p>I have the following time string </p>
<pre><code>12:45pm - 01:00pm Today, September 7
</code></pre>
<p>and I want to convert this string into UTC datetime in the following format</p>
<pre><code>2016-09-07T22:45:00Z
</code></pre>
<p>How can I achieve this in python?</p>
| -1 | 2016-09-07T20:16:28Z | 39,398,238 | <pre><code>developed the script to achieve it.
def appointment_time_string(time_str):
import datetime
a = time_str.split()[0]
in_time = datetime.datetime.strptime(a,'%I:%M%p')
start_time = str(datetime.datetime.strftime(in_time, "%H:%M:%S")) + "Z"
if time_str.split()[3] =... | 0 | 2016-09-08T18:52:15Z | [
"python"
] |
Convert columns from a data frame to a list of dicts efficiently | 39,378,331 | <p>I am converting columns of data frame to to a list of dictionaries, however, due to the number of columns and number of observations in my data frame I run out of memory using my current approach:</p>
<pre><code>df = pd.DataFrame(np.random.randn(10, 3), columns=['a', 'b', 'c'])
df.T.to_dict().values()
</code></pre>... | 2 | 2016-09-07T20:17:44Z | 39,378,372 | <p>is that what you want?</p>
<pre><code>In [9]: df.to_dict('r')
Out[9]:
[{'a': 1.3720225964856179,
'b': -1.1530341240730422,
'c': -0.18791193632296455},
{'a': 1.3283240103713496, 'b': 3.6614598433626959, 'c': -0.46395170547460196},
{'a': -1.4960282310010959,
'b': 0.25156344524211743,
'c': -1.366431138584928... | 2 | 2016-09-07T20:20:49Z | [
"python",
"pandas",
"dictionary",
"dataframe"
] |
Remove nan rows in a scipy sparse matrix | 39,378,363 | <p>I am given a (normalized) sparse adjacency matrix and a list of labels for the respective matrix rows. Because some nodes have been removed by another sanitization function, there are some rows containing NaNs in the matrix. I want to find these rows and remove them <em>as well as their respective labels</em>. Here ... | 1 | 2016-09-07T20:20:04Z | 39,379,774 | <p>If I make a sample array:</p>
<pre><code>In [328]: A=np.array([[1,0,0,np.nan],[0,np.nan,np.nan,0],[1,0,1,0]])
In [329]: A
Out[329]:
array([[ 1., 0., 0., nan],
[ 0., nan, nan, 0.],
[ 1., 0., 1., 0.]])
In [331]: M=sparse.lil_matrix(A)
</code></pre>
<p>This lil sparse matrix is store... | 0 | 2016-09-07T22:11:18Z | [
"python",
"numpy",
"scipy",
"sparse-matrix",
"networkx"
] |
Maintaining Dictionary Integrity While Running it Through Multithread Process | 39,378,382 | <p>I sped up a process by using a multithread function, however I need to maintain a relationship between the output and input. </p>
<pre><code>import requests
import pprint
import threading
ticker = ['aapl', 'googl', 'nvda']
url_array = []
for i in ticker:
url = 'https://query2.finance.yahoo.com/v10/finance/quo... | 2 | 2016-09-07T20:21:21Z | 39,380,627 | <p>To make it easy to maintain the correspondence between input and output, the <code>ev_array</code> can be preallocated so it's the same size as the <code>ticker</code> array, and the <code>fetch_ev()</code> thread function can be given an extra argument specifying the index of the location in that array to store the... | 1 | 2016-09-07T23:55:42Z | [
"python",
"multithreading",
"dictionary"
] |
Iterating across multiple columns in Pandas DF and slicing dynamically | 39,378,510 | <p><strong>TLDR:</strong> How to iterate across all options of multiple columns in a pandas dataframe without specifying the columns or their values explicitly?</p>
<p><strong>Long Version:</strong> I have a pandas dataframe that looks like this, only it has a lot more features or drug dose combinations than are liste... | 1 | 2016-09-07T20:31:18Z | 39,379,186 | <p>What about using the underlying numpy array and some boolean logic to build an array containing only the lines you want ?</p>
<pre><code>dosage_df = pd.DataFrame((np.random.rand(40000,10)*100).astype(np.int))
dict_of_dose_ranges={3:[10,11,12,13,15,20],4:[20,22,23,24]}
#combined_doses will be bool array that will s... | 0 | 2016-09-07T21:21:26Z | [
"python",
"pandas",
"machine-learning",
"scikit-learn",
"grid-search"
] |
Iterating across multiple columns in Pandas DF and slicing dynamically | 39,378,510 | <p><strong>TLDR:</strong> How to iterate across all options of multiple columns in a pandas dataframe without specifying the columns or their values explicitly?</p>
<p><strong>Long Version:</strong> I have a pandas dataframe that looks like this, only it has a lot more features or drug dose combinations than are liste... | 1 | 2016-09-07T20:31:18Z | 39,380,574 | <p>You can use <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product</code></a> to generate all possible dosage combinations, and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.query.html" rel="nofollow"><code>DataFrame.query... | 2 | 2016-09-07T23:47:49Z | [
"python",
"pandas",
"machine-learning",
"scikit-learn",
"grid-search"
] |
Sudo pip install upgrade operation not permitted | 39,378,523 | <p>I am trying to upgrade Numpy on Python 2.7 on Mac El Capitan, but I keep getting errors. I have Numpy v1.8.0rc1 and I need the latest one.</p>
<p><code>sudo pip2 install --upgrade numpy</code></p>
<p><code>...</code></p>
<p><code>OSError: [Errno 1] Operation not permitted: '/tmp/pip-HUSiK5-uninstall/System/Librar... | 2 | 2016-09-07T20:31:50Z | 39,378,584 | <p>You're likely running into System Integrity Protection, the system introduced by Apple to prevent modification of system files (see <a href="https://apple.stackexchange.com/questions/209572/how-to-use-pip-after-the-os-x-el-capitan-upgrade">this answer on Ask Different</a>). Your options are approximately:</p>
<ul>
... | 0 | 2016-09-07T20:36:24Z | [
"python",
"numpy",
"pip",
"upgrade"
] |
Changing data in a DataFrame column (Pandas) with a For loop | 39,378,535 | <p>I'm trying to take the data from "Mathscore" and convert the values into numerical values, all under "Mathscore."</p>
<p>strong =1
Weak = 0</p>
<p>I tried doing this via the function below using For loop but I can't get the code to run. Is the way I'm trying to assign data incorrect?</p>
<p>Thanks! </p>
<pre><c... | 4 | 2016-09-07T20:32:22Z | 39,378,624 | <p>you can <a href="http://pandas.pydata.org/pandas-docs/stable/categorical.html" rel="nofollow">categorize</a> your data:</p>
<pre><code>In [23]: df['Mathscore'] = df.Mathscore.astype('category').cat.rename_categories(['1','0'])
In [24]: df
Out[24]:
Id_Student Mathscore
0 1 1
1 2 ... | 3 | 2016-09-07T20:38:52Z | [
"python",
"pandas",
"dataframe"
] |
Changing data in a DataFrame column (Pandas) with a For loop | 39,378,535 | <p>I'm trying to take the data from "Mathscore" and convert the values into numerical values, all under "Mathscore."</p>
<p>strong =1
Weak = 0</p>
<p>I tried doing this via the function below using For loop but I can't get the code to run. Is the way I'm trying to assign data incorrect?</p>
<p>Thanks! </p>
<pre><c... | 4 | 2016-09-07T20:32:22Z | 39,379,032 | <p>You could use:</p>
<pre><code>df['Mathscore'] = df['Mathscore'].str.replace('Strong','1')
df['Mathscore'] = df['Mathscore'].str.replace('Weak','0')
</code></pre>
<p>Returns:</p>
<pre><code>In [1]: df
Out[1]:
Id_Student Mathscore
0 1 1
1 2 0
2 3 0
3 ... | 1 | 2016-09-07T21:07:57Z | [
"python",
"pandas",
"dataframe"
] |
Python - expanding the range between dot dot (id1..id2) | 39,378,551 | <p>Suppose i have a list of ids like: </p>
<pre><code>ids= 1/1/n1..1/1/n5 , 1/1/x1 , 1/1/g1
</code></pre>
<p>Expected output: </p>
<pre><code>1/1/n1 , 1/1/n2 , 1/1/n3 , 1/1/n4 , 1/1/n5 ,1/1/x1, 1/1/g1
</code></pre>
<p>Means wherever i finds 'ids..ids', i will fill the gap </p>
<p>I have written a very basic code,... | 0 | 2016-09-07T20:33:43Z | 39,378,682 | <p>Here's the base code; I'll let you recombine it as desired, including list comprehensions that you already have. Just split the range as you're already doing. Instead of de-constructing the entire string, just take that last digit and run the range:</p>
<pre><code>ports_list=['1/1/n1..1/1/n8']
for port in ports_... | 0 | 2016-09-07T20:43:02Z | [
"python",
"list",
"python-2.7"
] |
Python - expanding the range between dot dot (id1..id2) | 39,378,551 | <p>Suppose i have a list of ids like: </p>
<pre><code>ids= 1/1/n1..1/1/n5 , 1/1/x1 , 1/1/g1
</code></pre>
<p>Expected output: </p>
<pre><code>1/1/n1 , 1/1/n2 , 1/1/n3 , 1/1/n4 , 1/1/n5 ,1/1/x1, 1/1/g1
</code></pre>
<p>Means wherever i finds 'ids..ids', i will fill the gap </p>
<p>I have written a very basic code,... | 0 | 2016-09-07T20:33:43Z | 39,378,792 | <p>Not sure it is more readable or better than your current approach, but we can use regular expressions to extract the common part and the range borders from a string:</p>
<pre><code>import re
def expand(l):
result = []
pattern = re.compile(r"^(.*?)(\d+)$")
for item in l:
# determine if it is a ... | 2 | 2016-09-07T20:50:51Z | [
"python",
"list",
"python-2.7"
] |
remove specific rows in dataframe with pandas | 39,378,552 | <p>i need some help from all of you
I'm working with a data form from excel, so basically now i have something like this. </p>
<pre><code>csr id ac otc tm lease maint
1 456 b 0 0 0 0
1 543 a 0 1 1 0
1 435 e 0 0 0 0
2 123 w 1 1 1 1
2... | 1 | 2016-09-07T20:33:45Z | 39,378,702 | <p>try this:</p>
<pre><code>In [35]: df.eval('otc == 0 and tm == 0 and lease == 0 and maint == 0')
Out[35]:
0 True
1 False
2 True
3 False
4 True
5 True
6 False
7 True
dtype: bool
In [36]: df[~df.eval('otc == 0 and tm == 0 and lease == 0 and maint == 0')]
Out[36]:
csr id ac otc tm ... | 1 | 2016-09-07T20:44:36Z | [
"python",
"excel",
"pandas",
"dataframe",
"filter"
] |
remove specific rows in dataframe with pandas | 39,378,552 | <p>i need some help from all of you
I'm working with a data form from excel, so basically now i have something like this. </p>
<pre><code>csr id ac otc tm lease maint
1 456 b 0 0 0 0
1 543 a 0 1 1 0
1 435 e 0 0 0 0
2 123 w 1 1 1 1
2... | 1 | 2016-09-07T20:33:45Z | 39,378,716 | <p>You can also extract the four columns that you are interested and count how many zeros it has for each row and create logical vector for indexing:</p>
<pre><code>df[(df[['otc', 'tm', 'lease', 'maint']] == 0).sum(axis = 1) < 4]
# csr id ac otc tm lease maint
# 1 1 543 a 0 1 1 0
#... | 2 | 2016-09-07T20:45:31Z | [
"python",
"excel",
"pandas",
"dataframe",
"filter"
] |
Reference to an element in a list | 39,378,598 | <p>I am a little confused about how python deal with reference to an element in a list, considering these two examples:</p>
<p>First example:</p>
<pre><code>import random
a = [[1,2],[3,4],[5,6],[7,8]]
b = [0.1,0.2]
c = random.choice(a)
c[:] = b
print(a)
</code></pre>
<p>Second example:</p>
<pre><code>import random
... | 4 | 2016-09-07T20:37:28Z | 39,378,778 | <p>Let's start with the second case. You write</p>
<pre><code>c = random.choice(a)
</code></pre>
<p>so the name <code>c</code> gets bound to some element of a, then</p>
<pre><code>c = b
</code></pre>
<p>so the name <code>c</code> gets bound to some other object (the one to which the name <code>b</code> is referring... | 3 | 2016-09-07T20:50:12Z | [
"python",
"random"
] |
Translation of a phrase both ways | 39,378,636 | <p>I am having trouble with Tuccin to English.
I can get it to translate in from English to Tuccin only.
What I want is if word is English translate to Tuccin,
If word is Tuccin, translate to English full phrases.
And finally if any input words are not stored I want it
To print that same word in its own place so show t... | 0 | 2016-09-07T20:39:46Z | 39,378,819 | <p><a href="http://stackoverflow.com/questions/483666/python-reverse-invert-a-mapping">This</a> stack answer demonstrates how to quickly invert a simple dictionary. So, in your case, what you would do is:</p>
<pre><code>Eng = {t[0]: [e] for t, e in Tuc.items()}
</code></pre>
<p>and use this dictionary the same way yo... | -1 | 2016-09-07T20:53:10Z | [
"python",
"translation"
] |
Sum of Pairs: Codewars | 39,378,656 | <p>I recently solved a problem as stated below in Codewars(<strong>NOT</strong> asking for a solution, already solved it) and though it is not the optimized solution I came across a very interesting problem which I could not figure out an answer to.</p>
<p><strong>I have NO intention to give out the solution, but just... | 0 | 2016-09-07T20:41:08Z | 39,378,966 | <p><code>ints.index(i)</code> doesn't give you the index of the particular occurrence of <code>i</code> you're working with. If you want that, you want <code>enumerate</code>, not <code>index</code>.</p>
<p><code>ints.index(i)</code> means "go through <code>ints</code> and find the index of the <em>first</em> element ... | 0 | 2016-09-07T21:03:27Z | [
"python"
] |
Searching file for the same string twice and printing both seperately | 39,378,711 | <p>I am a beginner python programmer with a search question. I need to locate a string of DNA in a DNA file. The issue is that I do not know where the string appears in the file, it appears twice, and I need to know both locations. My current program can only find the first string and I am having difficulty having it c... | 0 | 2016-09-07T20:45:06Z | 39,379,049 | <p>How large is your file? If it is not prohibitively long, you could use the naive approach:</p>
<pre><code>file = open("filename.text", r)
genome = file.read()
file.close()
genome_length = len(genome)
pattern = "ATCT" #or whatever your pattern is
pattern_length = len(pattern)
pattern_locations = []
for i in range(g... | 0 | 2016-09-07T21:09:33Z | [
"python",
"python-2.7",
"bioinformatics"
] |
Searching file for the same string twice and printing both seperately | 39,378,711 | <p>I am a beginner python programmer with a search question. I need to locate a string of DNA in a DNA file. The issue is that I do not know where the string appears in the file, it appears twice, and I need to know both locations. My current program can only find the first string and I am having difficulty having it c... | 0 | 2016-09-07T20:45:06Z | 39,396,046 | <p>I read your problem as "I am trying to find the locations of a DNA subsequence." Does the following example represent what you are trying to achieve? Let me know if I am oversimplifying your question and I can revise.</p>
<pre><code>>>> import re
>>> dna = 'AGTCTCCCGGATTTGGATTTAA' #super short, bu... | 1 | 2016-09-08T16:26:47Z | [
"python",
"python-2.7",
"bioinformatics"
] |
Sending SMS from django app | 39,378,728 | <p>I came to the requirement to send SMS from my django app. Its a dashboard from multiple clients, and each client will have the ability to send programable SMS. </p>
<p>Is this achievable with django smsish? I have found some packages that aren't updated, and I sending email sms is not possible.</p>
<p>All answers ... | 1 | 2016-09-07T20:46:31Z | 39,379,920 | <p>Using Twilio is not mandatory, but I do recommend it. Twilio does the heavy lifting, your Django App just needs to make the proper API Requests to Twilio, which has great documentation on it. </p>
<p>Twilio has Webhooks as well which you can 'hook' to specific Django Views and process certain events. As for the 'pr... | 1 | 2016-09-07T22:26:22Z | [
"python",
"django",
"sms"
] |
Starting another script using a button in tkinter | 39,378,811 | <p>I am trying to run another script within a script using a button in tkinter </p>
<p>I have tried two methods one being</p>
<pre><code>import os
class SeaofBTCapp(tk.Tk):
#initilization
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.wm_title(self, "Ba... | -1 | 2016-09-07T20:52:35Z | 39,378,939 | <p>Your first method is not recommended for that. If you have another python script you should definitely import it.</p>
<p>About the second method:<br>
My guess is that the script <code>test2.py</code> is written without</p>
<pre><code>if __name__ == "__main__":
main()
</code></pre>
<p>And that's why it shoot y... | 0 | 2016-09-07T21:01:57Z | [
"python",
"python-3.x",
"user-interface",
"tkinter"
] |
Incomplete coordinate values for Google Vision OCR | 39,378,862 | <p>I have a script that is iterating through images of different forms. When parsing the Google Vision Text detection response, I use the XY coordinates in the 'boundingPoly' for each text item to specifically look for data in different parts of the form. </p>
<p>The problem I'm having is that some of the responses co... | 2 | 2016-09-07T20:55:59Z | 39,378,944 | <p><a href="https://cloud.google.com/vision/reference/rest/v1/images/annotate" rel="nofollow">From the docs</a>:</p>
<blockquote>
<p>boundingPoly</p>
<p>object(BoundingPoly)</p>
<p>The bounding polygon around the face. The coordinates of the bounding box are in the original image's scale, as returned in Im... | 1 | 2016-09-07T21:02:19Z | [
"python",
"ocr",
"google-cloud-vision"
] |
Plot 2D array with Pandas, Matplotlib, and Numpy | 39,378,902 | <p>As a result from simulations, I parsed the output using Pandas <code>groupby()</code>. I am having a bit of difficulty to plot the data the way I want. Here's the Pandas output file (suppressed for simplicity) that I'm trying to plot:</p>
<pre><code> Avg-del Min-del Max-del Avg-retx Min-retx ... | 0 | 2016-09-07T20:59:03Z | 39,381,333 | <p>Ok, there is a lot going on here. First, it is plotting 6 lines. When your code calls</p>
<pre><code>plt.plot(np.transpose(np.array(result)[0:3, 0:3]), label = 'p=0.3')
plt.plot(np.transpose(np.array(result)[3:6, 0:3]), label = 'p=0.5')
</code></pre>
<p>it is calling <code>plt.plot</code> on a 3x3 array of data.... | 0 | 2016-09-08T01:37:08Z | [
"python",
"pandas",
"numpy",
"multidimensional-array",
"matplotlib"
] |
How to verify that a package installed from a list of package names | 39,378,958 | <p>I'm writing a program that will install certain packages from a <code>whl</code> file, however I need a way to verify that the packages where installed:</p>
<pre><code>def verify_installs(self):
for pack in self.packages:
import pip
installed = pip.get_installed_distributions()
for nam... | -1 | 2016-09-07T21:02:54Z | 39,379,001 | <p>Say <code>pack_list</code> is a list of string names of modules:</p>
<pre><code>import importlib
def verify_packs(pack_list):
for pack in pack_list:
try:
importlib.import_module(pack)
except ImportError:
print("{} failed to install".format(pack))
</code></pre>
<p>Note t... | 0 | 2016-09-07T21:05:56Z | [
"python",
"python-2.7",
"loops",
"import"
] |
How to verify that a package installed from a list of package names | 39,378,958 | <p>I'm writing a program that will install certain packages from a <code>whl</code> file, however I need a way to verify that the packages where installed:</p>
<pre><code>def verify_installs(self):
for pack in self.packages:
import pip
installed = pip.get_installed_distributions()
for nam... | -1 | 2016-09-07T21:02:54Z | 39,379,233 | <p>I figured out a way to check the installed packages:</p>
<pre><code>def verify_installs(self):
for pack in self.packages:
import pip
items = pip.get_installed_distributions()
installed_packs = sorted(["{}".format(i.key) for i in items])
if pack not in installed_packs:
... | 0 | 2016-09-07T21:24:58Z | [
"python",
"python-2.7",
"loops",
"import"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.