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
Matlab range in Python
37,571,622
<p>I must translate some Matlab code into Python 3 and I often come across ranges of the form start:step:stop. When these arguments are all integers, I easily translate this command with np.arange(), but when some of the arguments are floats, especially the step parameter, I don't get the same output in Python. For exa...
3
2016-06-01T14:31:28Z
37,575,804
<p>Matlab docs for <code>linspace</code> say</p> <blockquote> <p>linspace is similar to the colon operator, ":", but gives direct control over the number of points and always includes the endpoints. "lin" in the name "linspace" refers to generating linearly spaced values as opposed to the sibling function logspace, ...
1
2016-06-01T18:03:08Z
[ "python", "matlab", "numpy", "range" ]
How to create 3d pcolormesh of array values?
37,571,682
<p>I have data that occurs in an arrays at <code>x(0:127)</code>, <code>y(0:127)</code>, and <code>z(0:98)</code>. For example, at the coordinates of <code>x=23</code>, <code>y=27</code>, and <code>z=76</code> the data value might be 826. How can I create a 3d <code>pcolorrmesh</code> of these values to look similar to...
0
2016-06-01T14:33:59Z
37,587,269
<p>I don't think you can use <code>pcolormesh</code> for 3D plots. However look <a href="http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html" rel="nofollow">here</a> for the official matplotlib tutorial on 3D plottting.</p>
0
2016-06-02T09:03:25Z
[ "python", "matplotlib" ]
How do I set color table ranges in a Paraview python script?
37,571,716
<p>I'm visualizing a time series of spatial data in Paraview, and I would like for my setup script to set the color tables for a given field based on the field's range over the full time series, rather than an individual snapshot. I've tried initializing the lookup table with values computed by the script, but to no av...
0
2016-06-01T14:35:31Z
37,705,462
<p>You should be able to do something like the following:</p> <pre><code># get color transfer function/color map for 'br' lut = GetColorTransferFunction('br') # get opacity transfer function/opacity map for 'br' opacityLut = GetOpacityTransferFunction('br') # Rescale transfer function lut.RescaleTransferFunction(-sc...
0
2016-06-08T14:32:17Z
[ "python", "paraview" ]
Using django-registration-redux, but nothing happen
37,571,782
<p><code>tangowithdjango</code> chapter12, the author teach me to use <code>django-registration-redux</code> to achieve login and registration function. But i found it just don't work. It means that, i could not use this to login and register. And i just follow the steps the author told me.</p> <p>here's my <strong>u...
0
2016-06-01T14:37:57Z
37,586,045
<p>Your template is too complicated. Start with the <a href="http://www.tangowithdjango.com/book17/chapters/login_redux.html#login-template" rel="nofollow">template from the tutorial</a>, and get that working first.</p> <pre><code>{% extends "rango/base.html" %} {% block body_block %} &lt;h1&gt;Login&lt;/h1&gt; ...
0
2016-06-02T08:05:01Z
[ "python", "django" ]
ValueError: need more than 0 values to unpack error in Python
37,571,862
<p>Today I tried to execute the following command in Linux, I want to test the Streaming interface in hadoop,</p> <pre><code> cat test.txt|php wc_mapper.php|python Reducer.py </code></pre> <p>an error happened:</p> <pre><code>"Traceback (most recent call last): File "Reducer.py", line 7, in &lt;module&gt; word,coun...
0
2016-06-01T14:41:27Z
37,572,700
<p>Provide delimiter in <code>split()</code> function</p> <pre><code> try: word,count = line.split(" ") except: print("Error") </code></pre> <p>I have put single space as delimiter. you can change accordingly.</p>
0
2016-06-01T15:17:40Z
[ "php", "python", "hadoop" ]
Pandas: calculate average number of rows per user per day
37,571,870
<p>I have a <code>Pandas DataFrame</code> which has a <code>DATE</code> column and a <code>userid</code> column like so:</p> <pre><code> userid DATE 0 vDKE27PF6z 2016-05-26 1 z6XJewg04Y 2016-05-25 2 e5Fsyak59l 2016-05-25 3 7SaYpGRtMI 2016-05-25 4 KGmTH0XOMz 2016-05-25 </code></pre> <p>There are...
-1
2016-06-01T14:41:43Z
37,572,127
<pre><code>df.groupby('DATE')['userid'].agg(lambda x:x.nunique()*1.0/x.count()) </code></pre> <p>in python3 would be fine without the <code>*1.0</code></p>
2
2016-06-01T14:52:15Z
[ "python", "pandas" ]
Pandas: calculate average number of rows per user per day
37,571,870
<p>I have a <code>Pandas DataFrame</code> which has a <code>DATE</code> column and a <code>userid</code> column like so:</p> <pre><code> userid DATE 0 vDKE27PF6z 2016-05-26 1 z6XJewg04Y 2016-05-25 2 e5Fsyak59l 2016-05-25 3 7SaYpGRtMI 2016-05-25 4 KGmTH0XOMz 2016-05-25 </code></pre> <p>There are...
-1
2016-06-01T14:41:43Z
37,572,129
<p><code>pd.groupby</code> is the way to go. I think you're looking for the <code>describe()</code> function. It gives simple statistics about the DataFrame in question.</p> <pre><code>data = pd.DataFrame({'userid':['vDKE27PF6z', 'z6XJewg04Y', 'e5Fsyak59l', '7SaYpGRtMI', 'KGmTH0XOMz'], ...
0
2016-06-01T14:52:15Z
[ "python", "pandas" ]
Pandas: calculate average number of rows per user per day
37,571,870
<p>I have a <code>Pandas DataFrame</code> which has a <code>DATE</code> column and a <code>userid</code> column like so:</p> <pre><code> userid DATE 0 vDKE27PF6z 2016-05-26 1 z6XJewg04Y 2016-05-25 2 e5Fsyak59l 2016-05-25 3 7SaYpGRtMI 2016-05-25 4 KGmTH0XOMz 2016-05-25 </code></pre> <p>There are...
-1
2016-06-01T14:41:43Z
37,572,147
<p>You should be able to do something like this:</p> <pre><code>df = pd.DataFrame({"userid": ["vDKE27PF6z", "vDKE27PF6z", "e5Fsyak59l", "7SaYpGRtMI", "KGmTH0XOMz" ], "DATE" : ["2016-05-25","2016-05-25","2016-05-25","2016-05-25","2016-05-26"]}) dates = df.groupby("DATE").count() # Number of occurrences of each date ...
2
2016-06-01T14:52:48Z
[ "python", "pandas" ]
Pandas: calculate average number of rows per user per day
37,571,870
<p>I have a <code>Pandas DataFrame</code> which has a <code>DATE</code> column and a <code>userid</code> column like so:</p> <pre><code> userid DATE 0 vDKE27PF6z 2016-05-26 1 z6XJewg04Y 2016-05-25 2 e5Fsyak59l 2016-05-25 3 7SaYpGRtMI 2016-05-25 4 KGmTH0XOMz 2016-05-25 </code></pre> <p>There are...
-1
2016-06-01T14:41:43Z
37,572,207
<p>Suppose you have</p> <pre><code>df userid DATE 0 vDKE27PF6z 2016-05-26 1 z6XJewg04Y 2016-05-25 2 e5Fsyak59l 2016-05-25 3 7SaYpGRtMI 2016-05-25 4 KGmTH0XOMz 2016-05-25 </code></pre> <p>Then you may proceed as follows:</p> <pre><code>df.groupby('DATE',as_index=False).agg(lambda x: 1/len(np.uniqu...
0
2016-06-01T14:55:20Z
[ "python", "pandas" ]
What does each item mean in svmLight Format
37,571,930
<p>I am very confused about what each part means in a svmLight data format. For example:</p> <p>(label/target, [(feature, value), ...], queryid)</p> <p>Does the label means the rank of the data and queryid is the id of the object?</p> <p>For example: for the following item:</p> <p>2 qid:1 1:4.000000 2:2.772589 3:0....
1
2016-06-01T14:44:35Z
37,589,726
<p>The leading number is indeed the "target" of this object. The <code>qid:1</code> part is used in constraining pairwise difference between such objects. The <code>docid</code>, or rather everything after the final <code>#</code> is an info string that </p> <blockquote> <p>can be used to pass additional information...
0
2016-06-02T10:49:40Z
[ "python", "format", "svm", "svmlight" ]
Change Python method parameter name programmatically
37,571,943
<p><strong>I am not looking to change the actual signature of the method</strong></p> <p><strong>I do not want to create a new method with new parameter names</strong></p> <p>How can I modify a parameter's name in a method's signature? </p> <p>I am creating an abstract class for a Spark Streaming job on a custom int...
0
2016-06-01T14:45:07Z
37,572,468
<p>give <code>records</code> a default value so it is optional.</p> <pre><code>def apply(self, sc, records=None): </code></pre>
2
2016-06-01T15:07:42Z
[ "python", "parameters" ]
Python 3.x multi line comment throws syntax error
37,571,974
<p>I'm working on a Python project and as of now, my code has over 400+ lines. At one point, I had to write a multi-line comment about a small bug which needs a work around, and the interpreter decided to throw a syntax error.</p> <p>According to the interpreter, the syntax error is occuring at <strong>elif</strong>. ...
2
2016-06-01T14:46:16Z
37,572,043
<p>This is an indentation error. Your "multi-line comment" (really multi-line string) must be indented under the <code>if</code> block just like anything else.</p> <p><code>""" These kinds of things """</code> are not really comments in Python. You're just creating a string and then throwing the value away (not storin...
7
2016-06-01T14:48:37Z
[ "python", "indentation" ]
Scikit learn linear regression predicting labels
37,572,136
<p>I am trying to use SK learn to perform linear regression on time series labeled data. My data format is <code>data=(timestamp,value,label)</code> </p> <p>The labels that are assigned to my data are either 0 or 1. I tried to follow this <a href="http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html...
1
2016-06-01T14:52:22Z
37,572,222
<p>1 - <code>diabetes_y_train</code> are the labels for train</p> <p>2 - You are using a regression function, so it is right to have continous variables. If you want to have binary output you are not solving a regression problem but a classification one you can then set a threshold to discretise the predictions or use...
0
2016-06-01T14:55:53Z
[ "python", "machine-learning", "scikit-learn", "linear-regression" ]
Scikit learn linear regression predicting labels
37,572,136
<p>I am trying to use SK learn to perform linear regression on time series labeled data. My data format is <code>data=(timestamp,value,label)</code> </p> <p>The labels that are assigned to my data are either 0 or 1. I tried to follow this <a href="http://scikit-learn.org/stable/auto_examples/linear_model/plot_ols.html...
1
2016-06-01T14:52:22Z
37,572,304
<p>1 - Yes</p> <p>2 - Predict calculates a floating point number, because the example is trying to predict a floating point value and not a binary value. So there is no yes/no answer, but a predictaed value, and to estimate the error, a difference is calculated and averaged in <code>np.mean((regr.predict(diabetes_X_te...
-1
2016-06-01T14:59:07Z
[ "python", "machine-learning", "scikit-learn", "linear-regression" ]
Python Calculator (DIviding by zero properly)
37,572,223
<p>I'm very new to programming in Python and most of the answers I have searched for are more complex versions of the script than I am looking for. I have made very simplistic calculator:</p> <pre><code>loop = 1 choice = 0 while loop == 1: print 'Python Calculator!\n' print 'Mathematical Operation:\n' ...
-1
2016-06-01T14:55:55Z
37,572,275
<p>Put your division operation in a <code>try-except</code> block like this:</p> <pre><code>try: # put division here div1/div2 pass except ZeroDivisionError: print "Divide by 0 Error" </code></pre>
1
2016-06-01T14:57:47Z
[ "python", "calculator", "divide-by-zero", "dividebyzeroexception" ]
Python Calculator (DIviding by zero properly)
37,572,223
<p>I'm very new to programming in Python and most of the answers I have searched for are more complex versions of the script than I am looking for. I have made very simplistic calculator:</p> <pre><code>loop = 1 choice = 0 while loop == 1: print 'Python Calculator!\n' print 'Mathematical Operation:\n' ...
-1
2016-06-01T14:55:55Z
37,572,305
<p>Use a condition on div2 that returns the string "Divide by 0 Error" rather than handling the exception - that way is much simpler. </p> <pre><code>if div2 == 0: print "Divide by 0 Error" else: print div1, '/', div2, '=', div1/div2 </code></pre> <p>The reason why you want to avoid the try/catch is because...
0
2016-06-01T14:59:08Z
[ "python", "calculator", "divide-by-zero", "dividebyzeroexception" ]
Python Calculator (DIviding by zero properly)
37,572,223
<p>I'm very new to programming in Python and most of the answers I have searched for are more complex versions of the script than I am looking for. I have made very simplistic calculator:</p> <pre><code>loop = 1 choice = 0 while loop == 1: print 'Python Calculator!\n' print 'Mathematical Operation:\n' ...
-1
2016-06-01T14:55:55Z
37,572,320
<p>try/except :)</p> <pre><code>try: print div1, '/', div2, '=', div1/div2 except ZeroDivisionError: print div1, '/', div2, ':', 'Division by zero!' </code></pre>
0
2016-06-01T14:59:48Z
[ "python", "calculator", "divide-by-zero", "dividebyzeroexception" ]
Failed to retrieve access token google-app-engine
37,572,225
<p>I'm trying out the <a href="https://github.com/GoogleCloudPlatform/appengine-mapreduce/wiki/3.2-Example-Code" rel="nofollow">appengine-mapreduce python example</a> and getting into endless waiting for the mapreduce.mapper_pipeline.MapperPipeline task as it retries to retrieve access token. I run it locally. What cou...
0
2016-06-01T14:55:58Z
37,614,188
<p>Deleting the ~/.config/gcloud/application_default_credentials.json fixed the problem. Found it here <a href="https://code.google.com/p/googleappengine/issues/detail?id=11690" rel="nofollow">#3</a></p>
1
2016-06-03T12:16:34Z
[ "python", "google-app-engine", "google-cloud-platform" ]
Change projection of a fits image
37,572,240
<p>This is my first question here, so I'll try to explain it well.</p> <p>I am working with some all-sky fits astronomical images, which are in galactic coordinates (in the AITOF projection). I would like to transform these fits images into RA,Dec coordinates, so that the image is rotated in the proper way (i.e. the ...
-1
2016-06-01T14:56:31Z
38,091,902
<p>This is not a pyfits problem. You have to perform the conversion. Numpy may help you.</p> <p>There are several standards (1932, 1958)</p> <p>See <a href="http://scienceworld.wolfram.com/astronomy/GalacticCoordinates.html" rel="nofollow">http://scienceworld.wolfram.com/astronomy/GalacticCoordinates.html</a></p>
0
2016-06-29T06:29:23Z
[ "python", "astropy", "fits", "pyfits" ]
Using Splinter to click on multiple buttons on one page
37,572,260
<p>On one webpage, there exist a series of buttons with the same name that I need to select. I can collect these buttons through a command like </p> <p><code>buttons = browser.find_by_name("value")</code></p> <p>but once I select one of these buttons the rest of the elements are "Stale" and unable to be used. Is ther...
0
2016-06-01T14:57:17Z
38,287,766
<p>Could you link to the page where you tried this?</p> <p>I am a bit surprised that the other elements go stale after clicking on of them, but oh well. This should work although it might be bit slow:</p> <pre><code>buttons = browser.find_by_name("value") buttons_length = len(buttons) buttons[0].click() for i in ran...
0
2016-07-10T01:20:34Z
[ "python", "python-3.x", "splinter" ]
broadcasting — multiply a (NxN) array by a (M) array to have a (NxNxM) array
37,572,393
<p>I have two <code>numpy</code>'s <em>ndarrays</em></p> <pre><code>a.shape # -&gt; (3, 3) b.shape # -&gt; (5,) </code></pre> <p>and I want to compute a <code>c</code> array, defined by</p> <pre><code>c.shape # -&gt; (3, 3, 5) c[...,i] = a*b[i] </code></pre> <p>(the exact shape of <code>c</code> is unimportant beca...
1
2016-06-01T15:03:50Z
37,572,542
<p>A nice solution is to use the fantastic <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.einsum.html"><code>einsum</code></a> function:</p> <pre><code>&gt;&gt;&gt; a = np.array([[1,2,3],[4,5,6],[7,8,9]]) &gt;&gt;&gt; b = np.array([10, 100, 1000, 10000, 100000]) &gt;&gt;&gt; c = np.einsum('ij,k-&gt...
5
2016-06-01T15:10:52Z
[ "python", "numpy" ]
broadcasting — multiply a (NxN) array by a (M) array to have a (NxNxM) array
37,572,393
<p>I have two <code>numpy</code>'s <em>ndarrays</em></p> <pre><code>a.shape # -&gt; (3, 3) b.shape # -&gt; (5,) </code></pre> <p>and I want to compute a <code>c</code> array, defined by</p> <pre><code>c.shape # -&gt; (3, 3, 5) c[...,i] = a*b[i] </code></pre> <p>(the exact shape of <code>c</code> is unimportant beca...
1
2016-06-01T15:03:50Z
37,573,037
<p>An alternative solution would be with <a href="http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.outer.html" rel="nofollow"><code>np.outer</code></a> as basically we are performing outer product there. Now, <code>np.outer</code> expects the inputs to be <code>1D</code> arrays and as the pre-processing...
0
2016-06-01T15:32:57Z
[ "python", "numpy" ]
Find the value change and the index in a dictionary
37,572,459
<p>I have a large dictionary:</p> <pre><code>exp_dict={0: {'length': 38.63999999999999, 'line_nm': [['Hammersmith &amp; City_1'], ['Hammersmith &amp; City_1'], ['Hammersmith &amp; City_1'], ['Metropolitan_1', 'Hammersmith &amp; City_1'], ['Metropolitan_1', 'Hammersmith &amp; City_1'], ['Metropol...
1
2016-06-01T15:07:09Z
37,582,051
<p>Here are some thoughts:</p> <ul> <li>Don't use <code>dict</code> as a variable name, because it already exists as a builtin. Use <code>dict_</code> (or another name altogether)</li> <li>It's better Python style to include spaces around operators like "==" and "=" (a great resource: <a href="https://www.python.org/...
1
2016-06-02T03:18:49Z
[ "python", "list", "dictionary", "indexing", "intersection" ]
Running .exe files with user arguments in python
37,572,506
<p>I have compiled a windows executable that connects to a software radio and reads out the values in its registers. When I execute this in command prompt, it returns me the following output</p> <p><a href="http://i.stack.imgur.com/qwQpb.png" rel="nofollow"><img src="http://i.stack.imgur.com/qwQpb.png" alt="Running th...
0
2016-06-01T15:09:34Z
37,572,876
<p><code>flush</code> the pipe when you write a command (and include newlines to simulate user inputs with Enter key presses, assuming program expects that), and <code>close</code> the pipe when you're done. It's also generally a good idea to avoid <code>shell=True</code>, as it introduces additional layers wrapping th...
1
2016-06-01T15:25:13Z
[ "python", "cmd" ]
Running .exe files with user arguments in python
37,572,506
<p>I have compiled a windows executable that connects to a software radio and reads out the values in its registers. When I execute this in command prompt, it returns me the following output</p> <p><a href="http://i.stack.imgur.com/qwQpb.png" rel="nofollow"><img src="http://i.stack.imgur.com/qwQpb.png" alt="Running th...
0
2016-06-01T15:09:34Z
37,572,910
<p>When you use your program interactively, I assume that you type <em>101 <kbd>Return</kbd></em>, and then <em>q <kbd>Return</kbd></em>.</p> <p>When you start it from Python, you must simulate that <kbd>Return</kbd> with a <code>\n</code>, and you should wait the program to end instead of killing it:</p> <pre><code>...
1
2016-06-01T15:26:29Z
[ "python", "cmd" ]
Pre-populating HTML forms within python CGI
37,572,606
<p>I have been working on a URL parser for the get method when writing CGI scripts in python 2.7. Moving forward I am trying to have my HTML forms pre-populate with either nothing (if the webpage has been just opened) or with what the user entered previously. The script links to itself so everything is being called cor...
0
2016-06-01T15:13:46Z
37,573,277
<p>Found the answer. A combination of using a bad test case for my if statements as well as incorrect quoting. If anyone is interested I can post the full code up for reference.</p>
0
2016-06-01T15:44:30Z
[ "python", "html", "cgi", "dynamic-websites" ]
Pandas groupby and make set of items
37,572,611
<p>I am using pandas groupby and want to apply the function to make a set from the items in the group.</p> <p>The following does not work:</p> <pre><code>df = df.groupby('col1')['col2'].agg({'size': len, 'set': set}) </code></pre> <p>But the following works:</p> <pre><code>def to_set(x): return set(x) df = df....
0
2016-06-01T15:14:01Z
37,572,897
<p>It's because <code>set</code> is of <code>type</code> <code>type</code> whereas <code>to_set</code> is of <code>type</code> <code>function</code>:</p> <pre><code>type(set) &lt;class 'type'&gt; def to_set(x): return set(x) type(to_set) &lt;class 'function'&gt; </code></pre> <p>According to the <a href="http:...
2
2016-06-01T15:26:06Z
[ "python", "pandas" ]
python etree insert, append and SubElement
37,572,695
<p>I want to create an element tree like this in Python:</p> <pre><code>&lt;parent&gt; &lt;child/&gt; &lt;child/&gt; &lt;child/&gt; &lt;/parent&gt; </code></pre> <p>I want to use it as an empty template that I can work on later. However, I cannot insert or append multiple <code>&lt;child&gt;</code> element to t...
-1
2016-06-01T15:17:25Z
37,572,907
<p>I guess you need to create new element objects to append them to the root, otherwise it is the same element that you append twice, which has no effect :</p> <pre><code>root = etree.Element('root') for i in range(3): child = etree.Element('child') root.append(child) </code></pre> <p>Hope this helps.</p>
1
2016-06-01T15:26:27Z
[ "python", "xml", "lxml", "elementtree" ]
python: insert the list data into database
37,572,698
<p>there is postgresql database named movie_db, and created a table named films as following:</p> <pre><code>CREATE TABLE movies ( title varchar(128) NOT NULL, description varchar(256) NOT NULL, directors varchar(128)[], roles varchar(128)[] ); </code></pre> <p>I have four list for the title, descr...
0
2016-06-01T15:17:38Z
37,573,818
<p><strong>psycopg2</strong> has a great support for array insert. This probably will help. </p> <pre><code>import psycopg2 conn = psycopg2.connect(database="postgres") cur = conn.cursor() title = ['a', 'b', 'c'] description = ['good love', 'sun beautiful', 'wind go'] director = ['tom', 'jack', 'john'] directors = [...
2
2016-06-01T16:10:50Z
[ "python", "sql", "postgresql", "list", "insert" ]
Flask-SQLAlchemy insert records with multiple foreign keys
37,572,811
<p>I have 3 tables:</p> <pre><code>class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String) successes = db.relationship('Success', backref='user', lazy='dynamic') class Success(db.Model): id = db.Column(db.Integer, primary_key=True) package = db.Column(db.String) ...
0
2016-06-01T15:22:34Z
37,891,337
<p>You can do the exact same thing with <code>trial.successes</code> and it should just work. By extending <code>user.successes</code> you add the <code>Success</code> instances to the session and associate them with the <code>User</code> instance. By extending <code>trial.successes</code>, you add the <code>Success</c...
1
2016-06-17T22:39:28Z
[ "python", "flask", "sqlalchemy", "foreign-keys", "flask-sqlalchemy" ]
Serial vectorial subtraction in Python or "subtractive convolution"?
37,572,822
<p>First of all, I would like to apologize for the unclear title of the question: the reason is I couldn't identify the mathematical process at work.</p> <p>Here is the situation in a nutshell:</p> <ol> <li>I have two vectors, f1 and f2, of different lengths.</li> <li>I want to calculate the least square distance bet...
1
2016-06-01T15:22:57Z
37,686,871
<p>First, I want to point out that the number of terms in <code>dist</code> is not <code>len(f1)-nBuf</code> but <code>len(f1)-nBuf+1</code>. That's just how many ways the shorter vector fully overlaps with the longer one.</p> <p>Ignoring the division by <code>len(f1)</code>, which is just scaling by a constant, you a...
2
2016-06-07T18:37:41Z
[ "python", "python-3.x", "numpy", "convolution", "least-squares" ]
Assign time element of DateTimeIndex to new column
37,572,827
<p>im working with the below <code>DataFrame</code> and want to access only the time (not date) of my <code>DateTimeIndex</code>:</p> <pre><code> idle wheel Induce wheel axial radial tiempo 5/30/2016 19:37:46 -1,099.12 -1,048.78 -477.13 5/30/2016 19:37:47 -1,099.12 -1,048.78 -4...
2
2016-06-01T15:23:05Z
37,573,205
<p>Use <code>.time</code> on your <code>index</code> <code>'tiempo'</code> :</p> <pre><code>df['time'] = df.index.time </code></pre> <p>or, if <code>'tiempo'</code> is a <code>column</code> use</p> <pre><code>df['time'] = df.tiempo.dt.time </code></pre> <p>to get:</p> <pre><code> tiempo idle wheel ...
2
2016-06-01T15:41:49Z
[ "python", "pandas", "dataframe", "datetimeindex" ]
How can I make Python 3's Print fit the size of the command prompt?
37,572,837
<p>Python 3 can easily handle printing a lot of text:</p> <pre><code>text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vitae odio quis felis consectetur blandit. Etiam mattis vehicula ex id sodales. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris fermentum semper nisi vel aliqua...
2
2016-06-01T15:23:23Z
37,572,963
<p>You might have a look at this <a href="https://gist.github.com/jtriley/1108174" rel="nofollow">Gist</a>.</p> <p>Then using the returned values to split the string in subsequent <code>print</code> calls accordingly.</p> <p><strong>IDLE shell</strong>: </p> <p>Width can be retrieved with sys.stdout.shell.width and ...
1
2016-06-01T15:29:02Z
[ "python", "python-3.x", "printing", "lines" ]
How can I make Python 3's Print fit the size of the command prompt?
37,572,837
<p>Python 3 can easily handle printing a lot of text:</p> <pre><code>text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vitae odio quis felis consectetur blandit. Etiam mattis vehicula ex id sodales. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris fermentum semper nisi vel aliqua...
2
2016-06-01T15:23:23Z
37,573,392
<p>The hard part will be to get the size of the console (Windows world) or terminal (Unix), because I know no portable way to get it. It involves (as shown in the <a href="https://gist.github.com/jtriley/1108174" rel="nofollow">Gist</a> proposed by @MaximeB):</p> <ul> <li>the use of <code>GetConsoleScreenBufferInfo</c...
1
2016-06-01T15:49:31Z
[ "python", "python-3.x", "printing", "lines" ]
How can I make Python 3's Print fit the size of the command prompt?
37,572,837
<p>Python 3 can easily handle printing a lot of text:</p> <pre><code>text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vitae odio quis felis consectetur blandit. Etiam mattis vehicula ex id sodales. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris fermentum semper nisi vel aliqua...
2
2016-06-01T15:23:23Z
37,573,636
<p>As mentioned in the comments, <a href="https://docs.python.org/3/library/pprint.html" rel="nofollow"><code>pprint</code></a> and <a href="https://docs.python.org/3/library/textwrap.html" rel="nofollow"><code>textwrap</code></a> can be used to align output to a given width. Given that, the only trick is determining t...
3
2016-06-01T16:01:23Z
[ "python", "python-3.x", "printing", "lines" ]
Extracting weights from .caffemodel without caffe installed in Python
37,572,948
<p>Is there a relatively simple way to extract weights in Python from one of the many pretrained models in Caffe Zoo <em>WITHOUT CAFFE</em> (nor pyCaffe)? i.e. parsing <code>.caffemodel</code> to hdf5/numpy or whatever format that can be read by Python? </p> <p>All the answers I found use C++ code with caffe classes ...
1
2016-06-01T15:28:37Z
37,573,293
<p>Nowadays, caffe can save the weights in two formats: BINARYPROTO, or HDF5. Binary weights files with extension <code>.caffemodel</code> are in BINARYPROTO format, while extension <code>.caffemodel.h5</code> are in HDF5 format. Since the HDF5 format was introduced to caffe recently, I expect most models you currently...
1
2016-06-01T15:45:09Z
[ "python", "neural-network", "deep-learning", "caffe", "pycaffe" ]
Extracting weights from .caffemodel without caffe installed in Python
37,572,948
<p>Is there a relatively simple way to extract weights in Python from one of the many pretrained models in Caffe Zoo <em>WITHOUT CAFFE</em> (nor pyCaffe)? i.e. parsing <code>.caffemodel</code> to hdf5/numpy or whatever format that can be read by Python? </p> <p>All the answers I found use C++ code with caffe classes ...
1
2016-06-01T15:28:37Z
37,576,017
<p>I don't understand why you want to do that without caffe/pycaffe, perhaps you are tired of deploying caffe on new machine ? But since caffemodel is special binary data type of caffe, using others' tool doesn't make life easier.</p> <p>If you do insist to do this, there is another framework : <a href="http://mochajl...
1
2016-06-01T18:16:46Z
[ "python", "neural-network", "deep-learning", "caffe", "pycaffe" ]
Extracting weights from .caffemodel without caffe installed in Python
37,572,948
<p>Is there a relatively simple way to extract weights in Python from one of the many pretrained models in Caffe Zoo <em>WITHOUT CAFFE</em> (nor pyCaffe)? i.e. parsing <code>.caffemodel</code> to hdf5/numpy or whatever format that can be read by Python? </p> <p>All the answers I found use C++ code with caffe classes ...
1
2016-06-01T15:28:37Z
38,687,082
<p>As it so happens ethereon made a wonderful library to convert caffe models to tensorflow code but that is not all !<br> It also allows the user to convert .caffemodel to .npy without having to build pycaffe !!!<br> It tests if caffe was built and if not it falls back to a pure google protobuf implementation !<br> Wa...
1
2016-07-31T18:21:43Z
[ "python", "neural-network", "deep-learning", "caffe", "pycaffe" ]
How do I avoid login for messaging Using Python Praw script?
37,572,976
<p>I have written a script to archive submissions and comments of a certain author on Reddit. When it detects a new post I have it pm me the content.</p> <p>Currently I start the session like this...</p> <pre><code>client = praw.Reddit(user_agent=USER_AGENT) client.set_oauth_app_info(client_id = CLIENT_ID, client_sec...
0
2016-06-01T15:29:32Z
37,573,540
<p>You need the <code>privatemessages</code> OAuth Scope.<br> Use it as a string in <code>get_authorize_url()</code>, as shown here: <a href="https://praw.readthedocs.io/en/stable/pages/oauth.html#step-3-getting-authorization-from-the-user" rel="nofollow">https://praw.readthedocs.io/en/stable/pages/oauth.html#step-3-ge...
1
2016-06-01T15:56:55Z
[ "python", "oauth", "reddit", "praw" ]
Issues printing email content sent with python in Android
37,573,036
<p>I'm making an android application that has to take an email, which has been sent via a python script to a gmail account, and search the subject and message body for certain phrases. I haven't had any problem setting up the email services (I'm using the smtp library to send in python, and javamail IMAP to read in and...
0
2016-06-01T15:32:55Z
37,573,447
<p>I had also some problems in the past and it was due to a strange indentation. If you look below the From/TO/Subjct has no spaces from beginning of the line. Taking from one def:</p> <pre><code>def mail_form(): ...... message = """\ From: %s To: %s Subject: %s %s """ % (FROM, "; ".join(TO), SUBJECT, TEXT) .....
0
2016-06-01T15:51:43Z
[ "android", "python", "email", "javamail" ]
Python script: no output, but no errors?
37,573,084
<p>I have a series of short DNA alignments and I want to track the locations and kinds of mismatches within them. The alignments are separated by '--' so the file looks like this:</p> <pre><code>TTCGCTTGCAGAGAGAAATCAC ||||| |||||||||||||||| TTCGCATGCAGAGAGAAATCAC -- TGCTCACCTCTCTTTCTGTCAGT ||||||||||||||| ||||||| TGCT...
-2
2016-06-01T15:35:14Z
37,573,474
<p>Your Python script need main entry point to run it.</p> <p>add the below at the bottom of your script</p> <pre><code>if __name__ == '__main__': # Call the function you want to invoke. </code></pre> <p>Then you at least see your function getting executed. Then you can start debugging further.</p>
0
2016-06-01T15:53:16Z
[ "python" ]
Django Rest Framework: Custom url pattern for Detail model-viewset with datetime lookup field
37,573,119
<p>I have a ModelViewSet defined with lookup field as <code>timestamp</code> (a datetime field) instead of default <code>pk</code> field</p> <p>Here is my code:</p> <pre><code>class MySerializer(serializers.ModelSerializer): class Meta: model = ACFCrowdData class MyViewSet(viewsets.ModelViewSet): que...
2
2016-06-01T15:37:16Z
37,573,552
<p>You can make a custom <code>retrieve</code> method and use your own timestamp parser. Something like this might do the trick. I haven't tried this specific code out, but the principle should work.</p> <pre><code>from datetime import datetime class MyViewSet(viewsets.ModelViewSet): ... def retrieve(self, ...
2
2016-06-01T15:57:24Z
[ "python", "django", "django-rest-framework" ]
Heroku MySQL DB Error with Flask
37,573,189
<p>I'm trying to host a local MySQL database using ClearDB on Heroku. The build is successful, but when I try to access the application, the application fails. </p> <p>Here is my app.py code (it fails on the first line):</p> <pre><code>db = MySQLdb.connect(host="localhost", user="root", db="database") cur = db.cursor...
0
2016-06-01T15:41:04Z
37,573,323
<p>There's no point in posting your Heroku config, because it's clear that your app isn't using it. You have hardcoded the database host as "localhost", rather than using the DATABASE_URL environment variable.</p>
0
2016-06-01T15:46:37Z
[ "python", "mysql", "heroku", "flask" ]
matplotlib: efficient way to create large number of Patch objects
37,573,314
<p>I have some Python code that plots a large number of non-regular polygons using matplotlib from some ocean model data.</p> <p>I do this by creating 4 numpy arrays of shape (N,2) defining the corners of each patch, where N is a large number (say 500,000)</p> <p>I then create matplotlib Patch object for each set of ...
2
2016-06-01T15:46:01Z
37,579,426
<p>What about to create collection by <code>matplolib.collections</code> instead of creating every polygon (or patch)? Look at the examples here: <a href="http://matplotlib.org/examples/api/collections_demo.html" rel="nofollow">http://matplotlib.org/examples/api/collections_demo.html</a></p> <p>And read matplotlib doc...
3
2016-06-01T21:54:13Z
[ "python", "numpy", "matplotlib" ]
matplotlib: efficient way to create large number of Patch objects
37,573,314
<p>I have some Python code that plots a large number of non-regular polygons using matplotlib from some ocean model data.</p> <p>I do this by creating 4 numpy arrays of shape (N,2) defining the corners of each patch, where N is a large number (say 500,000)</p> <p>I then create matplotlib Patch object for each set of ...
2
2016-06-01T15:46:01Z
37,579,557
<p><code>patches</code> could also be created with:</p> <pre><code>cc=np.stack((c1,c2,c3,c4),1) patches = [plt.Polygon(verts) for verts in cc] </code></pre> <p>This still involves a loop, but moves the stack out of the loop (<code>np.stack</code> is newish function; I can rewrite it if you version doesn't have it).</...
1
2016-06-01T22:05:05Z
[ "python", "numpy", "matplotlib" ]
Kivy DropDown not affected by max_height
37,573,325
<p>I've noticed some strange behaviour of the <code>DropDown</code> widget in Kivy <code>v1.9.2-dev0</code>.<br> The <a href="https://kivy.org/docs/api-kivy.uix.dropdown.html#kivy.uix.dropdown.DropDown.max_height" rel="nofollow">documentation</a> states:</p> <blockquote> <p><code>max_height</code><br> Indicate the...
3
2016-06-01T15:46:38Z
39,090,596
<p>This seemed to indeed be a bug, i just sent a pull request to fix it (<a href="https://github.com/kivy/kivy/pull/4550" rel="nofollow">https://github.com/kivy/kivy/pull/4550</a>), thanks for reporting, and sorry for the long delay!</p> <p>edit: fix was merged</p>
0
2016-08-23T00:30:48Z
[ "python", "python-3.x", "kivy" ]
Python dict key Sorted by list as value
37,573,373
<p>I have a list of dict like this, the value of each dict key is a list,</p> <pre><code>[{'mike':[500,1000,1500,2750,3000]},{'john':[750,1250,2000]},{'luke':[600,1100]}] </code></pre> <p>The number of dict in list will vary.</p> <p>How i can get output like this, Each dict value in ascending order</p> <pre><code>5...
3
2016-06-01T15:48:46Z
37,573,661
<p>Use <a href="https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions" rel="nofollow">list comprehensions</a> to flat the list of dicts into a list of tuples <code>(value, key)</code>, use <a href="https://docs.python.org/3/library/functions.html#sorted" rel="nofollow"><code>sorted</code></a> to so...
1
2016-06-01T16:02:42Z
[ "python", "list" ]
Python dict key Sorted by list as value
37,573,373
<p>I have a list of dict like this, the value of each dict key is a list,</p> <pre><code>[{'mike':[500,1000,1500,2750,3000]},{'john':[750,1250,2000]},{'luke':[600,1100]}] </code></pre> <p>The number of dict in list will vary.</p> <p>How i can get output like this, Each dict value in ascending order</p> <pre><code>5...
3
2016-06-01T15:48:46Z
37,573,664
<pre><code>a,b=[],[] for i in g: for k in i.values()[0]: a.append(k) b.append(i.keys()) print sorted(zip(a,b)) </code></pre>
0
2016-06-01T16:02:43Z
[ "python", "list" ]
Python dict key Sorted by list as value
37,573,373
<p>I have a list of dict like this, the value of each dict key is a list,</p> <pre><code>[{'mike':[500,1000,1500,2750,3000]},{'john':[750,1250,2000]},{'luke':[600,1100]}] </code></pre> <p>The number of dict in list will vary.</p> <p>How i can get output like this, Each dict value in ascending order</p> <pre><code>5...
3
2016-06-01T15:48:46Z
37,573,741
<h1>A one liner:</h1> <pre><code>result = sorted(((item, key) for d in x for (key, value) in d.items() for item in value), key=lambda x: x[0]) for elem in result: print ({elem[0]}:{elem[0]}.format(elem=elem) </code></pre> <h1>A multi liner:</h1> <pre><code>x = [{"mike":[500,1000,1500,2750,3000]},{"john":[750,12...
2
2016-06-01T16:06:40Z
[ "python", "list" ]
Python dict key Sorted by list as value
37,573,373
<p>I have a list of dict like this, the value of each dict key is a list,</p> <pre><code>[{'mike':[500,1000,1500,2750,3000]},{'john':[750,1250,2000]},{'luke':[600,1100]}] </code></pre> <p>The number of dict in list will vary.</p> <p>How i can get output like this, Each dict value in ascending order</p> <pre><code>5...
3
2016-06-01T15:48:46Z
37,573,760
<p>You use <code>itertools</code> for solving this problem:</p> <pre><code>from itertools import product, chain LL = list(chain(*[list(product(i.keys(), i.values()[0])) for i in L])) sorted(LL, key=lambda x: x[1]) Out[152]: [('mike', 500), ('luke', 600), ('john', 750), ('mike', 1000), ('luke', 1100), ('john', 1...
1
2016-06-01T16:07:28Z
[ "python", "list" ]
Install error for PIL/PILLOW in Pycharm
37,573,436
<p>I have tried to install both the PIL and PILLOW packages in pycharm but I'm getting some errors when I try from the terminal as suggested. How can I resolve them?</p> <p>Error:</p> <pre><code>ValueError: jpeg is required unless explicitly disabled using --disable-jpeg, aborting </code></pre> <p>followed by:</p> ...
0
2016-06-01T15:51:08Z
37,573,500
<p>You need to install python development tools first</p> <p>Python 2:</p> <pre><code>sudo apt-get install python-dev python-setuptools </code></pre> <p>Python 3:</p> <pre><code>sudo apt-get install python3-dev python3-setuptools </code></pre> <p>See other requirements in this <a href="http://stackoverflow.com/a/3...
3
2016-06-01T15:54:36Z
[ "python", "pycharm" ]
Progress Bar while download file over http with Requests
37,573,483
<p>I need to download a sizable (~200MB) file. I figured out how to download and save the file with <a href="http://stackoverflow.com/questions/16694907/how-to-download-large-file-in-python-with-requests-py">here</a>. It would be nice to have a progress bar to know how much has been downloaded. I found <a href="http://...
3
2016-06-01T15:53:42Z
37,573,701
<p>I suggest you try <code>tqdm</code>[1], it's very easy to use. Example code for downloading with <code>requests</code> library[2]:</p> <pre><code>from tqdm import tqdm import requests url = "http://example.com/bigfile.bin" # Streaming, so we can iterate over the response. response = requests.get(url, stream=True) ...
5
2016-06-01T16:04:43Z
[ "python", "python-requests" ]
Progress Bar while download file over http with Requests
37,573,483
<p>I need to download a sizable (~200MB) file. I figured out how to download and save the file with <a href="http://stackoverflow.com/questions/16694907/how-to-download-large-file-in-python-with-requests-py">here</a>. It would be nice to have a progress bar to know how much has been downloaded. I found <a href="http://...
3
2016-06-01T15:53:42Z
37,573,781
<p>It seems like you're going to need to get the remote file size (<a href="http://stackoverflow.com/questions/24584956/get-file-size-before-downloading-using-http-header-not-matching-with-one-retriev">answered here</a>) to calculate how far along you are.</p> <p>You could then update your progress bar while processin...
2
2016-06-01T16:08:43Z
[ "python", "python-requests" ]
Progress Bar while download file over http with Requests
37,573,483
<p>I need to download a sizable (~200MB) file. I figured out how to download and save the file with <a href="http://stackoverflow.com/questions/16694907/how-to-download-large-file-in-python-with-requests-py">here</a>. It would be nice to have a progress bar to know how much has been downloaded. I found <a href="http://...
3
2016-06-01T15:53:42Z
37,574,635
<p>It seems that there is a disconnect between the examples on the <a href="http://progressbar-2.readthedocs.io/en/latest/usage.html" rel="nofollow">Progress Bar Usage</a> page and what the code actually requires.</p> <p>In the following example, not the use of <code>maxval</code> instead of <code>max_value</code>. Al...
1
2016-06-01T16:55:08Z
[ "python", "python-requests" ]
Why is this output 30 in python?
37,573,502
<p>Can someone explain why this code of python outputs 30? It seems like add = func ? But how does python knows this without declaring. It's a question in the python course from sololearn.com, a lot of people don't seem to understand</p> <pre><code>def add(x, y): return x + y def do_twice(func, x, y): return ...
-3
2016-06-01T15:54:45Z
37,573,650
<pre><code>def do_twice(func, x, y): return func(func(x, y), func(x, y)) </code></pre> <p>when called with <code>add</code>, <code>5</code> and <code>10</code> will return </p> <pre><code>add(add(5, 10), add(5, 10)) </code></pre> <p>i.e.</p> <pre><code>add(15, 15) </code></pre> <p>which is indeed <code>30</cod...
4
2016-06-01T16:02:13Z
[ "python", "function" ]
Why is this output 30 in python?
37,573,502
<p>Can someone explain why this code of python outputs 30? It seems like add = func ? But how does python knows this without declaring. It's a question in the python course from sololearn.com, a lot of people don't seem to understand</p> <pre><code>def add(x, y): return x + y def do_twice(func, x, y): return ...
-3
2016-06-01T15:54:45Z
37,573,691
<p>A is set to 5 and B to 10. This add function simply returns the sum of two inputs. You call do_twice with the add function, 5, and, 10 as inputs. First, do_twice evaluates the sum of 5 and 10 in both inner calls of func(x, y). This leaves us with "return func(15, 15)". This adds 15 and 15, yielding 30. Finally, yo...
1
2016-06-01T16:04:19Z
[ "python", "function" ]
Why is this output 30 in python?
37,573,502
<p>Can someone explain why this code of python outputs 30? It seems like add = func ? But how does python knows this without declaring. It's a question in the python course from sololearn.com, a lot of people don't seem to understand</p> <pre><code>def add(x, y): return x + y def do_twice(func, x, y): return ...
-3
2016-06-01T15:54:45Z
37,573,839
<p>Python don't care what you pass in for func for your function do-twice. But in the body of your function do_twice you are invoking func passed in i.e You are using func as if it supposed to be a callable(something you can invoke. A function is one such thing.). You can verify it by passing a string to do_twice and...
1
2016-06-01T16:12:16Z
[ "python", "function" ]
Is Text.concordance() in nltk available for pyspark as distributed method
37,573,533
<p>I'm working on Natural Language Processing using NLTK on spark. where tried to implement <strong>3.1 Accessing Text from the Web and from Disk</strong> part from <a href="http://www.nltk.org/book/ch03.html" rel="nofollow">http://www.nltk.org/book/ch03.html</a>. For this I followed How to do Natural Language Proces...
1
2016-06-01T15:56:16Z
37,819,354
<p>There are two issues here. </p> <p>First, this:</p> <pre><code>text = words.map(lambda x : Text(x).concordance('gene')) </code></pre> <p>maps over the individual tokens in <code>words</code>. That is, you're converting each word into a one-word text. What you want instead of <code>map</code> is <code>mapPartit...
0
2016-06-14T18:16:44Z
[ "python", "apache-spark", "nlp", "nltk", "pyspark" ]
Access attributes of a Multigraph in NetworkX
37,573,534
<p>I am using code from this question: <a href="http://stackoverflow.com/questions/25639169/networkx-change-color-width-according-to-edge-attributes-inconsistent-result">networkx - change color/width according to edge attributes - inconsistent result</a> because it almost answers my question, but I am working with a Mu...
0
2016-06-01T15:56:20Z
37,573,728
<p>Changing the line causing the error to</p> <pre><code>colors = [print(G[u][v]) for u,v in edges] </code></pre> <p>We can see what you are actually looking at is:</p> <pre><code>{0: {'color': 'r'}} {0: {'color': 'b'}} {0: {'color': 'g'}} </code></pre> <p>I assume networkx is storing which graph it is on as the ke...
2
2016-06-01T16:06:08Z
[ "python", "networkx" ]
How to assign sample_weights in sklearn.cluster DBSCAN?
37,573,536
<p>I'm using DBSCAN to find clusters of pixel values of an RGB image.</p> <p><code>db = DBSCAN(eps=0.3, min_samples=10).fit(X)</code></p> <p>where, <code>X</code> is an <code>N x 3</code> matrix. Each row of <code>X</code> contains RGB triplets.</p> <p>Now, I want to assign weights to pixel values as a function of d...
0
2016-06-01T15:56:43Z
37,579,051
<p>It seems that you are using scikit-learn v &lt;= 0.15, as this is the last version where DBSCAN had fit of form</p> <pre><code>fit(X) </code></pre> <p>since 0.16 it is</p> <pre><code>fit(X, y=None, sample_weight=None) </code></pre> <p>Simply update your scikit-learn to 0.16 or 0.17.X</p>
2
2016-06-01T21:26:05Z
[ "python", "machine-learning", "dbscan" ]
How to use Firebase REST API(Python) for authentication of a user?
37,573,706
<p>I am using Firebase as backend for my Internet of Things app. Using python on my Raspberry Pi, I am storing data on Firebase. As of currently my database is public for r/w. I have created an dummy account using Console>Auth>Users. I want to use this account to sign in to my Firebase App through my Raspberry Pi using...
2
2016-06-01T16:04:58Z
37,579,186
<p>Alfonso from the Firebase Auth team. </p> <p>We currently do not have a supported or documented REST API for auth. </p> <p>You can still create a project through the legacy console and use the old docs to learn how to mint your own custom auth tokens, and send them over to the database REST API for authentication....
2
2016-06-01T21:35:08Z
[ "python", "firebase", "firebase-authentication" ]
Trying to copy column1 from a csv file to another empty file using python
37,573,805
<p>I'm looking for a way using python to copy the first column from a csv into an empty file. I'm trying to learn python so any help would be great!</p> <p>So if this is <code>test.csv</code></p> <pre><code>A 32 D 21 C 2 B 20 </code></pre> <p>I want this output</p> <pre><code>A D C B </code></pre> <p>I've tried th...
0
2016-06-01T16:10:01Z
37,573,870
<p>This answer reads the CSV file, understanding a column to be demarked by a space character. You have to add the <code>header=None</code> otherwise the first row will be taken to be the header / names of columns.</p> <p><code>ss</code> is a slice - the 0th column, taking all rows as denoted by <code>:</code></p> <p...
0
2016-06-01T16:14:12Z
[ "python", "csv" ]
Trying to copy column1 from a csv file to another empty file using python
37,573,805
<p>I'm looking for a way using python to copy the first column from a csv into an empty file. I'm trying to learn python so any help would be great!</p> <p>So if this is <code>test.csv</code></p> <pre><code>A 32 D 21 C 2 B 20 </code></pre> <p>I want this output</p> <pre><code>A D C B </code></pre> <p>I've tried th...
0
2016-06-01T16:10:01Z
37,574,048
<p>The best you can do is create a empty list and append the column and then write that new list into another csv for example:</p> <pre><code>import csv def writetocsv(l): #convert the set to the list b = list(l) print (b) with open("newfile.csv",'w',newline='',) as f: w = csv.writer(f, delimiter=',') ...
0
2016-06-01T16:23:29Z
[ "python", "csv" ]
Trying to copy column1 from a csv file to another empty file using python
37,573,805
<p>I'm looking for a way using python to copy the first column from a csv into an empty file. I'm trying to learn python so any help would be great!</p> <p>So if this is <code>test.csv</code></p> <pre><code>A 32 D 21 C 2 B 20 </code></pre> <p>I want this output</p> <pre><code>A D C B </code></pre> <p>I've tried th...
0
2016-06-01T16:10:01Z
37,574,093
<pre><code>import csv reader = csv.reader(open("test.csv","rb"), delimiter='\t') writer = csv.writer(open("output.csv","wb")) for e in reader: writer.writerow(e[0]) </code></pre>
0
2016-06-01T16:25:40Z
[ "python", "csv" ]
Trying to copy column1 from a csv file to another empty file using python
37,573,805
<p>I'm looking for a way using python to copy the first column from a csv into an empty file. I'm trying to learn python so any help would be great!</p> <p>So if this is <code>test.csv</code></p> <pre><code>A 32 D 21 C 2 B 20 </code></pre> <p>I want this output</p> <pre><code>A D C B </code></pre> <p>I've tried th...
0
2016-06-01T16:10:01Z
37,579,431
<p>First, you want to open your files. A good practice is to use the <code>with</code> statement (that, technically speaking, introduces a <em>context manager</em>) so that when your code exits from the <code>with</code> block all the files are automatically closed</p> <pre><code>with open('test.csv') as inpfile, ope...
1
2016-06-01T21:54:43Z
[ "python", "csv" ]
how to fill inside a region of an image in opencv python?
37,573,819
<p>I have found the boundaries of an image like this:</p> <p><img src="http://i.stack.imgur.com/t8aVw.png" alt=""></p> <p>Now I need to fill inside of the region (it is a breast tissue). Is there any functions in opencv or other modules in python like skimage through which I can do that?? something like maybe <code>i...
1
2016-06-01T16:11:04Z
37,582,204
<p>A simple floodfill will not work in this case. The image you have provided looks like one single contour but it has multiple holes in it. Before you can apply flood fill, I suggest you fill the holes in the line using spline curves. Once done you can apply <a href="http://docs.opencv.org/2.4/modules/imgproc/doc/misc...
0
2016-06-02T03:37:13Z
[ "python", "opencv", "image-processing" ]
Kivy: drag n drop, get file path
37,573,848
<p>In Kivy, I am trying to build an interface where the user can drag and drop a file into a widget (text input) and then my code would retrieve the file system path of that file (/path/to/users.file). That seems like a simpler approach than using the FileChooser widget, but how would I do it?</p> <p>Thanks!</p>
3
2016-06-01T16:12:43Z
38,854,461
<p>Use <a href="https://kivy.org/docs/api-kivy.core.window.html#kivy.core.window.WindowBase.on_dropfile" rel="nofollow"><code>on_dropfile</code></a> event handler. Here is an working example:</p> <pre><code>from kivy.app import App from kivy.core.window import Window class WindowFileDropExampleApp(App): def buil...
0
2016-08-09T15:10:15Z
[ "python", "kivy" ]
opencv python copy mask region (black or white pixels) onto a BGR image region
37,573,856
<p>In OpenCV python, say we read an image with cv2.imread and get a BGR numpy array. We next generate a mask with the cv2.inRange command. The mask has the same width/height and each mask pixel is either black or white.</p> <p>I want to copy a region from the mask (taken as an image of black and white pixels) onto a r...
2
2016-06-01T16:13:20Z
37,575,218
<p>If you try to do it with a single channel (grayscale) mask directly, the shapes of the array slices will not be the same, and the operation will fail.</p> <pre><code>&gt;&gt;&gt; img[10:20,10:20] = mask[10:20,10:20] ValueError: could not broadcast input array from shape (10,10) into shape (10,10,3) </code></pre> ...
0
2016-06-01T17:29:06Z
[ "python", "opencv" ]
How to get a .Rect to follow another based on the x,y x direction and y direction on the one in front?
37,573,871
<p>I've been working on a snake code for quite a while now. It is still rather primitive and very very basic. I have gotten the collisions to work, food generation and very basic movement. What I'm struggling on is figuring out the movement. Whenever you press WASD or the Arrow Keys it would move the head, and the "bod...
1
2016-06-01T16:14:25Z
37,576,007
<p>The body blocks don't need to know the direction. You can just append a new head block (with the next x, y coords) to the list and remove the last block. </p> <p>You could also use a <code>collections.deque</code>, pronounced "deck", a double ended queue which allows fast appends and pops on either end (although ef...
2
2016-06-01T18:16:03Z
[ "python", "pygame" ]
Error gotten in integising strings in .split() list
37,573,988
<p>Im starting to learn python can someone pls tell me how to OK this nosetest:</p> <pre><code>from nose.tools import * from lexicon.lexicon import lexicon def test_directions(): assert_equal(lexicon.scan("north"), [('direction', 'north')]) result = lexicon.scan("north south east") ass...
-1
2016-06-01T16:19:58Z
37,575,762
<p>This code:</p> <pre><code>try: x = something_that_raises_an_error() except: return y </code></pre> <p>does not set <code>x = y</code>. It simply performs the statement inside the <code>except</code> block, so it returns <code>y</code>.</p> <p>When you run <code>scan("north")</code> and it goes into the <c...
0
2016-06-01T18:00:11Z
[ "python", "try-catch", "nose" ]
Error gotten in integising strings in .split() list
37,573,988
<p>Im starting to learn python can someone pls tell me how to OK this nosetest:</p> <pre><code>from nose.tools import * from lexicon.lexicon import lexicon def test_directions(): assert_equal(lexicon.scan("north"), [('direction', 'north')]) result = lexicon.scan("north south east") ass...
-1
2016-06-01T16:19:58Z
37,644,353
<p>This is a complete solution to the problem</p> <pre><code>directions =['north','south','east','east','down','up','left','right','back','front'] numbers = xrange(999999999) class lexicon: @staticmethod def scan(d): list2=d.split() list1=[] list3=[] try: for x in d....
0
2016-06-05T16:43:59Z
[ "python", "try-catch", "nose" ]
Tensorflow memory management -- chunking?
37,573,996
<p>I have a problem computing a reduction of a function of a network represented by a large (200000x200000) matrix generated as a distance matrix between pairs of points.</p> <p>Minimal example, input X a 200000x2 numpy array of cartesian coordinates:</p> <pre><code>x = tf.constant(X[:,0], shape=[X.shape[0],1]) y = t...
0
2016-06-01T16:20:24Z
37,575,708
<p>What's really needed here (but not yet implemented) is cwise fusion. What's happening right now is that <code>2*sqrt(a+b)</code> will allocate new Tensor for <code>a+b</code>, then new tensor for <code>sqrt</code> and then another one for <code>2*sqrt</code>. PS, you can dig where the memory is going by examining me...
1
2016-06-01T17:56:59Z
[ "python", "memory", "tensorflow" ]
django 'User' object has no attribute 'user'
37,573,999
<p>In my model I have a class</p> <pre><code>class User(AbstractDateTime, AbstractBaseUser, PermissionsMixin, models.Model): email = models.EmailField(max_length=255, unique=True,blank=False,default='') first_name = models.CharField(max_length=255, blank=False,default='') last_name = models.CharField(max_...
0
2016-06-01T16:20:28Z
37,574,076
<p>Your function <code>last_seen</code> has a bug. You were doing <code>self.user.email</code> which is incorrect, it should be <code>self.email</code>.</p> <p>Also, it's not good practice to do <code>User.objects.filter()</code>, because <code>filter</code> is used for doing lookup with conditions like sql <code>WHER...
6
2016-06-01T16:24:45Z
[ "python", "django" ]
Get nested LDAP group members with python-ldap
37,574,007
<p>I'm trying to find the best way to get a list of all LDAP user accounts that belong to groups which are members of a groupOfNames using python-ldap. This is on an OpenLDAP server, not AD. I wrote the function below, which does the job but takes forever to run. I'm hoping either python-ldap has some builtin functi...
0
2016-06-01T16:20:56Z
38,109,197
<p>I realized that running ldapsearch repeatedly was the limiting factor, so I made a new version which builds a dictionary of ALL group and groupOfNames records first. It takes up a bit more memory than the old solution, but is less taxing on the LDAP server and runs significantly faster (down from ~15 minutes to &lt...
0
2016-06-29T20:11:26Z
[ "python", "optimization", "ldap", "openldap", "python-ldap" ]
Best way to execute 'ls' shell command with multiple arguments?
37,574,255
<p>I have the following command that I want to execute in Python and store in a variable:</p> <pre><code>ls -1 var1 2&gt;/dev/null | grep var2 | grep var3 | head -n 1 </code></pre> <p>But I can't get it to work. I tried using subprocess (both 'call' and 'check_output' as well as 'os.system' and nothing worked.. It al...
0
2016-06-01T16:34:47Z
37,574,350
<p>I don't have any problem when using <code>subprocess</code> :</p> <pre><code>&gt;&gt;&gt; import subprocess &gt;&gt;&gt; sub = subprocess.Popen("ls -1 var1 2&gt;/dev/null | grep var2 | grep var3 | head -n 1", shell=True, stdout=subprocess.PIPE) &gt;&gt;&gt; str = sub.stdout.read() &gt;&gt;&gt; str '' </code></pre> ...
1
2016-06-01T16:41:13Z
[ "python", "shell" ]
Best way to execute 'ls' shell command with multiple arguments?
37,574,255
<p>I have the following command that I want to execute in Python and store in a variable:</p> <pre><code>ls -1 var1 2&gt;/dev/null | grep var2 | grep var3 | head -n 1 </code></pre> <p>But I can't get it to work. I tried using subprocess (both 'call' and 'check_output' as well as 'os.system' and nothing worked.. It al...
0
2016-06-01T16:34:47Z
37,574,361
<p>You need to ensure you are executing in a shell, as you are relying on the shell to dispatch the pipes, e.g. (Py>3.1):</p> <pre><code>import subprocess var1, var2, var3 = "var1", "var2", "var3" cmd = "ls -1 {} 2&gt;/dev/null | grep {} | grep {} | head -n 1".format(var1, var2, var3) result = subprocess.check_output(...
-1
2016-06-01T16:41:33Z
[ "python", "shell" ]
Best way to execute 'ls' shell command with multiple arguments?
37,574,255
<p>I have the following command that I want to execute in Python and store in a variable:</p> <pre><code>ls -1 var1 2&gt;/dev/null | grep var2 | grep var3 | head -n 1 </code></pre> <p>But I can't get it to work. I tried using subprocess (both 'call' and 'check_output' as well as 'os.system' and nothing worked.. It al...
0
2016-06-01T16:34:47Z
37,574,645
<p>For executing shell commands you'd use the subprocess module.</p> <p>Usage and examples can be found at: <a href="https://docs.python.org/2/library/subprocess.html" rel="nofollow">Python Docs: subprocess</a></p> <p>The actual python code for calling bash would look like this</p> <pre><code>import subprocess task ...
3
2016-06-01T16:55:37Z
[ "python", "shell" ]
How to calculate matrix product on (sparse) bit matrix efficiently in python
37,574,424
<p>Ordinary matrix product between bit array:</p> <pre><code> 1, 0, 0 Matrix A = 1, 1, 1 0, 0, 1 1, 1, 0 Transpose of A = 0, 1, 0 0, 1, 1 C = Matrix A times (Transpose of Matrix A) 1, 1, 0 C = 1, 3, 1 0, 1, 1 </code></pre> <p>A is a bit array of 1 and ...
2
2016-06-01T16:44:36Z
37,587,383
<p>Existing performance libraries such as MKL always use float/double as the data type. Comparing to converting your A to a float CSR and then calling <code>.dot()</code> or some MKL routines, you may find writing your own <code>bit-mat-mul</code> code is faster. You don't even need the multiply operation. It is only c...
2
2016-06-02T09:08:53Z
[ "python", "scipy", "bit-manipulation", "intel-mkl" ]
I don't know what is happening with python zlib
37,574,643
<pre><code>comp = z.compress("iasdfhuisahfiiunajsdfijniunadinfianlisdnf", 1) z.decompress(comp, 1) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; zlib.error: Error -2 while preparing to decompress data: inconsistent stream state </code></pre> <p>It seem to be a zlib bug, but I wan...
-3
2016-06-01T16:55:31Z
37,574,871
<p><code>zlib.decompress</code> does not take a compression level parameter. The optional second parameter means <a href="https://docs.python.org/2/library/zlib.html#zlib.decompress" rel="nofollow">something completely different</a>.</p> <pre><code>zlib.decompress(comp) </code></pre>
1
2016-06-01T17:07:01Z
[ "python", "zlib" ]
I don't know what is happening with python zlib
37,574,643
<pre><code>comp = z.compress("iasdfhuisahfiiunajsdfijniunadinfianlisdnf", 1) z.decompress(comp, 1) Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; zlib.error: Error -2 while preparing to decompress data: inconsistent stream state </code></pre> <p>It seem to be a zlib bug, but I wan...
-3
2016-06-01T16:55:31Z
37,574,928
<p>Be careful, the "1" in <code>z.compress("iasdfhuisahfiiunajsdfijniunadinfianlisdnf", 1)</code> is not the same as the "1" in <code>z.decompress(comp, 1)</code>.</p> <p>Indeed the first one is the compression level, (from 0 to 9), whereas the second one is the window size, which you can omit.</p> <p>Hence, you can ...
3
2016-06-01T17:10:15Z
[ "python", "zlib" ]
Can't write Unicode text using cx_Oracle
37,574,647
<p>I'm working on a Python script that reads in a CSV writes the contents out to an Oracle database using cx_Oracle. So far I've been getting the following error:</p> <pre><code>UnicodeEncodeError: 'ascii' codec can't encode character '\xa0' in position 1369: ordinal not in range(128) </code></pre> <p>Evidently, cx_O...
0
2016-06-01T16:55:41Z
37,600,367
<p>Check the value of the "encoding" and "nencoding" attributes on the connection. This value is set by calling OCI routines that check the environment variables NLS_LANG and NLS_NCHAR. It looks like this value is US-ASCII or equivalent. When writing to the database, cx_Oracle takes the text and gets a byte string by e...
1
2016-06-02T19:15:51Z
[ "python", "oracle", "unicode", "utf-8", "cx-oracle" ]
Forcing a colormap to be square
37,574,734
<p>I am working on Python with the <code>matplotlib</code> library and I have a problem with color maps dimension.</p> <p>I have some target variable <code>target</code> that depends on two variables <code>x</code> and <code>y</code> - i.e. my data <code>target</code> is a matrix with the variable <code>x</code> being...
0
2016-06-01T17:00:12Z
37,575,083
<p>What's your <code>matplotlib</code> version? If it's newer than <code>1.1.0</code> then you can try this:</p> <pre><code>fig = plt.figure() ax = fig.add_subplot(111) ax.imshow(np.random.rand(32, 64), cmap='rainbow', aspect=2) plt.show() </code></pre> <p><a href="http://i.stack.imgur.com/OPSjY.png" rel="nofollow"><...
1
2016-06-01T17:19:53Z
[ "python", "matplotlib", "colormap" ]
Create labledpoints from Spark Dataframe & how to pass list of names to VectorAssembler
37,574,833
<p>I have a further questions from here <a href="http://stackoverflow.com/a/32557330/5235052">http://stackoverflow.com/a/32557330/5235052</a> I am trying to build labledPoints from a dataframe, where I have the features and label in columns. The features are all boolean with 1/0. </p> <p>Here is a sample row from the ...
1
2016-06-01T17:05:44Z
37,575,054
<p>There is nothing wrong here. What you get is a string representation of the <code>SparseVector</code> which exactly reflects your input:</p> <ul> <li>you take first five columns (<code>assembler.setInputCols(df_columns[0:5])</code>) and the output vector is of length 5</li> <li>since first columns of example input ...
3
2016-06-01T17:18:03Z
[ "python", "apache-spark", "spark-dataframe" ]
How to exctract a part of a url in this case?
37,574,904
<p>So I need a way to extract file names from public dropbox urls, without using the API, I've concluded that all sharing links in Dropbox are made like this : </p> <pre><code>dropbox.com/s/{random alphanemucric string}/{file name} </code></pre> <p>For example I have this link : </p> <pre><code>https://www.dropbox.c...
2
2016-06-01T17:08:22Z
37,575,026
<p>Use <a href="https://docs.python.org/2/library/urlparse.html#urlparse.urlsplit" rel="nofollow"><code>urlparse.urlsplit</code></a>,</p> <pre><code>import os import urlparse url = 'https://www.dropbox.com/s/sbyuft7zscqzgbs/checklist%281%29.pdf?dl=0' path = urlparse.urlsplit(url).path # /s/sbyuft7zscqzgbs/checklis...
2
2016-06-01T17:16:14Z
[ "python", "regex", "string" ]
How to exctract a part of a url in this case?
37,574,904
<p>So I need a way to extract file names from public dropbox urls, without using the API, I've concluded that all sharing links in Dropbox are made like this : </p> <pre><code>dropbox.com/s/{random alphanemucric string}/{file name} </code></pre> <p>For example I have this link : </p> <pre><code>https://www.dropbox.c...
2
2016-06-01T17:08:22Z
37,575,067
<p>You can do the following :</p> <pre><code>&gt;&gt;&gt; name = 'https://www.dropbox.com/s/sbyuft7zscqzgbs/checklist%281%29.pdf?dl=0' &gt;&gt;&gt; name.split('/')[-1].split('?')[0] 'checklist%281%29.pdf' </code></pre> <p>The <code>split("/")[-1]</code> takes everything after the last slash, and the <code>split('?')[...
1
2016-06-01T17:18:43Z
[ "python", "regex", "string" ]
Creating and manipulating dataframes with only binary values
37,574,935
<p>Given the following dataframe:</p> <pre><code>df = pd.DataFrame({'s1':[1,2,3,4], 's2':[4,3,2,1], 's3':[7,4,3,1], 's4':[9,4,3,1]}) </code></pre> <p>I want to do the following:</p> <ol> <li><p>Map a predicate <code>&gt;2</code> over <code>['s1', 's2']</code>, map a predicate <code>&gt;4</code> over <code>['s3', 's4...
0
2016-06-01T17:10:47Z
37,576,162
<p><strong>Items 1 and 2</strong></p> <p>To map the predicate, use the <code>gt</code> function. Then use <code>any</code> to select rows that have at least one <code>True</code> value (i.e. exclude rows that are all <code>False</code>).</p> <p>You can use <code>astype(int)</code> when applying the predicate, but it...
1
2016-06-01T18:25:18Z
[ "python", "pandas", "dataframe" ]
Adding sheet2 to existing excelfile from data of sheet1 with pandas python
37,575,008
<p>I am fetching data from web into an excel sheet using pandas &amp; able to save it to sheet 1, now i want to fetch a column data into sheet 2 of same excel.</p> <p>When I am executing the code it still doesn't create a new sheet in the excelfile, just overwrites the existing sheet with new name &amp; desired data.<...
1
2016-06-01T17:15:00Z
37,575,208
<p>You can use <code>openpyxl</code>, the library <code>pandas</code> uses for <code>xlsx</code>, to achieve this:</p> <pre><code>import pandas as pd from openpyxl import load_workbook book = load_workbook('Abc.xlsx') writer = pd.ExcelWriter('Abc.xlsx', engine='openpyxl') writer.book = book writer.sheets = dict((ws....
0
2016-06-01T17:28:22Z
[ "python", "excel", "pandas" ]
How do you create a dictionary from nested lists in Python?
37,575,070
<p>I was hoping that there might be someway to use a comprehension to do this, but say I have data that looks like this:</p> <pre><code>data = [['a', 'b', 'c'], [1, 2, 3], [4, 5, 6]] </code></pre> <p>My ultimate goal is to create a dictionary where the first nested list holds the keys and the remaining lists hold the...
1
2016-06-01T17:19:01Z
37,575,133
<p>You can use zip in a dict comprehension:</p> <pre><code>{z[0]: list(z[1:3]) for z in zip(*data)} Out[16]: {'a': [1, 4], 'b': [2, 5], 'c': [3, 6]} </code></pre> <h2>How it works:</h2> <p>zip will take the <em>transpose</em>:</p> <pre><code>list(zip(['a', 'b', 'c'], [1, 2, 3], [4, 5, 6])) Out[19]: [('a', 1, 4), ('...
4
2016-06-01T17:23:02Z
[ "python", "python-3.x", "dictionary-comprehension" ]
"LIST object not callable ERROR
37,575,072
<p><a href="http://i.stack.imgur.com/jOSgE.png" rel="nofollow"><img src="http://i.stack.imgur.com/jOSgE.png" alt="enter image description here"></a></p> <p>Help me to rectify my code why this error occurs:</p> <blockquote> <p>"TypeError: 'list' object is not callable"</p> </blockquote>
-1
2016-06-01T17:19:03Z
37,575,094
<p><code>key</code> is meant to be a callable (typically a function). You have provided something in square brackets, which is a list. A list is not callable.</p> <p>Try:</p> <pre><code>min(input, key=find_count_vowel) </code></pre> <p><code>find_count_vowel</code> is a function so that's all you're meant to pass. D...
0
2016-06-01T17:20:48Z
[ "python", "python-2.7", "exception", "pycharm", "typeerror" ]
Appending multiple variables to CSV file
37,575,075
<p>This may sound like a question I already asked, but I have a Python code where I am running the text/html file through a tone analyzer and generating the output to a CSV file. The problem I am facing is that I need to write two variables from the output 'Tone_name' and store them as two columns of the same CSV file....
0
2016-06-01T17:19:11Z
37,575,315
<pre><code>rows = [] for tone in cat['tones']: rows.append((tone['tone_name'],tone['score'])) ... for row in rows: writer.writerow(row) </code></pre> <p>Or more concisely:</p> <pre><code>writer.writerows((tone['tone_name'],tone['score']) for tone in cat['tones']) </code></pre>
0
2016-06-01T17:34:47Z
[ "python", "csv" ]
Disable Template Cache Jinja2
37,575,089
<p>I'm trying to disable Jinja2's template cache. I've done some looking around, and I've found that there's a <code>cache_size</code> parameter for jinja's environment. I'm using the following: </p> <pre><code>app.jinja_env = jinja2.Environment( cache_size = 0, loader = jinja2.FunctionLoader(utils.load_templ...
5
2016-06-01T17:20:20Z
38,328,911
<p>You might want to set <code>app.config['TEMPLATES_AUTO_RELOAD'] = True</code> instead. Instead of disabling the cache, it will reload templates if the cached version no longer matches the template file.</p>
2
2016-07-12T12:28:22Z
[ "python", "flask", "jinja2" ]
No output from Process using multiprocessing
37,575,120
<p>I am a beginner in multiprocessing, can anyone tell me why this does not produce any output?</p> <pre><code>import multiprocessing def worker(num): """thread worker function""" print('Worker:', num) if __name__ == '__main__': jobs = [] for i in range(4): p = multiprocessing.Process(targe...
2
2016-06-01T17:22:19Z
37,575,220
<p>You probably need to flush the output. You can use <code>sys.stdout.flush()</code>:</p> <pre><code>import multiprocessing import sys def worker(num): """thread worker function""" print('Worker:', num) sys.stdout.flush() return if __name__ == '__main__': jobs = [] for i in range(4): ...
0
2016-06-01T17:29:12Z
[ "python", "python-3.x", "multiprocessing", "python-idle", "python-multiprocessing" ]
No output from Process using multiprocessing
37,575,120
<p>I am a beginner in multiprocessing, can anyone tell me why this does not produce any output?</p> <pre><code>import multiprocessing def worker(num): """thread worker function""" print('Worker:', num) if __name__ == '__main__': jobs = [] for i in range(4): p = multiprocessing.Process(targe...
2
2016-06-01T17:22:19Z
37,575,493
<p>You're starting your <code>Process()</code>, but never waiting on it to complete, so your program's execution ends before the background process finishes. Try this, with a call to <a href="https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Process.join" rel="nofollow"><code>Process.join()</code><...
1
2016-06-01T17:44:04Z
[ "python", "python-3.x", "multiprocessing", "python-idle", "python-multiprocessing" ]
How to insert two arguments in list Python
37,575,130
<p>I have</p> <pre><code>dollar_list = [] with open('fix/dollar.csv', 'r') as f: r = csv.DictReader(f) for dct in r: d = dct['date'] # Convert '%d/%m/%Y' to '%Y-%m-%d'. d = datetime.datetime.strptime(d, '%d/%m/%Y').strftime('%Y-%m-%d') dollar_list.append(d, dct['value']) # &lt;...
0
2016-06-01T17:22:43Z
37,575,158
<p>I guess maybe you want </p> <pre><code>dollar_list.extend([d, dct['value']]) # &lt;- here #list looks like [A1,A2,B1,B2,C1,C2,...] </code></pre> <p>or </p> <pre><code>dollar_list.append([d, dct['value']]) # &lt;- here #list looks like [[1,2],[3,4],..] </code></pre>
2
2016-06-01T17:24:59Z
[ "python", "list" ]
How to insert two arguments in list Python
37,575,130
<p>I have</p> <pre><code>dollar_list = [] with open('fix/dollar.csv', 'r') as f: r = csv.DictReader(f) for dct in r: d = dct['date'] # Convert '%d/%m/%Y' to '%Y-%m-%d'. d = datetime.datetime.strptime(d, '%d/%m/%Y').strftime('%Y-%m-%d') dollar_list.append(d, dct['value']) # &lt;...
0
2016-06-01T17:22:43Z
37,575,343
<p>I do not think extending is the right way, as an ordered pair of a date and a value shall be inserted into a list.</p> <p><strong>Proposal</strong> based on a tuple to represent the ordered (date, value) pairs:</p> <pre><code>#! /usr/bin/env python from __future__ import print_function import csv import datetime a...
1
2016-06-01T17:36:33Z
[ "python", "list" ]
Business days between two columns of dates with Pandas Groupby
37,575,192
<p>I have a <code>Dataframe</code> in <code>Pandas</code> with a letter and two dates as columns. I would like to calculate the difference between the two date columns for the previous row using <code>shift(1)</code> provided that the <code>Letter</code>value is the same (using a <code>groupby</code>). The complex part...
0
2016-06-01T17:27:31Z
37,575,829
<p>The following should work - first removing the leading zeros from the date digits):</p> <pre><code>df = pd.DataFrame(data=[['A', datetime(2016, 1, 7), datetime(2016, 1, 9)], ['A', datetime(2016, 3, 1), datetime(2016, 3, 8)], ['B', datetime(2016, 5, 1), datetime(2016, ...
1
2016-06-01T18:04:30Z
[ "python", "python-2.7", "numpy", "pandas" ]
how to fully use value_count function in python
37,575,197
<p>Using Python value_count() in order to figure out frequent occurrences of words in a column. There's a lot of words and the function is only showing the most and the least frequent occurrences. How do I make the it show the entire list of counts of values so I can see what's not showing? </p>
0
2016-06-01T17:27:42Z
37,576,204
<p>I guess you're talking about <code>pd.options.display.max_rows</code> default option...</p> <p>Just do the following:</p> <pre><code>pd.options.display.max_rows = 10000 </code></pre> <p>and run <code>value_counts()</code> again:</p> <pre><code>df['column'].value_counts() </code></pre>
0
2016-06-01T18:27:23Z
[ "python", "pandas" ]
django.utils.datastructures.MultiValueDictKeyError with form post data
37,575,241
<p><code>django.utils.datastructures.MultiValueDictKeyError: "'user_data'"</code></p> <p>Is what i get when trying to access user_data from the request.POST</p> <pre><code>post_data = dict(request.POST) print(post_items) </code></pre> <p>returns</p> <pre><code>{'user_data[first_name]': ['Jamie'], 'user_data[name_la...
0
2016-06-01T17:30:45Z
37,575,296
<p>Your <code>POST</code> data is really weird but for the sake of correctness, you should do:</p> <pre><code>first_name = post_data["user_data[first_name]"] name_last = post_data["user_data[name_last]"] </code></pre> <p>Because the string <code>user_data[first_name]</code> is the key for the dict not just string <co...
1
2016-06-01T17:33:53Z
[ "python", "django" ]
What Arguments to use while doing a KS test in python with student's t distribution?
37,575,270
<p>I have data regarding metallicity in stars, I want to compare it with a student's t distribution. To do this I am running a Kolmogorov-Smirnov test using scipy.stats.kstest on python <code>KSstudentst = scipy.stats.kstest(data,"t",args=(a,b))</code> But I am unable to find what the arguments are supposed to be. ...
0
2016-06-01T17:32:35Z
37,575,713
<p>Those seem like the arguments for <a href="http://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.stats.t.html" rel="nofollow"><code>scipy.stats.t.cdf</code></a>: <code>(df, loc=0, scale=1)</code> for standard t. Since they have default values, you need to pass a tuple but it can be a singleton (<code>args...
0
2016-06-01T17:57:19Z
[ "python", "scipy", "kolmogorov-smirnov" ]
What Arguments to use while doing a KS test in python with student's t distribution?
37,575,270
<p>I have data regarding metallicity in stars, I want to compare it with a student's t distribution. To do this I am running a Kolmogorov-Smirnov test using scipy.stats.kstest on python <code>KSstudentst = scipy.stats.kstest(data,"t",args=(a,b))</code> But I am unable to find what the arguments are supposed to be. ...
0
2016-06-01T17:32:35Z
37,575,927
<p>The args argument must be a tuple but it can be a single variable. You can do your test using <code>ks_statistic, pvalue = scipy.stats.kstest(x, 't', (10,))</code> if 10 is the degrees of freedom.</p>
0
2016-06-01T18:10:54Z
[ "python", "scipy", "kolmogorov-smirnov" ]