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 |
---|---|---|---|---|---|---|---|---|---|
Process a LOT of data | 39,800,838 | <p>So I'm working with parametric energy simulations and ended up with 500GB+ of data stored in .CSV files. I need to be able to process all this data to compare the results and gain insights of the influence of different parameters. </p>
<p>Each csv file name contains information of the parameters used for the simulation so I can not merge the files. </p>
<p>I normally loaded the .csv files to python using pandas and defining a Class. but now (with all this data) there is not enough memory to do this. </p>
<p>Can you point me out a way to process this data? I need to be able to do plots and compare the csv files. </p>
<p>Thank you for your time. </p>
| 0 | 2016-09-30T22:16:06Z | 39,800,978 | <p><a href="http://stackoverflow.com/questions/27203161/convert-large-csv-to-hdf5">Convert</a> the csv files to <a href="https://www.hdfgroup.org/hdf5/" rel="nofollow">hdf5</a>, which was created to deal with massive and complex datasets. It works with <a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-hdf5" rel="nofollow">pandas</a> as well as <a href="http://www.pytables.org/FAQ.html" rel="nofollow">other</a> <a href="http://www.h5py.org/" rel="nofollow">libraries</a>.</p>
| 0 | 2016-09-30T22:29:47Z | [
"python",
"csv",
"dataframe",
"bigdata"
]
|
Program does not loop | 39,800,985 | <p>I'm curious as to why this program is not looping. The program will run once but when another game is played it doesn't record the winner and quits.</p>
<p>Any assistance will be greatly appreciated!</p>
<p>Here is the Python program:</p>
<pre><code>import random
random.seed()
print ("For each round please select from the following warriors: ")
print ("'C' or 'c' for Cowboy")
print ("'N' or 'n' for Ninja")
print ("'B' or 'b' for Bear")
print ("'Q' or 'q' for quit")
print()
gamesPlayed = 0
print ("Round", gamesPlayed +1, ":")
warriorStr = input("Please choose a warrior: ")
warriorStr = warriorStr.lower()
while not warriorStr.isalpha():
print()
print ("That's not a valid choice!")
warriorStr = input("Please enter a weapon: ")
computer = random.choice("cnb")
count = 0
winCount = 0
lossCount = 0
tieCount = 0
if warriorStr == "n" or "N" and computer == "c" or "C":
winCount = winCount + 1
print ("You win")
elif warriorStr == "c" or "C" and computer == "b" or "B":
winCount = winCount + 1
print ("You win")
elif warriorStr == "b" or "B" and computer == "n" or "N":
winCount = winCount + 1
print ("You win")
elif warriorStr == "c" and computer == "n":
lossCount = lossCount + 1
print ("Computer wins")
elif warriorStr == "b" and computer == "c":
lossCount = lossCount + 1
print ("Computer wins")
elif warriorStr == "n" and computer == "b":
lossCount = lossCount + 1
print ("Computer wins")
elif warriorStr == "c" and computer == "c":
tieCount = tieCount + 1
print ("You tied")
elif warriorStr == "n" and computer == "n":
tieCount = tieCount + 1
print ("You tied")
elif warriorStr == "b" and computer == "b":
tieCount = tieCount + 1
print ("You tied")
gamesPlayed = gamesPlayed + 1
print()
print ("Round", gamesPlayed +1, ":")
warriorStr = input("Choose a warrior: ")
if warriorStr == "q" and "Q":
print("Game Over!")
print ("You have played a total of", gamesPlayed, "games.")
print ("You won", winCount, "times")
print ("The computer won", lossCount, "times")
print ("You tied", tieCount, "times")
</code></pre>
| 0 | 2016-09-30T22:30:30Z | 39,801,308 | <p>Wrap the whole thing in a while loop.
Try something <em>like</em> this:</p>
<pre><code>warriorStr = input("Please choose a warrior: ")
warriorStr = warriorStr.lower()
acceptables = ['a','c','n','q']
while warriorStr not 'q' and warriorStr in acceptables:
warriorStr = input("Please enter a weapon: ")
computer = random.choice("cnb")
count = 0
winCount = 0
lossCount = 0
tieCount = 0
if warriorStr == "n" or "N" and computer == "c" or "C":
winCount = winCount + 1
print ("You win")
elif warriorStr == "c" or "C" and computer == "b" or "B":
winCount = winCount + 1
print ("You win")
elif warriorStr == "b" or "B" and computer == "n" or "N":
winCount = winCount + 1
print ("You win")
elif warriorStr == "c" and computer == "n":
lossCount = lossCount + 1
print ("Computer wins")
elif warriorStr == "b" and computer == "c":
lossCount = lossCount + 1
print ("Computer wins")
elif warriorStr == "n" and computer == "b":
lossCount = lossCount + 1
print ("Computer wins")
elif warriorStr == "c" and computer == "c":
tieCount = tieCount + 1
print ("You tied")
elif warriorStr == "n" and computer == "n":
tieCount = tieCount + 1
print ("You tied")
elif warriorStr == "b" and computer == "b":
tieCount = tieCount + 1
print ("You tied")
gamesPlayed = gamesPlayed + 1
print()
print ("Round", gamesPlayed +1, ":")
warriorStr = input("Choose a warrior: ")
print("Game Over!")
print ("You have played a total of", gamesPlayed, "games.")
print ("You won", winCount, "times")
print ("The computer won", lossCount, "times")
print ("You tied", tieCount, "times")
</code></pre>
| 0 | 2016-09-30T23:10:01Z | [
"python",
"loops"
]
|
Convert an Object dtype column to Number Dtype in a datafrane Pandas | 39,800,997 | <p>Trying to answer this question <a href="http://stackoverflow.com/questions/39647978/get-list-of-unique-string-values-per-column-in-a-dataframe-using-python">Get List of Unique String per Column</a> we ran into a different problem from my dataset. When I import this CSV file to the dataframe every column is OBJECT type, we need to convert the columns that are just number to real (number) dtype and those that are not number to String dtype.</p>
<p>Is there a way to achieve this?</p>
<p><a href="https://www.dropbox.com/s/thtxso04c1y13xl/HistorianDataSample.zip?dl=0" rel="nofollow">Download the data sample from here</a></p>
<p>I have tried following code from following article <a href="http://stackoverflow.com/questions/15891038/pandas-change-data-type-of-columns">Pandas: change data type of columns</a> but did not work.</p>
<pre><code>df = pd.DataFrame(a, columns=['col1','col2','col3'])
</code></pre>
<p>As always thanks for your help</p>
| 2 | 2016-09-30T22:32:39Z | 39,801,222 | <p><strong><em>Option 1</em></strong><br>
use <code>pd.to_numeric</code> in an <code>apply</code></p>
<pre><code>df.apply(pd.to_numeric, errors='ignore')
</code></pre>
<p><strong><em>Option 2</em></strong><br>
use <code>pd.to_numeric</code> on <code>df.values.ravel</code></p>
<pre><code>cvrtd = pd.to_numeric(df.values.ravel(), errors='coerce').reshape(-1, len(df.columns))
pd.DataFrame(np.where(np.isnan(cvrtd), df.values, cvrtd), df.index, df.columns)
</code></pre>
<hr>
<p><strong><em>Note</em></strong><br>
These are not exactly the same. For some column that contains mixed values, option 2 converts what it can while option 2 leaves everything in that column an object. Looking at your file, I'd choose option 1.</p>
<hr>
<p><strong><em>Timing</em></strong> </p>
<pre><code>df = pd.read_csv('HistorianDataSample/HistorianDataSample.csv', skiprows=[1, 2])
</code></pre>
<p><a href="http://i.stack.imgur.com/zfCBE.png" rel="nofollow"><img src="http://i.stack.imgur.com/zfCBE.png" alt="enter image description here"></a></p>
| 1 | 2016-09-30T22:59:20Z | [
"python",
"pandas"
]
|
read CSV file and validate column which on the basis of UTF-8 character | 39,801,014 | <p>I have to read a CSV file which is containing columns (PersonName, age, address) and I have to validate the the PersonName.
"PersonName may only contain UTF-8 characters."</p>
<p>I am using python3.x so cant use decode method after opening the file.</p>
<p>Please tell me how to open and read the file so that PersonName who is not containing any UTF-8 character can be ignored and I can move to next line for validation.</p>
| 0 | 2016-09-30T22:33:47Z | 39,801,097 | <p>Assuming the rest of the file requires no checking or is UTF-8 legal (which includes ASCII data), you can <code>open</code> the file with <code>encoding='utf-8'</code> and <code>errors='replace'</code>. This will change any invalid bytes (in UTF-8 encoding) into the Unicode replacement character, <code>\ufffd</code>. Alternatively, to preserve the data, you can use <code>'surrogateescape'</code> as the <code>errors</code> handler, which uses private use Unicode codes to represent the original value in a way that can be undone later. You can then check for those as you go:</p>
<pre><code>with open(csvname, encoding='utf-8', errors='replace', newline='') as f:
for PersonName, age, address in csv.reader(f):
if '\ufffd' in PersonName:
continue
... PersonName was decoded without errors, so process the row ...
</code></pre>
<p>Or with <code>surrogateescape</code>, you can ensure any non-UTF-8 data (if that's "possible") in the other fields is restored on write:</p>
<pre><code>with open(incsvname, encoding='utf-8', errors='surrogateescape', newline='') as inf,\
open(outcsvname, 'w', encoding='utf-8', errors='surrogateescape', newline='') as outf:
csvout = csv.writer(outf)
for PersonName, age, address in csv.reader(f):
try:
# Check for surrogate escapes, and reject PersonNames containing them
# Most efficient way to do so is a test encode; surrogates will fail
# to encode with default error handler
PersonName.encode('utf-8')
except UnicodeEncodeError:
continue # Had non-UTF-8, skip this row
... PersonName was decoded without surrogate escapes, so process the row ...
# You can recover the original file bytes in your code for a field with:
# fieldname.encode('utf-8', errors='surrogateescape')
# Or if you're just passing data to a new file, write the same strings
# back to a file opened with the same encoding/errors handling; the surrogates
# will be restored to their original values:
csvout.writerow([PersonName, age, address])
</code></pre>
| 0 | 2016-09-30T22:43:34Z | [
"python",
"python-3.x",
"csv",
"unicode",
"utf-8"
]
|
Why does my text clustering do this | 39,801,020 | <p>I have an unlabeled dataset with product names. For example, baseball shirt, bomber jacket, active classic boxer, etc. </p>
<p>I created a tf-idf matrix with the data then I ran k-means on the matrix. I plotted a within-cluster sum of squares to find the best k which is 5. </p>
<p>After clustering I figured out the cosine similarity between documents</p>
<pre><code># cosine similarity between each document
from sklearn.metrics.pairwise import cosine_similarity
dist = 1.0 - cosine_similarity(tfidf_matrix)
print dist
</code></pre>
<p>Then I used MDS on dist to reduce it to 2 dimensions so I can plot the clusters</p>
<pre><code>from sklearn.manifold import MDS
mds = MDS(n_components=2, dissimilarity="precomputed", random_state=1)
xs, ys = pos[:, 0], pos[:, 1]
</code></pre>
<p>The cluster plot looks pretty good except for the circumference. Is there a reason why it is doing this? The rest of the clusters seem like they are clustering around a similar area.</p>
<p><a href="http://i.stack.imgur.com/qD1MX.png" rel="nofollow"><img src="http://i.stack.imgur.com/qD1MX.png" alt="enter image description here"></a></p>
| 2 | 2016-09-30T22:34:30Z | 39,806,909 | <p>TF-IDF only works for <strong>long text</strong>.</p>
<p>Because of this, almost every document is completely different from every other, and they "fan out" like this.</p>
<p>I doubt that k-means worked either.</p>
| 2 | 2016-10-01T13:00:27Z | [
"python",
"scikit-learn",
"cluster-analysis",
"k-means",
"tf-idf"
]
|
Can't import by library name, even though I have python setup.py develop it | 39,801,085 | <p>I am running into a very strange python import problem. I wrote my own repo, and used a setup.py script to setup the import path, script below:</p>
<pre><code>#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
from setuptools import setup, find_packages
__author__ = 'Shaun Rong'
__version__ = '0.1'
__maintainer__ = 'Shaun Rong'
__email__ = 'rongzq08@gmail.com'
if __name__ == "__main__":
setup(name='Quantomic',
version=__version__,
author="Ziqin (Shaun) Rong, Wenxuan Huang",
author_email="rongzq08@mit.edu key01027@mit.edu",
license="MIT License",
packages=find_packages(),
zip_safe=False)
</code></pre>
<p>I used <code>python setup.py develop</code> to run the codes. Now, however, I can't import the whole library by name <strong>Quantomic</strong>, any codes like </p>
<pre><code>import Quantomic
</code></pre>
<p>or </p>
<pre><code>from Quantomic import settings
</code></pre>
<p>will raise the error: <code>ImportError: No module named Quantomic</code></p>
<p>I do have a <code>__init__.py</code> under the library root, and I checked <code>sys.path</code>, <code>/Users/shaunrong/Documents/projects/Quantomic</code> is in the path.</p>
<p>I do, however, can import using relative paths in any codes inside Quantomic, using like</p>
<pre><code>import settings
</code></pre>
<p>will work OK.</p>
<p>Can anyone tell me what is going on? I am happy to provide more information upon request!</p>
<p><strong>UPDATE</strong></p>
<p>File/Folder structure looks like:</p>
<pre><code>/Quantomic
__init__.py
settings.py
/data
__init__.py
price.py
</code></pre>
| 0 | 2016-09-30T22:42:06Z | 39,801,498 | <p>Your <code>setup.py</code> file is in the wrong directory. Here is your folder structure</p>
<pre><code>/Quantomic
setup.py
__init__.py
settings.py
/data
__init__.py
price.py
</code></pre>
<p>It should look like this</p>
<pre><code>/Quantomic (can be named anything)
setup.py
/Quantomic
__init__.py
settings.py
/data
__init__.py
price.py
</code></pre>
<p>When you last ran <code>setup.py</code>, it likely installed a <code>data</code> library into your python installation. Or, because you used <code>develop</code>, it added the path above <code>data</code> to the pythonpath using a <code>pth</code> file in your python libs folder.</p>
| 1 | 2016-09-30T23:39:28Z | [
"python",
"import"
]
|
How to document a Python variable? | 39,801,102 | <p>How can I document a variable in Python. In JavaScript / JSDoc I can do something like that.:</p>
<pre><code>/** @type {Array<Number>} */
var foo;
/** @type {Number[]} */
var bar;
</code></pre>
<p>Some IDEs than can give better code completion.</p>
<p>Is this also possible in Python?</p>
| 0 | 2016-09-30T22:44:18Z | 39,801,255 | <p><code>x, y, z = [], [], [] # type: (List[int], List[int], List[str])</code> is how it is defined in the spec ... your particular IDE may or may not implement it in this way ...</p>
<p>see also: <a href="https://www.python.org/dev/peps/pep-0484/#type-comments" rel="nofollow">https://www.python.org/dev/peps/pep-0484/#type-comments</a></p>
| 1 | 2016-09-30T23:02:40Z | [
"python",
"documentation"
]
|
How to use Python Requests to make this POST request | 39,801,236 | <p>I'm trying to POST to the Adobe Sign API. Even if you're not familiar with the API, this should be a pretty straightforward question. </p>
<p>Sign's documentation says the POST I need to do looks like this: </p>
<pre><code>POST /api/rest/v5/transientDocuments HTTP/1.1
Host: api.na1.echosign.com
Access-Token: MvyABjNotARealTokenHkYyi
Content-Type: multipart/form-data
Content-Disposition: form-data; name="File"; filename="MyPDF.pdf"
<PDF CONTENT>
</code></pre>
<p>Here is my current code, using Python Requests: </p>
<pre><code>def createTransientDocument(your_file_base_url, file_name):
headers = {'access-token': datafile.accessToken,
'x-user-email': '<redacted for StackOverflow>',
'content-type': 'multipart/form-data'}
files = {'file': (file_name, open(your_file_base_url + file_name, 'rb'))}
r = requests.post(datafile.transient_documents_URL, files = files, headers=headers)
return r
</code></pre>
<p>Unfortunately, this is not quite what the API is looking for. I get a response: </p>
<pre><code>*{"code":"BAD_REQUEST","message":"The request provided is invalid"}*
</code></pre>
<p>Any tips on how to use the Requests library to POST my PDF file to this API? </p>
<p>Sorry for the n00b question, but I am learning the Requests library right now. Thanks. </p>
| 0 | 2016-09-30T23:00:59Z | 39,801,571 | <p>It's a nuance, but you need to name the file "File" with a capital F. Otherwise the API doesn't pick it up on the Adobe Sign side. Here is the correct (and working) API call. </p>
<pre><code>def createTransientDocument(your_file_base_url, file_name):
headers = {'access-token': datafile.accessToken,
'x-user-email': '<email redacted>',
'content-disposition':'form-data'}
files = {'File': open(your_file_base_url+file_name, 'rb')}
r = requests.post(datafile.transient_documents_URL, files=files, headers=headers)
return r
</code></pre>
| 0 | 2016-09-30T23:51:16Z | [
"python",
"post",
"python-requests"
]
|
analyzing excel using pandas | 39,801,265 | <p>I wanted to analyze excel files and find out the data range ( min value, max value, min len, max len, blanks etc I want to create a new analysis file which would spit out these insights. I'm looking into the panda library to do this. </p>
<pre><code>df = pd.read_excel(open('file.xlsx','rb'), sheetname='TestData')
</code></pre>
<p>How should I be proceeding ?</p>
| 0 | 2016-09-30T23:03:54Z | 39,801,338 | <p>Use numpy to get the minimum/maximum etc. The functions require numpy arrays though, so either slice each column of a dataframe, or cast the dataframe as a matrix</p>
<p><a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html" rel="nofollow">https://docs.scipy.org/doc/numpy/reference/generated/numpy.argmax.html</a></p>
| 0 | 2016-09-30T23:14:44Z | [
"python",
"excel",
"csv",
"pandas"
]
|
analyzing excel using pandas | 39,801,265 | <p>I wanted to analyze excel files and find out the data range ( min value, max value, min len, max len, blanks etc I want to create a new analysis file which would spit out these insights. I'm looking into the panda library to do this. </p>
<pre><code>df = pd.read_excel(open('file.xlsx','rb'), sheetname='TestData')
</code></pre>
<p>How should I be proceeding ?</p>
| 0 | 2016-09-30T23:03:54Z | 39,807,421 | <p>you can find out some of those statistics you are looking for - min, max, avg (mean), std. deviation for numeric columns using <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.describe.html" rel="nofollow">describe()</a> method</p>
<p>Demo:</p>
<pre><code>df = pd.read_excel(r'/path/to/file.xlsx')
In [35]: df
Out[35]:
a b c txt
0 8 5 2 dd
1 6 6 2 aa
2 3 7 9 cc
3 4 2 3 dd
4 3 3 5 cc
In [36]: df.describe()
Out[36]:
a b c
count 5.000000 5.000000 5.000000
mean 4.800000 4.600000 4.200000
std 2.167948 2.073644 2.949576
min 3.000000 2.000000 2.000000
25% 3.000000 3.000000 2.000000
50% 4.000000 5.000000 3.000000
75% 6.000000 6.000000 5.000000
max 8.000000 7.000000 9.000000
</code></pre>
| 0 | 2016-10-01T13:51:38Z | [
"python",
"excel",
"csv",
"pandas"
]
|
Select a tag inside a class with bs4 | 39,801,273 | <p>I'm trying to get the href of this part of html:</p>
<pre><code><h3 class="post-title entry-title" itemprop="name">
<a href="http://sslproxies24.blogspot.it/2016/10/01-10-16-free-ssl-proxies-1070.html">01-10-16 | Free SSL Proxies (1070)</a>
</h3>
</code></pre>
<p>So I created this script:</p>
<pre><code>import urllib.request
from bs4 import BeautifulSoup
url = "http://sslproxies24.blogspot.it/"
soup = BeautifulSoup(urllib.request.urlopen(url))
for tag in soup.find_all("h3", "post-title entry-title"):
links = tag.get("href")
</code></pre>
<p>But links, doesn't find anything. This is because, the class "post-title entry-title" that I selected with bs4, has not attribute "href"...</p>
<p>In fact the output of:</p>
<pre><code>print (tag.attrs)
</code></pre>
<p>is:</p>
<pre><code>{'itemprop': 'name', 'class': ['post-title', 'entry-title']}
</code></pre>
<p>How can I do to select the "a" element and get the links in href?</p>
| 2 | 2016-09-30T23:05:01Z | 39,801,387 | <p>You can quickly solve it by getting the inner <code>a</code> element:</p>
<pre><code>for tag in soup.find_all("h3", "post-title entry-title"):
link = tag.a.get("href")
</code></pre>
<p>where <code>tag.a</code> is a shortcut to <code>tag.find("a")</code>.</p>
<p>Or, you can match the <code>a</code> element directly with a <a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors" rel="nofollow">CSS selector</a>:</p>
<pre><code>for a in soup.select("h3.post-title.entry-title > a"):
link = a.get("href")
</code></pre>
<p>where dot is a <em>class</em> attribute selector, <code>></code> means <em>direct parent-child relationship</em>.</p>
<p>Or, you can check <code>itemprop</code> attribute instead of a class:</p>
<pre><code>for a in soup.select("h3[itemprop=name] > a"):
link = a.get("href")
</code></pre>
| 1 | 2016-09-30T23:22:21Z | [
"python",
"python-3.x",
"beautifulsoup",
"bs4"
]
|
Need help using python subprocess module to navigate Linux directories | 39,801,284 | <p>First off, I know there are FAR better ways to do this. I'm trying to learn the most basic behavior of subprocess.Popen() when it interacts with various UNIX commands. I'm doing something wrong with directory navigation, and I have no idea what it is. I'm running iPython as my REPL, so the ls command shows the files in the current working directory. </p>
<p>Someone please tell me what I'm doing wrong! </p>
<pre><code>In [61]: newtree_dirs
Out[61]:
['10dir',
'1dir',
'2dir',
'3dir',
'4dir',
'5dir',
'6dir',
'7dir',
'8dir',
'9dir']
In [62]: ls
10dir/ 1dir/ 2dir/ 3dir/ 4dir/ 5dir/ 6dir/ 7dir/ 8dir/ 9dir/
In [63]: for folder in newtree_dirs:
...: p1 = sub.Popen(['cd', './{}'.format(folder)])
...: p1.communicate()
...: foo = (i for i in xrange(10))
...: for num in foo:
...: p2 = sub.Popen(['touch', '{}file'.format(num)])
...: p2.communicate()
...: p3 = sub.Popen(['cd', '..'])
...: p3.communicate()
...:
...:
---------------------------------------------------------------------------
OSError Traceback (most recent call last)
<ipython-input-63-bb6e77faf97b> in <module>()
1 for folder in newtree_dirs:
----> 2 p1 = sub.Popen(['cd', u'./{}'.format(folder)])
3 p1.communicate()
4 bar = (i for i in xrange(10))
5 for num in bar:
</code></pre>
<p>after that exception, further exceptions descend into the subprocess module's error handling for a missing directory. The directory names in my cwd are identical and I don't know what's going on. </p>
| 2 | 2016-09-30T23:06:24Z | 39,820,473 | <p><code>sub.Popen(['cd', './10dir')</code> raises "OSError: [Errno 2] No such <strong>file</strong> or directory" because there is no such file named <code>cd</code> on your <code>$PATH</code> (and possibly on your computer at all). <code>cd</code> is not a stand alone executable, it's a shell builtin. If it were a stand alone executable it wouldn't be able to change the current working directory of the shell (or of your script for that matter) because a child process can't directly change it's parent's current working directory, environment variables, user id etc.</p>
<p>More info:<br>
<a href="//unix.stackexchange.com/q/11454/142240">builtin vs normal command</a></p>
<p>Note: Technically to be POSIX complient in addition to the shell builtin <code>cd</code> an OS must provide a stand alone executable <code>cd</code> that changes <strong>it's own</strong> current directory and returns, but many Linux distributions don't include it. Source: <a href="//unix.stackexchange.com/a/38819/142240">Why is cd not a program?</a></p>
| 1 | 2016-10-02T18:52:24Z | [
"python",
"linux",
"shell"
]
|
How can I get the page source, without showing the page opened, using selenium with chromedriver and python? | 39,801,287 | <p>I'm using selenium with Chrome driver; How can I get the page source, without showing the page opened? What I should specify in webdriver.ChromeOptions()?
Here the code:</p>
<pre><code>from selenium.common.exceptions import WebDriverException
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("???")
bowser = webdriver.Chrome(chrome_options=chrome_options)
browser = webdriver.Chrome()
try:
browser.get("www.google.com")
html_content = browser.page_source
#do stuff
browser.quit()
except WebDriverException:
print "Invalid URL"
</code></pre>
| 0 | 2016-09-30T23:07:01Z | 39,801,529 | <p>You should not use <code>ChromeDriver</code> but some headless Webdriver like <code>HtmlUnitDriver</code>, explained <a href="http://www.seleniumhq.org/docs/03_webdriver.jsp#htmlunit-driver" rel="nofollow">here</a></p>
| 0 | 2016-09-30T23:45:03Z | [
"python",
"selenium",
"selenium-chromedriver"
]
|
How can I get the page source, without showing the page opened, using selenium with chromedriver and python? | 39,801,287 | <p>I'm using selenium with Chrome driver; How can I get the page source, without showing the page opened? What I should specify in webdriver.ChromeOptions()?
Here the code:</p>
<pre><code>from selenium.common.exceptions import WebDriverException
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("???")
bowser = webdriver.Chrome(chrome_options=chrome_options)
browser = webdriver.Chrome()
try:
browser.get("www.google.com")
html_content = browser.page_source
#do stuff
browser.quit()
except WebDriverException:
print "Invalid URL"
</code></pre>
| 0 | 2016-09-30T23:07:01Z | 39,802,501 | <p>If you are adamant to use selenium, then you can use any of the headless browsers such as htmlunit driver.
Else you can can just send a get request on the URL and get the response text.</p>
| 0 | 2016-10-01T02:42:57Z | [
"python",
"selenium",
"selenium-chromedriver"
]
|
Convert string expression to mathematical expression? | 39,801,324 | <p>I'm looking for something that would take a mathematical expression string as an input and would change it by adding parentheses to it. </p>
<p>For examples :</p>
<p>Input 1 : <code>"2*4^7"</code></p>
<p>Output 1 : <code>"(2*(4^7))"</code></p>
<p>Input 2 : <code>"sin(x)*3-8^9"</code></p>
<p>Output 2 : <code>"((sin(x)*3)-(8^9))"</code></p>
<p>Input 3 : <code>"(2-8)/6"</code></p>
<p>Output 3 : <code>"((2-8)/6)"</code></p>
<p>I'm currently trying to code it, but it's taking too much time and I would rather focus on other things, so if you guys know some module that could do that, that would be great. </p>
<p>I'm working with python 3</p>
<p>Thank you!</p>
| 2 | 2016-09-30T23:13:01Z | 39,801,484 | <p>Using the <code>ast</code> module, you can parse your string and then traverse it to build a string representation you require:</p>
<pre><code>import ast
def represent(tree):
t = type(tree)
if t == ast.Module:
return represent(tree.body)
elif t == list:
# arithmetic expression should only be one thing
return ", ".join(represent(part) for part in tree)
elif t == ast.Expr:
return represent(tree.value)
elif t == ast.BinOp:
o = type(tree.op)
if o == ast.BitXor:
op = "^"
elif o == ast.Mult:
op = "*"
elif o == ast.Add:
op = "+"
...
return "({}{}{})".format(
represent(tree.left),
op,
represent(tree.right),
)
elif t == ast.Num:
return str(tree.n)
elif t == ast.Name:
return tree.id
elif t == ast.Call:
return "{}({})".format(
represent(tree.func),
represent(tree.args),
)
...
# prints (((sin(x)*2)*x)+4)
print(represent(ast.parse("sin(x)*2*x+4")))
</code></pre>
<p>As @user2357112 noted in the comments, this will only work if you limit yourself to use Python's expression syntax, most importantly by using <code>**</code> instead of <code>^</code> for exponentiation. </p>
| 1 | 2016-09-30T23:36:56Z | [
"python",
"string",
"python-3.x"
]
|
uwsgi cheaper killing workers processing requests | 39,801,326 | <p>I have a very basic flask application under uwsgi, managed by signals under supervisorctl. I use cheaper for scaling workers and ran into very disturbing situation.
uwsgi is killing oldest worker, even when it is processing a request, causing 500.</p>
<p><strong>How to prevent uwsgi from killing workers processing the request, for the sake of cheaping?</strong></p>
<p>Any help/hints deeply appreciated.
Found another similar post without response: <a href="http://stackoverflow.com/questions/28307401/uwsgi-killing-workers-too-fast">UWSGI killing workers too fast</a> </p>
<p>Config: uwsgi version: 2.0.4</p>
<pre><code># Auto-scaling
workers = 30
cheaper = 2
cheaper-step = 3
cheaper-algo = backlog
cheaper-overload = 2
</code></pre>
<p>Logs:</p>
<pre><code>[pid: 15601|app: 0|req: 13/78] 10.83.9.61 () {28 vars in 368 bytes} [Fri Sep 30 02:00:34 2016] POST /xxxxxxxxxxxx => generated 257 bytes in 151 msecs (HTTP/1.1 200) 2 headers in 72 bytes (1 switches on core 0)
[pid: 15601|app: 0|req: 14/79] 10.83.9.61 () {28 vars in 368 bytes} [Fri Sep 30 02:00:35 2016] POST /xxxxxxxxxxxx => generated 186 bytes in 649 msecs (HTTP/1.1 200) 2 headers in 72 bytes (1 switches on core 0)
[pid: 15600|app: 0|req: 21/80] 10.83.9.62 () {28 vars in 369 bytes} [Fri Sep 30 03:30:08 2016] POST /xxxxxxxxxxxx => generated 186 bytes in 2696 msecs (HTTP/1.1 200) 2 headers in 72 bytes (3 switches on core 0)
Respawned uWSGI worker 1 (new pid: 21009)
Respawned uWSGI worker 4 (new pid: 21010)
Respawned uWSGI worker 5 (new pid: 21011)
[pid: 15601|app: 0|req: 15/81] 10.83.9.62 () {28 vars in 370 bytes} [Fri Sep 30 03:30:09 2016] POST /xxxxxxxxxxxx => generated 186 bytes in 3046 msecs (HTTP/1.1 200) 2 headers in 72 bytes (2 switches on core 0)
[pid: 15600|app: 0|req: 22/82] 10.83.9.63 () {28 vars in 370 bytes} [Fri Sep 30 03:30:10 2016] POST /xxxxxxxxxxxx => generated 0 bytes in 3347 msecs (HTTP/1.1 500) 2 headers in 127 bytes (7 switches on core 0)
worker 2 killed successfully (pid: 15600) <------------- pid 15600 was interrupted, returned 500 (line above)
uWSGI worker 2 cheaped.
[pid: 15601|app: 0|req: 16/83] 10.83.9.62 () {28 vars in 369 bytes} [Fri Sep 30 03:30:12 2016] POST /xxxxxxxxxxxx => generated 0 bytes in 2560 msecs (HTTP/1.1 500) 2 headers in 127 bytes (3 switches on core 0)
[pid: 21010|app: 0|req: 19/84] 10.83.9.63 () {28 vars in 369 bytes} [Fri Sep 30 03:30:12 2016] POST /xxxxxxxxxxxx => generated 186 bytes in 2931 msecs (HTTP/1.1 200) 2 headers in 72 bytes (4 switches on core 0)
worker 3 killed successfully (pid: 15601) <------------- pid 15601 was interrupted, returned 500 (line above)
uWSGI worker 3 cheaped.
[pid: 21011|app: 0|req: 22/85] 10.83.9.61 () {28 vars in 370 bytes} [Fri Sep 30 03:30:12 2016] POST /xxxxxxxxxxxx => generated 186 bytes in 3236 msecs (HTTP/1.1 200) 2 headers in 72 bytes (4 switches on core 0)
[pid: 21009|app: 0|req: 7/86] 10.83.9.61 () {28 vars in 370 bytes} [Fri Sep 30 03:30:12 2016] POST /xxxxxxxxxxxx => generated 0 bytes in 3532 msecs (HTTP/1.1 500) 2 headers in 127 bytes (4 switches on core 0)
worker 1 killed successfully (pid: 21009) <------------- pid 15601 was interrupted, returned 500 (line above)
uWSGI worker 1 cheaped.
[pid: 21011|app: 0|req: 23/87] 10.83.9.63 () {28 vars in 369 bytes} [Fri Sep 30 03:30:15 2016] POST /xxxxxxxxxxxx => generated 186 bytes in 1614 msecs (HTTP/1.1 200) 2 headers in 72 bytes (1 switches on core 0)
Respawned uWSGI worker 1 (new pid: 21013)
Respawned uWSGI worker 2 (new pid: 21014)
Respawned uWSGI worker 3 (new pid: 21015)
[pid: 21011|app: 0|req: 24/88] 10.83.9.61 () {28 vars in 369 bytes} [Fri Sep 30 03:30:17 2016] POST /xxxxxxxxxxxx => generated 186 bytes in 2546 msecs (HTTP/1.1 200) 2 headers in 72 bytes (3 switches on core 0)
[pid: 21010|app: 0|req: 20/89] 10.83.9.62 () {28 vars in 370 bytes} [Fri Sep 30 03:30:15 2016] POST /xxxxxxxxxxxx => generated 0 bytes in 4845 msecs (HTTP/1.1 500) 2 headers in 127 bytes (6 switches on core 0)
worker 4 killed successfully (pid: 21010) <------------- pid 15601 was interrupted, returned 500 (line above)
uWSGI worker 4 cheaped.
[pid: 21015|app: 0|req: 17/90] 10.83.9.61 () {28 vars in 369 bytes} [Fri Sep 30 03:30:18 2016] POST /xxxxxxxxxxxx => generated 186 bytes in 2402 msecs (HTTP/1.1 200) 2 headers in 72 bytes (3 switches on core 0)
worker 5 killed successfully (pid: 21011) <------------- pid 15601 was interrupted, returned 500 (line above)
</code></pre>
| 0 | 2016-09-30T23:13:25Z | 39,808,544 | <p>Bug fixed & merged in August 2016.</p>
<p><a href="https://github.com/unbit/uwsgi/issues/1288" rel="nofollow">https://github.com/unbit/uwsgi/issues/1288</a></p>
<p><a href="https://github.com/unbit/uwsgi/commit/f5dd0b855d0d21be62534dc98375fae2cd7c13f0" rel="nofollow">https://github.com/unbit/uwsgi/commit/f5dd0b855d0d21be62534dc98375fae2cd7c13f0</a></p>
| 0 | 2016-10-01T15:47:41Z | [
"python",
"flask",
"uwsgi"
]
|
How to derive equation from Numpy's polyfit? | 39,801,403 | <p>Given an array of x and y values, the following code will calculate a regression curve for these data points.</p>
<pre><code># calculate polynomial
z = np.polyfit(x, y, 5)
f = np.poly1d(z)
# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)
plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()
</code></pre>
<p>How can I use the above to derive the actual equation for this curve?</p>
| 0 | 2016-09-30T23:24:55Z | 39,801,630 | <p>Construct a simple example:</p>
<pre><code>In [94]: x=np.linspace(0,1,100)
In [95]: y=2*x**3-3*x**2+x-1
In [96]: z=np.polyfit(x,y,3)
In [97]: z
Out[97]: array([ 2., -3., 1., -1.])
</code></pre>
<p>The <code>z</code> coefficients correspond to the [2,-3,1,-1] I used to construct <code>y</code>.</p>
<pre><code>In [98]: f=np.poly1d(z)
In [99]: f
Out[99]: poly1d([ 2., -3., 1., -1.])
</code></pre>
<p>The <code>str</code>, or print, string for <code>f</code> is a representation of this polynomial equation. But it's the <code>z</code> coeff that defines the equation.</p>
<pre><code>In [100]: print(f)
3 2
2 x - 3 x + 1 x - 1
In [101]: str(f)
Out[101]: ' 3 2\n2 x - 3 x + 1 x - 1'
</code></pre>
<p>What else do you mean by 'actual equation'?</p>
<p><code>polyval</code> will evaluate <code>f</code> at a specific set of <code>x</code>. Thus to recreate <code>y</code>, use <code>polyval(f,x)</code>:</p>
<pre><code>In [107]: np.allclose(np.polyval(f,x),y)
Out[107]: True
</code></pre>
| 2 | 2016-10-01T00:00:59Z | [
"python",
"numpy"
]
|
How to derive equation from Numpy's polyfit? | 39,801,403 | <p>Given an array of x and y values, the following code will calculate a regression curve for these data points.</p>
<pre><code># calculate polynomial
z = np.polyfit(x, y, 5)
f = np.poly1d(z)
# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)
plt.plot(x,y,'o', x_new, y_new)
plt.xlim([x[0]-1, x[-1] + 1 ])
plt.show()
</code></pre>
<p>How can I use the above to derive the actual equation for this curve?</p>
| 0 | 2016-09-30T23:24:55Z | 39,801,980 | <p>If you want to show the equation, you can use <code>sympy</code> to output latex:</p>
<pre><code>from sympy import S, symbols
from matplotlib import pyplot as plt
import numpy as np
x=np.linspace(0,1,100)
y=np.sin(2 * np.pi * x)
p = np.polyfit(x, y, 5)
f = np.poly1d(p)
# calculate new x's and y's
x_new = np.linspace(x[0], x[-1], 50)
y_new = f(x_new)
x = symbols("x")
poly = sum(S("{:6.2f}".format(v))*x**i for i, v in enumerate(p[::-1]))
eq_latex = sympy.printing.latex(poly)
plt.plot(x_new, y_new, label="${}$".format(eq_latex))
plt.legend(fontsize="small")
</code></pre>
<p>the result:</p>
<p><a href="http://i.stack.imgur.com/Q1h21.png" rel="nofollow"><img src="http://i.stack.imgur.com/Q1h21.png" alt="enter image description here"></a></p>
| 1 | 2016-10-01T01:00:06Z | [
"python",
"numpy"
]
|
Ignoring a value in a list search | 39,801,404 | <p>I am using lists to store attributes and this problem cropped up when I was searching for equal items:</p>
<pre><code>l = [['a',1,2],['b',1,2],['c',2,3],['d',1,2]]
if [any,1,2] in l:
print ('blue')
elif [any,2,3] in l:
print('red')
</code></pre>
<p>desired output</p>
<pre><code>blue
</code></pre>
<p>What I want is the first value being ignored/can be any value.
I know the any function doesn't work this way but what is the correct method to doing so?</p>
<p>Perhaps this is more understandable</p>
<pre><code>l = [['a',1,2],['b',1,2],['c',2,3],['d',1,2]]
for a in range(0,4):
if [1,2] == x[1:] for x in l:
print ('blue')
elif [2,3] == x[1:] for x in l:
print('red')
</code></pre>
| -1 | 2016-09-30T23:25:03Z | 39,801,455 | <p>For filtering equal items (according to your definition) you can use list comprehension and slicing:</p>
<pre><code>>>> lst = [['a',1,2],['b',1,2],['c',2,3],['d',1,2]]
>>> [e for e in lst if e[1:] == [1,2]]
[['a', 1, 2], ['b', 1, 2], ['d', 1, 2]]
</code></pre>
| 0 | 2016-09-30T23:31:39Z | [
"python",
"list"
]
|
Ignoring a value in a list search | 39,801,404 | <p>I am using lists to store attributes and this problem cropped up when I was searching for equal items:</p>
<pre><code>l = [['a',1,2],['b',1,2],['c',2,3],['d',1,2]]
if [any,1,2] in l:
print ('blue')
elif [any,2,3] in l:
print('red')
</code></pre>
<p>desired output</p>
<pre><code>blue
</code></pre>
<p>What I want is the first value being ignored/can be any value.
I know the any function doesn't work this way but what is the correct method to doing so?</p>
<p>Perhaps this is more understandable</p>
<pre><code>l = [['a',1,2],['b',1,2],['c',2,3],['d',1,2]]
for a in range(0,4):
if [1,2] == x[1:] for x in l:
print ('blue')
elif [2,3] == x[1:] for x in l:
print('red')
</code></pre>
| -1 | 2016-09-30T23:25:03Z | 39,801,457 | <p>for completely generic case simply introduce some magical symbol to denote 'any' like '*' and write your own simple comparator</p>
<pre><code>def matches(element, mask):
for el, mask_el in zip(element, mask):
if mask_el != '*' and el != mask_el:
return False
return True
</code></pre>
<p>and now you can do</p>
<pre><code>for list_el in list:
if matches(list_el, ['*', 1, 2]):
print 'blah'
</code></pre>
<p>the nice thing is that it is very generic, and will work with arbitrary number of '*' in your mask.</p>
| -1 | 2016-09-30T23:31:57Z | [
"python",
"list"
]
|
Ignoring a value in a list search | 39,801,404 | <p>I am using lists to store attributes and this problem cropped up when I was searching for equal items:</p>
<pre><code>l = [['a',1,2],['b',1,2],['c',2,3],['d',1,2]]
if [any,1,2] in l:
print ('blue')
elif [any,2,3] in l:
print('red')
</code></pre>
<p>desired output</p>
<pre><code>blue
</code></pre>
<p>What I want is the first value being ignored/can be any value.
I know the any function doesn't work this way but what is the correct method to doing so?</p>
<p>Perhaps this is more understandable</p>
<pre><code>l = [['a',1,2],['b',1,2],['c',2,3],['d',1,2]]
for a in range(0,4):
if [1,2] == x[1:] for x in l:
print ('blue')
elif [2,3] == x[1:] for x in l:
print('red')
</code></pre>
| -1 | 2016-09-30T23:25:03Z | 39,820,888 | <p>:D actually managed to do it in one line thanks to pkacprzak.</p>
<pre><code>l = [['a',1,2],['b',1,2],['c',2,3],['d',1,2]]
if any(True for x in l if x[1:] == [1,2]):
print ('blue')
elif any(True for x in l if x[1:] == [2,3]):
print('red')
</code></pre>
<p>Code works like this:</p>
<pre><code>True for x in l
</code></pre>
<p>iterates over l (<---this is the letter L btw) and returns True if the next bit is True</p>
<pre><code>if x[1:] == [1,2]
</code></pre>
<p>this checks all values of x except the first and returns True</p>
<pre><code>any(...)
</code></pre>
<p>finds if any of the values returned from the bit inside the any is True</p>
<p>You could also return the value of the first item like so</p>
<pre><code>[x[0] for x in l if x[1:] == [1,2]]
</code></pre>
<p>and iterate over that as well</p>
| 0 | 2016-10-02T19:37:16Z | [
"python",
"list"
]
|
Sampling in pandas | 39,801,405 | <p>If I want to randomly sample a pandas dataframe I can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html" rel="nofollow">pandas.DataFrame.sample</a>.</p>
<p>Suppose I randomly sample 80% of the rows. How do I automatically get the other 20% of the rows that were not picked?</p>
| 2 | 2016-09-30T23:25:07Z | 39,801,461 | <p>As Lagerbaer explains, one can add a column with a unique index to the dataframe, or randomly shuffle the entire dataframe. For the latter, </p>
<pre><code>df.reindex(np.random.permutation(df.index))
</code></pre>
<p>works. (np means numpy)</p>
| 3 | 2016-09-30T23:32:35Z | [
"python",
"pandas"
]
|
Sampling in pandas | 39,801,405 | <p>If I want to randomly sample a pandas dataframe I can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sample.html" rel="nofollow">pandas.DataFrame.sample</a>.</p>
<p>Suppose I randomly sample 80% of the rows. How do I automatically get the other 20% of the rows that were not picked?</p>
| 2 | 2016-09-30T23:25:07Z | 39,801,503 | <pre><code>>>> import pandas as pd, numpy as np
>>> df = pd.DataFrame({'a': [1,2,3,4,5,6,7,8,9,10], 'b': [11,12,13,14,15,16,17,18,19,20]})
>>> df
a b
0 1 11
1 2 12
2 3 13
3 4 14
4 5 15
5 6 16
6 7 17
7 8 18
8 9 19
9 10 20
# randomly sample 5 rows
>>> sample = df.sample(5)
>>> sample
a b
7 8 18
2 3 13
4 5 15
0 1 11
3 4 14
# list comprehension to get indices not in sample's indices
>>> idxs_not_in_sample = [idx for idx in df.index if idx not in sample.index]
>>> idxs_not_in_sample
[1, 5, 6, 8, 9]
# locate the rows at the indices in the original dataframe that aren't in the sample
>>> not_sample = df.loc[idxs_not_in_sample]
>>> not_sample
a b
1 2 12
5 6 16
6 7 17
8 9 19
9 10 20
</code></pre>
| 2 | 2016-09-30T23:40:05Z | [
"python",
"pandas"
]
|
Permutations of a list using stack | 39,801,420 | <p>I'm trying to find a way to enumerate all combinations of a list of numbers without recursion or using itertools. I came up with a solution that works but I think it turned into a recursive function after all. I'm new to Python and not sure how I would make this work without recursion.</p>
<p>Any help is appreciated as I think I'm still failing to see the difference between the two.</p>
<pre><code>result = []
def permutation(li):
if len(li) == 1:
result.append(li[0])
print (result)
result.pop()
return
for i in range(0,len(li)):
result.append(li[i])
permutation(li[:i] + li[i+1:])
result.pop()
permutation([1,2,3])
</code></pre>
| 0 | 2016-09-30T23:27:36Z | 39,801,605 | <p>It is not that intuitive to come up with an algorithm "just like that" that produces all permutations without the use of recursion. </p>
<p>But there exist several different such algorithms. Have look at <a href="https://en.wikipedia.org/wiki/Heap%27s_algorithm" rel="nofollow">Heap's algorithm</a> for example:</p>
<pre><code>def permutation(li):
n = len(li)
c = [0] * n
print(li)
i = 1
while i < n:
if c[i] < i:
j = c[i] if i % 2 else 0
li[j], li[i] = li[i], li[j]
print(li)
c[i] += 1
i = 1
else:
c[i] = 0
i += 1
</code></pre>
| 2 | 2016-09-30T23:56:58Z | [
"python",
"algorithm"
]
|
Permutations of a list using stack | 39,801,420 | <p>I'm trying to find a way to enumerate all combinations of a list of numbers without recursion or using itertools. I came up with a solution that works but I think it turned into a recursive function after all. I'm new to Python and not sure how I would make this work without recursion.</p>
<p>Any help is appreciated as I think I'm still failing to see the difference between the two.</p>
<pre><code>result = []
def permutation(li):
if len(li) == 1:
result.append(li[0])
print (result)
result.pop()
return
for i in range(0,len(li)):
result.append(li[i])
permutation(li[:i] + li[i+1:])
result.pop()
permutation([1,2,3])
</code></pre>
| 0 | 2016-09-30T23:27:36Z | 39,803,099 | <p>I always liked this method: </p>
<p>Until the length of each variation in the queue equals the input's length: place the next input element in all positions of each variation</p>
<pre><code>input [1,2,3]
queue [[1]]
insert 2 in all positions of each variation
queue [[2,1],[1,2]]
insert 3 in all positions of each variation
queue [[3,2,1],[2,3,1],[2,1,3],[3,1,2],[1,3,2],[1,2,3]]
</code></pre>
| 1 | 2016-10-01T04:41:04Z | [
"python",
"algorithm"
]
|
How to inspect program state in the presence of generators/coroutines? | 39,801,488 | <p>With normal functions calls, the program state is mostly described by a simple call stack. It is printed out as a traceback after an uncaught exception, it can be examined with <code>inspect.stack</code>, and it can be displayed in a debugger after a breakpoint.</p>
<p>In the presence of generators, generator-based couroutines, and <code>async def</code>-based coroutines, I don't think the call stack is enough. What's a good way to mentally visualize the program state? How do I inspect it in run-time?</p>
<p>There are functions <code>inspect.getgeneratorstate</code> and <code>inspect.getcoroutinestate</code>, but they only provide information about whether the generator/coroutine is created, running, suspended, or closed. In the case the state is <code>RUNNING</code>, I want to be able to examine the actual line number the generator or coroutine is currently executing and the stack frames that correspond to the other functions it might have called. In the case it's <code>SUSPENDED</code>, I want to examine other generators / coroutines it sent data to or yielded to.</p>
<p>Edit: I found a related <a href="http://stackoverflow.com/questions/8389812/how-are-generators-and-coroutines-implemented-in-cpython">question on SO</a> which pointed me to this <a href="http://aosabook.org/en/500L/a-web-crawler-with-asyncio-coroutines.html" rel="nofollow">excellent article</a> that explains everything I asked about in this question.</p>
| 1 | 2016-09-30T23:37:36Z | 39,811,920 | <p>You just have to findout all instances fo generators and co-routines, in all "traditional" frames - (either search for them recursively in all objects in all frames, or you mitght try to use the garbage collector (gc) module to get a reference to all these instances)</p>
<p>Generators and co-routines have, respectively, a gi_frame and a cr_frame attribute.</p>
| 1 | 2016-10-01T22:09:41Z | [
"python",
"python-3.x",
"python-asyncio",
"coroutine",
"python-internals"
]
|
Scipy.optimize not fiting to my data | 39,801,490 | <p>I cannot get <code>scipy.optimize.curve_fit</code> to properly fit my data which is visually apparent. I know approximately what the parameter values should be and if I evaluate the function with the given parameters the calculated and experimental data appear to agree well:</p>
<p><img src="http://i.stack.imgur.com/Szbpj.png" alt="calculated and experimental data"></p>
<p>However, when I use <code>scipy.optimize.curve_fit</code> the output parameters with the smallest error is a much worse fit (by visual inspection). If I use the "known" parameters as my initial guess and bound the parameters to a relatively narrow window as shown in the example of output from fit function:</p>
<p><img src="http://i.stack.imgur.com/wezhW.png" alt="example of output from fit function"></p>
<p>I obtain error values ~10^2 times larger but the visual appearance of the fit seems better. The only way I can get a decent looking fit for the data is to bound all the parameters with ~ 0.3 units of the "known" parameter. I plan on using this code to fit more complex data that I will not know the parameters before hand, so I cannot just use the calculated plot.</p>
<p>The relevant code is included below:</p>
<pre><code>import matplotlib.pyplot as plt
import numpy as np
import scipy
from scipy.optimize import curve_fit
d_1= 2.72 #Anstroms
sig_cp_1= 0.44
sig_int_1= 1.03
d_1, sig_cp_1,sig_int_1=float(d_1),float(sig_cp_1),float(sig_int_1)
Ref=[]
Qz_F=[]
Ref_F=[]
g=open("Exp_Fresnal.csv",'rb')#"Test_Fresnal.csv", 'rb')
reader=csv.reader(g)
for row in reader:
Qz_F.append(row[0])
Ref.append(row[1])
Ref_F.append(row[2])
Ref=map(lambda a:float(a),Ref)
Ref_F=map(lambda a:float(a),Ref_F)
Qz_F=map(lambda a:float(a),Qz_F)
Ref_F_arr=np.array((Ref_F))
Qz_arr=np.array((Qz_F))
x=np.array((Qz_arr,Ref_F))
def func(x,d,sig_int,sig_cp):
return (x[1])*(abs(x[0]*d*(np.exp((-sig_int**2)*(x[0]**2)/2)/(1-np.exp(complex(0,1)*x[0]*d)*np.exp((-sig_cp**2)*(x[0]**2)/2)))))**2
DC_ref=func(x,d_1,sig_int_1,sig_cp_1)
Y=np.array((Ref))
popt, pcov=curve_fit(func,x,Y,)#p0=[2.72,1.0,0.44])
perr=np.sqrt(np.diag(pcov))
print "par=",popt;print"Var=",perr
Fit=func(x,*popt)
Fit=func(x,*popt)
Ref=np.transpose(np.array([Ref]))
Qz_F=np.transpose(Qz_F)
plt.plot(Qz_F, Ref, 'bs',label='Experimental')
plt.plot(Qz_F, Fit, 'r--',label='Fit w/ DCM model')
plt.axis([0,3,10**(-10),100])
plt.yscale('log')
plt.title('Reflectivity',fontweight='bold',fontsize=15)
plt.ylabel('Reflectivity',fontsize=15)
plt.xlabel('qz /A^-1',fontsize=15)
plt.legend(loc='upper right',numpoints=1)
plt.show()
</code></pre>
<p>The arrays are imported from a file (which I cannot include) and there are no outlier points that would cause the fit to become this distorted. Any help is appreciated.</p>
<p><strong>Edit</strong>
I included additional code and the <a href="https://1drv.ms/x/s!Al_2VBpziAxGgyGcJ0iViVivq9FV" rel="nofollow">input data</a> to go along with the code but you will have to re-save it as a MS-Dos .CSV </p>
| -1 | 2016-09-30T23:38:05Z | 39,801,936 | <p><a href="http://stackoverflow.com/questions/39801490/scipy-optimize-not-fiting-to-my-data#comment66895673_39801490">@WarrenWeckesser has a really good point</a>, but further note that the y axis is logarithmic. That apparently huge error at the right end is something like 1e-5 in magnitude, while the points on the top left have reflectivity values of around 0.1. The square error coming from the tail is simply insignificant compared to the huge terms on the left.</p>
<p>I'm sure <code>curve_fit</code> works great. If you want a better visual fit, I suggest trying a fit to <code>log(y)</code> with the <code>log()</code> of your model (either that, or weight your points during fitting); then the result might be more stable visually (and from a physical point of view). Since you're probably trying to give an overall broad-spectrum description of your system, this might be closer to what you expect (but this will inevitably lead to a less precise fit where the reflectivity is high).</p>
| 2 | 2016-10-01T00:51:32Z | [
"python",
"numpy",
"math",
"scipy",
"best-fit-curve"
]
|
create a list but getting a string? | 39,801,516 | <pre><code>s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def read_nodes(gfile):
for line in gfile.split():
nodes = line.split(":")[1].replace(';',',').split(',')
for node in nodes:
print node
print read_nodes(s)
</code></pre>
<p>I am expected to get <code>['A','B','C','D','E',.....'N']</code>, but I get <code>A B C D E .....N</code> and it's not a list. I spent a lot of time debugging, but could not find the right way.</p>
| -1 | 2016-09-30T23:42:55Z | 39,801,677 | <p>Each <code>line</code> you read will create a new list called nodes. You need to create a list outside this loop and store all the nodes. </p>
<pre><code>s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def read_nodes(gfile):
allNodes = []
for line in gfile.split():
nodes =line.split(":")[1].replace(';',',').split(',')
for node in nodes:
allNodes.append(node)
return allNodes
print read_nodes(s)
</code></pre>
| 0 | 2016-10-01T00:08:18Z | [
"python",
"list",
"debugging"
]
|
create a list but getting a string? | 39,801,516 | <pre><code>s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def read_nodes(gfile):
for line in gfile.split():
nodes = line.split(":")[1].replace(';',',').split(',')
for node in nodes:
print node
print read_nodes(s)
</code></pre>
<p>I am expected to get <code>['A','B','C','D','E',.....'N']</code>, but I get <code>A B C D E .....N</code> and it's not a list. I spent a lot of time debugging, but could not find the right way.</p>
| -1 | 2016-09-30T23:42:55Z | 39,801,680 | <p>Not quite sure what you are ultimately trying to accomplish but this will print what you say you are expecting:</p>
<pre><code>s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def read_nodes(gfile):
nodes = []
for line in gfile.split():
nodes += line.split(":")[1].replace(';',',').split(',')
return nodes
print read_nodes(s)
</code></pre>
| 0 | 2016-10-01T00:08:47Z | [
"python",
"list",
"debugging"
]
|
create a list but getting a string? | 39,801,516 | <pre><code>s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def read_nodes(gfile):
for line in gfile.split():
nodes = line.split(":")[1].replace(';',',').split(',')
for node in nodes:
print node
print read_nodes(s)
</code></pre>
<p>I am expected to get <code>['A','B','C','D','E',.....'N']</code>, but I get <code>A B C D E .....N</code> and it's not a list. I spent a lot of time debugging, but could not find the right way.</p>
| -1 | 2016-09-30T23:42:55Z | 39,801,689 | <p>Add the following code so that the output is
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N'] </p>
<pre><code>//Code to be added
nodes_list = []
def read_nodes(gfile):
for line in gfile.split():
nodes =line.split(":")[1].replace(';',',').split(',')
nodes_list.extend(nodes)
print nodes_list
print read_nodes(s)
</code></pre>
| 0 | 2016-10-01T00:10:21Z | [
"python",
"list",
"debugging"
]
|
create a list but getting a string? | 39,801,516 | <pre><code>s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def read_nodes(gfile):
for line in gfile.split():
nodes = line.split(":")[1].replace(';',',').split(',')
for node in nodes:
print node
print read_nodes(s)
</code></pre>
<p>I am expected to get <code>['A','B','C','D','E',.....'N']</code>, but I get <code>A B C D E .....N</code> and it's not a list. I spent a lot of time debugging, but could not find the right way.</p>
| -1 | 2016-09-30T23:42:55Z | 39,801,702 | <p>I believe this is what you're looking for:</p>
<pre><code>s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def read_nodes(gfile):
nodes = [line.split(":")[1].replace(';',',').split(',') for line in gfile.split()]
nodes = [n for l in nodes for n in l]
return nodes
print read_nodes(s) # prints: ['A','B','C','D','E',.....'N']
</code></pre>
<p>What you were doing wrong is that for each sub-list you create, your were iterating over that sub-list and printing out the contents. </p>
<p>The code above uses list comprehension to first iterate over the <code>gfile</code> and create a list of lists. The list is then flattened with the second line. Afterwards, the flatten list is returned.</p>
<p>If you still want to do it your way, Then you need a local variable to store the contents of each sub-list in, and then return that variable:</p>
<pre><code>s = """
1:A,B,C,D;E,F
2:G,H;J,K
&:L,M,N
"""
def read_nodes(gfile):
all_nodes = []
for line in gfile.split():
nodes = line.split(":")[1].replace(';',',').split(',')
all_nodes.extend(nodes)
return all_nodes
print read_nodes(s)
</code></pre>
| 1 | 2016-10-01T00:12:01Z | [
"python",
"list",
"debugging"
]
|
What does it mean that a scope is determined statically and used dynamically? | 39,801,617 | <p>This is an excerpt of Python docs for Classes I'm struggling to understand:</p>
<blockquote>
<p>A scope is a textual region of a Python program where a namespace is directly accessible. âDirectly accessibleâ here means that an unqualified reference to a name attempts to find the name in the namespace.</p>
<p>Although scopes are determined statically, they are used dynamically.</p>
</blockquote>
<p>I didn't quite comprehend what the author meant by a scope from this definition, what's a textual region of a program, and what it means that scopes are statically determined and dynamically used. I have an intuitive understanding of a scope, but would love to fully appreciate the docs definition. If someone would be so kind as to elaborate what author had in mind it would be greatly appreciated.</p>
| 2 | 2016-09-30T23:58:34Z | 39,801,949 | <h2>"Defined Statically"</h2>
<p>There is global scope and local scope (let's ignore the third one).</p>
<p>Whether a variable is global or local in some function is determined before the function is called, i.e. <strong>statically</strong>.</p>
<p>For example:</p>
<pre><code>a = 1
b = 2
def func1():
c = 3
print func1.__code__.co_varnames # prints ('c',)
</code></pre>
<p>It is determined statically that <code>func1</code> has one local variable and that its name is <code>c</code>. Statically, because it is done as soon as the function is created, not later when some local variable is actually accessed.</p>
<p>What are the consequences of that? Well, for example, this function fails:</p>
<pre><code>a = 1
def func2():
print a # raises an exception
a = 2
</code></pre>
<p>If scopes were dynamic in Python, <code>func2</code> would have printed 1. Instead, in line with <code>print a</code> it is already known that <code>a</code> is a local variable, so the global <code>a</code> will not be used. Local <code>a</code> wont be used either, because it is not yet initialized.</p>
<h2>"Used Dynamically"</h2>
<p>From the <a href="https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces" rel="nofollow">same document</a>:</p>
<blockquote>
<p>On the other hand, the actual search for names is done dynamically, at run time â however, the language definition is evolving towards static name resolution, at âcompileâ time, so donât rely on dynamic name resolution! (In fact, local variables are already determined statically.)</p>
</blockquote>
<p>Global variables are stored in a dictionary. When global variable <code>a</code> is accessed, the interpreter looks for key <code>a</code> in that dictionary. That is dynammic usage.</p>
<p>Local variables are not used that way. The interpreter knows beforehand how many variables a function has, so it can give each of them a fixed location. Then, accessing local variable <code>xy</code> can be optimized by simply taking <em>"the second local variable"</em> or <em>"the fifth local variable"</em>, without actually using the variable name.</p>
| 1 | 2016-10-01T00:54:25Z | [
"python",
"class",
"scope",
"namespaces",
"documentation"
]
|
Assign Global Variable Inside Class From Class Variable | 39,801,660 | <p>I have a question about classes in Python. I have create a class that looks something like this:</p>
<pre><code>class Model(Object):
__table__ = 'table_name'
def func():
def func2():
</code></pre>
<p>The table name is a global variable that the functions feed off of. I am trying to add old data so I would like to change the table name depending on if I am filling in from old information, so this is what I tried. </p>
<pre><code>class Model(Object):
def __init__(self, backfill = False):
self.backfill = backfill
if self.backfill:
__table__ = 'table_name'
else:
__table__ = 'table_name2'
def func():
def func2():
</code></pre>
<p>The final call would be something like this:</p>
<pre><code>if backfill:
model = Model(True).func()
else:
model = Model.func()
</code></pre>
<p>Then I realized this wouldn't work because I cannot call self.backfill from outside the class definitions. I even tried creating a definition and calling that inside the class but that did not work either.</p>
<p>My question is:</p>
<ol>
<li>Is there a way to initialize the global variable inside the class from the class variables? Or is there a better way to do this in general?</li>
</ol>
| 0 | 2016-10-01T00:06:05Z | 39,801,906 | <p><code>__table__</code> is a class variabe, which means you can access it from an instance or from the class itself. You can update any instance value according to the value of <code>backfill</code> in the <code>__init__</code> method:</p>
<pre><code>class Model(Object):
__table__ = 'table_name'
def __init__(self, backfill = False):
self.backfill = backfill
if self.backfill:
self.__table__ = 'table_name2'
</code></pre>
<p>Then to create an instance, just give the <code>backfill</code> parameter to the constructor, without any if/else statement:</p>
<pre><code>print(Model.__table__)
# table_name
backfill = True
model = Model(backfill)
print(model.__table__)
# table_name2
</code></pre>
<p>But I don't see the point of using a class variable in your case. You can just define it in the <code>__init__</code> method:</p>
<pre><code>class Model(Object):
def __init__(self, backfill = False):
self.backfill = backfill
self.__table__ = 'table_name'
if self.backfill:
self.__table__ = 'table_name2'
</code></pre>
| 1 | 2016-10-01T00:43:54Z | [
"python",
"python-2.7",
"class"
]
|
pyspark: add a new field to a data frame Row element | 39,801,691 | <p>I have the following element:</p>
<pre><code>a = Row(ts=1465326926253, myid=u'1234567', mytype=u'good')
</code></pre>
<p>The Row is of spark data frame Row class. Can I append a new field to a, so a would look like:</p>
<pre><code>a = Row(ts=1465326926253, myid=u'1234567', mytype=u'good', name = u'john')
</code></pre>
<p>Thanks!</p>
| 0 | 2016-10-01T00:10:28Z | 39,801,860 | <p>You cannot add new field to the <code>Row</code>. <code>Row</code> is a subclass of <code>tuple</code> and Python <code>tuples</code> are immutable. All you can do is create a new one:</p>
<pre><code>from pyspark.sql import Row
row = Row(ts=1465326926253, myid=u'1234567', mytype=u'good')
Row(**row.asDict(), name=u"john")
## Row(myid='1234567', mytype='good', name='john', ts=1465326926253)
</code></pre>
<p>Please note that <code>Row</code> keeps it fields sorted by name.</p>
| 0 | 2016-10-01T00:36:54Z | [
"python",
"apache-spark",
"dataframe",
"row",
"pyspark"
]
|
Python Requests getting inconsistent response code | 39,801,703 | <p>I am attempting to write a webscraper for the stats.nba.com website. Sometimes when I run a script, it comes out at as a 200 return code, but other times it becomes a 400 error code. I suspect that maybe it's takes a response sometimes, but not sure. Here is an example with four, but it's usually at a much bigger one. </p>
<p>Here is the code. </p>
<pre><code>urls = ['http://stats.nba.com/stats/boxscoresummaryv2?GameID=0021500001', 'http://stats.nba.com/stats/boxscoresummaryv2?GameID=0021500002',
'http://stats.nba.com/stats/boxscoresummaryv2?GameID=0021500003', 'http://stats.nba.com/stats/boxscoresummaryv2?GameID=0021500004']
for url in urls:
r = requests.get(url)
print r.url
print r.status_code
</code></pre>
<p>Here's a sample response and I continue to get wildly inconsistent response codes.</p>
<pre><code>http://stats.nba.com/stats/boxscoresummaryv2?GameID=0021500001
200
http://stats.nba.com/stats/boxscoresummaryv2?GameID=0021500002
400
http://stats.nba.com/stats/boxscoresummaryv2?GameID=0021500003
400
http://stats.nba.com/stats/boxscoresummaryv2?GameID=0021500004
400
</code></pre>
| 2 | 2016-10-01T00:12:08Z | 39,801,928 | <p>You need to pass a user-agent:</p>
<pre><code>In [11]: for url in urls:
....: r = requests.get(url, headers={"user-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.92 Safari/537.36"})
....: print(r.status_code)
....:
200
200
200
200
</code></pre>
<p>No user-agent:</p>
<pre><code>In [12]: for url in urls:
r = requests.get(url)
print(r.status_code)
....:
200
400
400
400
</code></pre>
<p>I would also consider adding a sleep between requests if I were you.</p>
| 0 | 2016-10-01T00:49:11Z | [
"python",
"python-requests"
]
|
How to run a http server which serve a specific path? | 39,801,718 | <p>this is my Python3 project hiearchy:</p>
<pre><code>projet
\
script.py
web
\
index.html
</code></pre>
<p>From <code>script.py</code>, I would like to run a http server which serve the content of the <code>web</code> folder.</p>
<p><a href="https://docs.python.org/3/library/http.server.html" rel="nofollow">Here</a> is suggested this code to run a simple http server:</p>
<pre><code>import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
print("serving at port", PORT)
httpd.serve_forever()
</code></pre>
<p>but this actually serve <code>project</code>, not <code>web</code>. How can I specify the path of the folder I want to serve?</p>
| 0 | 2016-10-01T00:13:59Z | 39,801,780 | <p><a href="https://docs.python.org/3/library/http.server.html#http.server.SimpleHTTPRequestHandler" rel="nofollow">https://docs.python.org/3/library/http.server.html#http.server.SimpleHTTPRequestHandler</a></p>
<blockquote>
<p>This class serves files from the current directory and below, directly
mapping the directory structure to HTTP requests.</p>
</blockquote>
<p>So you just need to change the current directory prior to starting the server - see <a href="https://docs.python.org/3/library/os.html#os.chdir" rel="nofollow"><code>os.chdir</code></a></p>
<p>eg:</p>
<pre><code>import http.server
import socketserver
import os
PORT = 8000
web_dir = os.path.join(os.path.dirname(__file__), 'web')
os.chdir(web_dir)
Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
print("serving at port", PORT)
httpd.serve_forever()
</code></pre>
| 1 | 2016-10-01T00:25:24Z | [
"python",
"python-3.x",
"simplehttpserver"
]
|
Iterating through iterrows | 39,801,726 | <p>iterrows can be used to iterate through a pandas dataframe:</p>
<pre><code>for row in df.iterrows():
print(row)
</code></pre>
<p>How can I use a second for loop to iterate through each element in the row?</p>
| -1 | 2016-10-01T00:15:11Z | 39,801,796 | <p>iterrows returns a tuple. The element indexed by [1] contains the row. You can then iterate through that element.</p>
<pre><code>for row in x.iterrows():
print(row[1])
for b in row[1]:
print(b)
</code></pre>
| 0 | 2016-10-01T00:28:07Z | [
"python",
"pandas"
]
|
Using Flask to load a txt file through the browser and access its data for processing | 39,801,728 | <p>I am making a data visualization tool that takes input from the user (choosing a file on the computer); processes it in Python with Pandas, Numpy, etc; and displays the data in the browser on a local server.</p>
<p>I am having trouble accessing the data once the file is selected using an HTML input form. </p>
<p>HTML form:</p>
<pre><code><form action="getfile" method="POST" enctype="multipart/form-data">
Project file path: <input type="file" name="myfile"><br>
<input type="submit" value="Submit">
</form>
</code></pre>
<p>Flask routing:</p>
<pre><code>@app.route("/")
def index():
return render_template('index.html')
@app.route('/getfile', methods=['GET','POST'])
def getfile():
if request.method == 'POST':
result = request.form['myfile']
else:
result = request.args.get['myfile']
return result
</code></pre>
<p>This returns a "Bad Request The browser (or proxy) sent a request that this server could not understand." error. I have tried a number of different ways of getting the data out of the file and simply printing it to the screen to start, and have received a range of errors including "TypeError: 'FileStorage' object is not callable" and "ImmutableMultiDict' object is not callable". Any pointers on how to approach this task correctly are appreciated.</p>
| 0 | 2016-10-01T00:15:24Z | 39,805,100 | <p>A <code>input type=file</code> data isn't passed in as the <code>form</code> dictionary of a request object. It is passed in as <code>request.files</code> (files dictionary in the request object).</p>
<p>So simply change:</p>
<pre><code>result = request.form['myfile']
</code></pre>
<p>to</p>
<pre><code>result = request.files['myfile']
</code></pre>
| 1 | 2016-10-01T09:40:22Z | [
"python",
"flask"
]
|
Using Flask to load a txt file through the browser and access its data for processing | 39,801,728 | <p>I am making a data visualization tool that takes input from the user (choosing a file on the computer); processes it in Python with Pandas, Numpy, etc; and displays the data in the browser on a local server.</p>
<p>I am having trouble accessing the data once the file is selected using an HTML input form. </p>
<p>HTML form:</p>
<pre><code><form action="getfile" method="POST" enctype="multipart/form-data">
Project file path: <input type="file" name="myfile"><br>
<input type="submit" value="Submit">
</form>
</code></pre>
<p>Flask routing:</p>
<pre><code>@app.route("/")
def index():
return render_template('index.html')
@app.route('/getfile', methods=['GET','POST'])
def getfile():
if request.method == 'POST':
result = request.form['myfile']
else:
result = request.args.get['myfile']
return result
</code></pre>
<p>This returns a "Bad Request The browser (or proxy) sent a request that this server could not understand." error. I have tried a number of different ways of getting the data out of the file and simply printing it to the screen to start, and have received a range of errors including "TypeError: 'FileStorage' object is not callable" and "ImmutableMultiDict' object is not callable". Any pointers on how to approach this task correctly are appreciated.</p>
| 0 | 2016-10-01T00:15:24Z | 39,808,586 | <p>Try this. I've been working on saving and unzipping files for the last few days. If you have any trouble with this code, let me know :)</p>
<p>I'd suggest saving the file on disk and then reading it. If you don't want to do that, you needn't.</p>
<pre><code>from flask import Flask, render_template, request
from werkzeug import secure_filename
@app.route('/getfile', methods=['GET','POST'])
def getfile():
if request.method == 'POST':
# for secure filenames. Read the documentation.
file = request.files['myfile']
filename = secure_filename(file.filename)
# os.path.join is used so that paths work in every operating system
file.save(os.path.join("wherever","you","want",filename))
# You should use os.path.join here too.
with open("wherever/you/want/filename") as f:
file_content = f.read()
return file_content
else:
result = request.args.get['myfile']
return result
</code></pre>
<p>And as zvone suggested in the comments, I too would advise against using GET to upload files.</p>
<p><a href="http://flask.pocoo.org/docs/0.11/patterns/fileuploads/" rel="nofollow">Uploading files</a><br>
<a href="http://effbot.org/librarybook/os-path.htm" rel="nofollow">os.path by Effbot</a></p>
<h3>Edit:-</h3>
<p>You don't want to save the file.</p>
<blockquote>
<p>Uploaded files are stored in memory or at a temporary location on the filesystem. You can access those files by looking at the files attribute on the request object. Each uploaded file is stored in that dictionary. It behaves just like a standard Python file object, but it also has a save() method that allows you to store that file on the filesystem of the server.</p>
</blockquote>
<p>I got this from the Flask documentation. Since it's a Python file you can directly use <code>file.read()</code> on it without <code>file.save()</code>.</p>
<p>Also if you need to save it for sometime and then delete it later, you can use <code>os.path.remove</code> to delete the file after saving it. <a href="http://stackoverflow.com/questions/16168018/deleting-file-if-it-exists-python">Deleting a file in Python</a></p>
| 0 | 2016-10-01T15:51:19Z | [
"python",
"flask"
]
|
In Python, how can I get a line number corresponding to a given character location? | 39,801,748 | <p>If I have a text that I've read into memory by using <code>open('myfile.txt').read()</code>, and if I know a certain location in this file, say, at character 10524, how can I find the line number of that location? </p>
| 0 | 2016-10-01T00:19:15Z | 39,801,759 | <p>Examine the text preceding your desired position and count the number of <code>\n</code> characters.</p>
| 2 | 2016-10-01T00:21:34Z | [
"python"
]
|
In Python, how can I get a line number corresponding to a given character location? | 39,801,748 | <p>If I have a text that I've read into memory by using <code>open('myfile.txt').read()</code>, and if I know a certain location in this file, say, at character 10524, how can I find the line number of that location? </p>
| 0 | 2016-10-01T00:19:15Z | 39,801,789 | <p>Something along the lines of:</p>
<pre><code>txt = open('myfile.txt').read()
lineno = len([c for c in txt[:10524] if c == '\n'])
</code></pre>
| 1 | 2016-10-01T00:26:57Z | [
"python"
]
|
Rsync include/exclude don't work in python subprocess | 39,801,862 | <p>I use rsync to move files from my home computer to a server. Here's the command that I use to transfer and update the directory of only files that contain a grep + glob. I execute this command from the <code>toplevel/</code> directory in the directory structure I show below.</p>
<pre><code> rsync -r --progress --include='**201609*/***' --exclude='*' -avzh files/ user@server.edu:/user/files
</code></pre>
<p>Here's what the file structure of the working directory on my home file looks like:</p>
<pre><code> - toplevel
- items
- files
- 20160315
- 20160910
- dir1
- really_cool_file1
- 20160911
- dir2
</code></pre>
<p>This works fine, and the file structure on <code>user@server.edu:/user/files</code> is the same as on my home computer.</p>
<hr>
<p>I wrote a python script to do this and it doesn't work. It also transfers over the <code>files/20160315</code>, which is not what I want.</p>
<pre><code> #!/usr/bin/env python3
import os
from subprocess import run
os.chdir("toplevel")
command_run = ["rsync", "-r",
"--progress",
"--include='**201609*/***'",
"--exclude='*'",
"-avzh",
"files/", "user@server.edu:/user/files"]
run(command_run, shell=False, check=True)
</code></pre>
<p>What's going on here? I had the same problem when <code>command_run</code> was a string, and I passed it to <code>subprocess.run()</code> with <code>shell=True</code>.</p>
| 1 | 2016-10-01T00:37:05Z | 39,801,965 | <p>Some of those quotes are removed by the shell before being passed to the called process. You need to do this yourself if you call the program with the default <code>shell=False</code>. This little script will tell you what your parameters need to look like</p>
<p>test.py</p>
<pre><code>#!/usr/bin/env python3
import sys
print(sys.argv)
</code></pre>
<p>And then running with your command line</p>
<pre><code>~/tmp $ ./test.py -r --progress --include='**201609*/***' --exclude='*' -avzh files/ user@server.edu:/user/files
['./test.py', '-r', '--progress', '--include=**201609*/***', '--exclude=*', '-avzh', 'files/', 'user@server.edu:/user/files']
~/tmp $
</code></pre>
| 1 | 2016-10-01T00:56:25Z | [
"python",
"python-3.x",
"rsync"
]
|
How to use the `pos` argument in `networkx` to create a flowchart-style Graph? (Python 3) | 39,801,880 | <p><strong>I am trying create a linear network graph using <code>Python</code></strong> (preferably with <code>matplotlib</code> and <code>networkx</code> although would be interested in <code>bokeh</code>) similar in concept to the one below. </p>
<p><a href="http://i.stack.imgur.com/qojHg.png"><img src="http://i.stack.imgur.com/qojHg.png" alt="enter image description here"></a></p>
<p><strong>How can this graph plot be constructed efficiently (<code>pos</code>?) in Python using <code>networkx</code>?</strong> I want to use this for more complicated examples so I feel that hard coding the positions for this simple example won't be useful :( . Does <code>networkx</code> have a solution to this? </p>
<blockquote>
<p><a href="https://networkx.github.io/documentation/development/reference/generated/networkx.drawing.nx_pylab.draw_networkx.html#networkx.drawing.nx_pylab.draw_networkx">pos (dictionary, optional) â A dictionary with nodes as keys and
positions as values. If not specified a spring layout positioning will
be computed. See networkx.layout for functions that compute node
positions.
</a></p>
</blockquote>
<p>I haven't seen any tutorials on how this can be achieved in <code>networkx</code> which is why I believe this question will be a reliable resource for the community. I've extensively gone through the <a href="https://networkx.github.io/documentation/development/tutorial/index.html"><code>networkx</code> tutorials</a> and nothing like this is on there. The layouts for <code>networkx</code> would make this type of network impossible to interpret without careful use of the <code>pos</code> argument... which I believe is my only option. <strong>None of the precomputed layouts on the <a href="https://networkx.github.io/documentation/networkx-1.9/reference/drawing.html">https://networkx.github.io/documentation/networkx-1.9/reference/drawing.html</a> documentation seem to handle this type of network structure well.</strong> </p>
<p><strong>Simple Example:</strong></p>
<p>(A) every outer key is the iteration in the graph moving from left to the right (e.g. iteration 0 represents samples, iteration 1 has groups 1 - 3, same with iteration 2, iteration 3 has Groups 1 - 2, etc.). (B) The inner dictionary contains the current grouping at that particular iteration, and the weights for the previous groups merging that represent the current group (e.g. <code>iteration 3</code> has <code>Group 1</code> and <code>Group 2</code> and for <code>iteration 4</code> all of <code>iteration 3's</code> <code>Group 2</code> has gone into <code>iteration 4's</code> <code>Group 2</code> but <code>iteration 3's</code> <code>Group 1</code> has been split up. The weights always sum to 1. </p>
<p>My code for the connections w/ weights for the plot above:</p>
<pre><code>D_iter_current_previous = {
1: {
"Group 1":{"sample_0":0.5, "sample_1":0.5, "sample_2":0, "sample_3":0, "sample_4":0},
"Group 2":{"sample_0":0, "sample_1":0, "sample_2":1, "sample_3":0, "sample_4":0},
"Group 3":{"sample_0":0, "sample_1":0, "sample_2":0, "sample_3":0.5, "sample_4":0.5}
},
2: {
"Group 1":{"Group 1":1, "Group 2":0, "Group 3":0},
"Group 2":{"Group 1":0, "Group 2":1, "Group 3":0},
"Group 3":{"Group 1":0, "Group 2":0, "Group 3":1}
},
3: {
"Group 1":{"Group 1":0.25, "Group 2":0, "Group 3":0.75},
"Group 2":{"Group 1":0.25, "Group 2":0.75, "Group 3":0}
},
4: {
"Group 1":{"Group 1":1, "Group 2":0},
"Group 2":{"Group 1":0.25, "Group 2":0.75}
}
}
</code></pre>
<p><strong>This is what happened when I made the Graph in <code>networkx</code></strong>:</p>
<pre><code>import networkx
import matplotlib.pyplot as plt
# Create Directed Graph
G = nx.DiGraph()
# Iterate through all connections
for iter_n, D_current_previous in D_iter_current_previous.items():
for current_group, D_previous_weights in D_current_previous.items():
for previous_group, weight in D_previous_weights.items():
if weight > 0:
# Define connections using `|__|` as a delimiter for the names
previous_node = "%d|__|%s"%(iter_n - 1, previous_group)
current_node = "%d|__|%s"%(iter_n, current_group)
connection = (previous_node, current_node)
G.add_edge(*connection, weight=weight)
# Draw Graph with labels and width thickness
nx.draw(G, with_labels=True, width=[G[u][v]['weight'] for u,v in G.edges()])
</code></pre>
<p><a href="http://i.stack.imgur.com/aiXnI.png"><img src="http://i.stack.imgur.com/aiXnI.png" alt="enter image description here"></a></p>
<p>Note: The only other way, I could think of to do this would be in <code>matplotlib</code> creating a scatter plot with every tick representing a iteration (5 including the initial samples) then connecting the points to each other with different weights. This would be some pretty messy code especially trying to line up the edges of the markers w/ the connections...However, I'm not sure if this and <code>networkx</code> is the best way to do it or if there is a tool (e.g. <code>bokeh</code> or <code>plotly</code>) that is designed for this type of plotting.</p>
| 11 | 2016-10-01T00:39:45Z | 39,863,493 | <p>Networkx has decent plotting facilities for exploratory data
analysis, it is not the tool to make publication quality figures,
for various reason that I don't want to go into here. I hence
rewrote that part of the code base from scratch, and made a
stand-alone drawing module called netgraph that can be found
<a href="https://github.com/paulbrodersen/netgraph">here</a> (like the original purely based on matplotlib). The API is
very, very similar and well documented, so it should not be too
hard to mold to your purposes.</p>
<p>Building on that I get the following result:</p>
<p><a href="http://i.stack.imgur.com/kjwqP.png"><img src="http://i.stack.imgur.com/kjwqP.png" alt="enter image description here"></a></p>
<p>I chose colour to denote the edge strength as you can<br>
1) indicate negative values, and<br>
2) distinguish small values better.<br>
However, you can also pass an edge width to netgraph instead (see <code>netgraph.draw_edges()</code>). </p>
<p>The different order of the branches is a result of your data structure (a dict), which indicates no inherent order. You would have to amend your data structure and the function <code>_parse_input()</code> below to fix that issue.</p>
<p>Code:</p>
<pre><code>import itertools
import numpy as np
import matplotlib.pyplot as plt
import netgraph; reload(netgraph)
def plot_layered_network(weight_matrices,
distance_between_layers=2,
distance_between_nodes=1,
layer_labels=None,
**kwargs):
"""
Convenience function to plot layered network.
Arguments:
----------
weight_matrices: [w1, w2, ..., wn]
list of weight matrices defining the connectivity between layers;
each weight matrix is a 2-D ndarray with rows indexing source and columns indexing targets;
the number of sources has to match the number of targets in the last layer
distance_between_layers: int
distance_between_nodes: int
layer_labels: [str1, str2, ..., strn+1]
labels of layers
**kwargs: passed to netgraph.draw()
Returns:
--------
ax: matplotlib axis instance
"""
nodes_per_layer = _get_nodes_per_layer(weight_matrices)
node_positions = _get_node_positions(nodes_per_layer,
distance_between_layers,
distance_between_nodes)
w = _combine_weight_matrices(weight_matrices, nodes_per_layer)
ax = netgraph.draw(w, node_positions, **kwargs)
if not layer_labels is None:
ax.set_xticks(distance_between_layers*np.arange(len(weight_matrices)+1))
ax.set_xticklabels(layer_labels)
ax.xaxis.set_ticks_position('bottom')
return ax
def _get_nodes_per_layer(weight_matrices):
nodes_per_layer = []
for w in weight_matrices:
sources, targets = w.shape
nodes_per_layer.append(sources)
nodes_per_layer.append(targets)
return nodes_per_layer
def _get_node_positions(nodes_per_layer,
distance_between_layers,
distance_between_nodes):
x = []
y = []
for ii, n in enumerate(nodes_per_layer):
x.append(distance_between_nodes * np.arange(0., n))
y.append(ii * distance_between_layers * np.ones((n)))
x = np.concatenate(x)
y = np.concatenate(y)
return np.c_[y,x]
def _combine_weight_matrices(weight_matrices, nodes_per_layer):
total_nodes = np.sum(nodes_per_layer)
w = np.full((total_nodes, total_nodes), np.nan, np.float)
a = 0
b = nodes_per_layer[0]
for ii, ww in enumerate(weight_matrices):
w[a:a+ww.shape[0], b:b+ww.shape[1]] = ww
a += nodes_per_layer[ii]
b += nodes_per_layer[ii+1]
return w
def test():
w1 = np.random.rand(4,5) #< 0.50
w2 = np.random.rand(5,6) #< 0.25
w3 = np.random.rand(6,3) #< 0.75
import string
node_labels = dict(zip(range(18), list(string.ascii_lowercase)))
fig, ax = plt.subplots(1,1)
plot_layered_network([w1,w2,w3],
layer_labels=['start', 'step 1', 'step 2', 'finish'],
ax=ax,
node_size=20,
node_edge_width=2,
node_labels=node_labels,
edge_width=5,
)
plt.show()
return
def test_example(input_dict):
weight_matrices, node_labels = _parse_input(input_dict)
fig, ax = plt.subplots(1,1)
plot_layered_network(weight_matrices,
layer_labels=['', '1', '2', '3', '4'],
distance_between_layers=10,
distance_between_nodes=8,
ax=ax,
node_size=300,
node_edge_width=10,
node_labels=node_labels,
edge_width=50,
)
plt.show()
return
def _parse_input(input_dict):
weight_matrices = []
node_labels = []
# initialise sources
sources = set()
for v in input_dict[1].values():
for s in v.keys():
sources.add(s)
sources = list(sources)
for ii in range(len(input_dict)):
inner_dict = input_dict[ii+1]
targets = inner_dict.keys()
w = np.full((len(sources), len(targets)), np.nan, np.float)
for ii, s in enumerate(sources):
for jj, t in enumerate(targets):
try:
w[ii,jj] = inner_dict[t][s]
except KeyError:
pass
weight_matrices.append(w)
node_labels.append(sources)
sources = targets
node_labels.append(targets)
node_labels = list(itertools.chain.from_iterable(node_labels))
node_labels = dict(enumerate(node_labels))
return weight_matrices, node_labels
# --------------------------------------------------------------------------------
# script
# --------------------------------------------------------------------------------
if __name__ == "__main__":
# test()
input_dict = {
1: {
"Group 1":{"sample_0":0.5, "sample_1":0.5, "sample_2":0, "sample_3":0, "sample_4":0},
"Group 2":{"sample_0":0, "sample_1":0, "sample_2":1, "sample_3":0, "sample_4":0},
"Group 3":{"sample_0":0, "sample_1":0, "sample_2":0, "sample_3":0.5, "sample_4":0.5}
},
2: {
"Group 1":{"Group 1":1, "Group 2":0, "Group 3":0},
"Group 2":{"Group 1":0, "Group 2":1, "Group 3":0},
"Group 3":{"Group 1":0, "Group 2":0, "Group 3":1}
},
3: {
"Group 1":{"Group 1":0.25, "Group 2":0, "Group 3":0.75},
"Group 2":{"Group 1":0.25, "Group 2":0.75, "Group 3":0}
},
4: {
"Group 1":{"Group 1":1, "Group 2":0},
"Group 2":{"Group 1":0.25, "Group 2":0.75}
}
}
test_example(input_dict)
pass
</code></pre>
| 6 | 2016-10-05T00:00:50Z | [
"python",
"matplotlib",
"plot",
"graph",
"networkx"
]
|
os.walk(directory) - AttributeError: 'tuple' object has no attribute 'endswith' | 39,801,970 | <p>I am trying to make a script in python to search for certain type of files (eg: <code>.txt</code>, <code>.jpg</code>, etc.). I started searching around for quite a while (including posts here in SO) and I found the following snippet of code:</p>
<pre><code>for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.txt'):
print file
</code></pre>
<p>However, I can't understand why <code>root, dirs, files</code> is used. For example, if I just use <code>for file in os.walk(directory)</code> it throws the error:</p>
<blockquote>
<p>"AttributeError: 'tuple' object has no attribute 'endswith'".</p>
</blockquote>
<p>What am I missing here?</p>
<p>Thanks in advance!</p>
| -1 | 2016-10-01T00:58:01Z | 39,802,015 | <p><code>os.walk()</code> returns a list of results, each of which is itself a tuple.</p>
<p>If you assign a single name to each result, then that name will be a tuple.</p>
<p>Tuples do not have a <code>.endswith()</code> method.</p>
| 0 | 2016-10-01T01:05:51Z | [
"python",
"python-3.5",
"os.walk",
"os.path"
]
|
os.walk(directory) - AttributeError: 'tuple' object has no attribute 'endswith' | 39,801,970 | <p>I am trying to make a script in python to search for certain type of files (eg: <code>.txt</code>, <code>.jpg</code>, etc.). I started searching around for quite a while (including posts here in SO) and I found the following snippet of code:</p>
<pre><code>for root, dirs, files in os.walk(directory):
for file in files:
if file.endswith('.txt'):
print file
</code></pre>
<p>However, I can't understand why <code>root, dirs, files</code> is used. For example, if I just use <code>for file in os.walk(directory)</code> it throws the error:</p>
<blockquote>
<p>"AttributeError: 'tuple' object has no attribute 'endswith'".</p>
</blockquote>
<p>What am I missing here?</p>
<p>Thanks in advance!</p>
| -1 | 2016-10-01T00:58:01Z | 39,802,017 | <p>The reason why you use <code>root, dirs, files</code> with <code>os.walk</code> is described in the <a href="https://docs.python.org/2/library/os.html#os.walk" rel="nofollow">docs</a>:</p>
<blockquote>
<p>For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames).</p>
</blockquote>
<p>so, using <code>root, dirs, files</code> is a Pythonic way of handling this 3-tuple yield. Otherwise, you'd have to do something like:</p>
<pre><code>data = os.walk('/')
for _ in data:
root = _[0]
dirs = _[1]
files = _[2]
</code></pre>
<p>Tuples don't have an <code>endswith</code> attribute. Strings, which may or may not be contained in the tuple, do.</p>
| 1 | 2016-10-01T01:05:57Z | [
"python",
"python-3.5",
"os.walk",
"os.path"
]
|
Kivy Image Child Class Produces Two Images | 39,801,977 | <p>I think this is probably a simple miss understanding about something deeper in kivy, but I have an RoundedImage class that is producing two images, where one is the original without rounded corners and one with the rounded corners off screen a bit. Whats going on?</p>
<p>Screenshot:
<a href="http://imgur.com/gallery/IRYfr" rel="nofollow">http://imgur.com/gallery/IRYfr</a></p>
<p>I think it may be something to do with subclassing Image?</p>
<pre><code>class RoundedImage(Image,StyleUnit):
_styleist = RadialGradientStyleist
_radius = [20]
_source = ''
_style = None
def __init__(self,**kwargs):
super(RoundedImage,self).__init__(**kwargs)
#self._source = source
#self.initalizeStyle()
with self.canvas:
StencilPush()
self.m_rect = RoundedRectangle( size = self.norm_image_size , \
pos=self.center, \
radius=self._radius)
StencilUse()
self.rect = Rectangle( size = self.norm_image_size , \
pos = self.center, \
texture = self.texture)
StencilUnUse()
StencilPop()
#Color(1,1,1)
#self.line = Line( rounded_rectangle=self.pos+self.size+self._radius,
# width=10)
self.bind(pos = self.update_rect,
size = self.update_rect)
def update_rect(self,*args):
self.m_rect.pos = self.center
self.m_rect.size = self.norm_image_size
self.rect.pos = self.center
self.rect.size = self.norm_image_size
</code></pre>
<p>The application code is simple:</p>
<pre><code>class ProfilesApp(App):
def build(self):
profile = RoundedImage( source = source,#self.imageLocation,\
allow_stretch=True)
return profile
profileApp = ProfilesApp()
profileApp.run()
</code></pre>
| 0 | 2016-10-01T00:59:31Z | 39,882,582 | <p>No imports, no other required classes and although I've seen that rounded rectangle somewhere, I don't have a clue what does that custom class do, so no runnable code. Let's work with that anyway.</p>
<p>Yes, it's because of that subclassing - the picture is already placed in the canvas and you use the texture of it which is there in <code>Rectangle(texture=<here>)</code>. Instead of that remove subclassing of the image <em>and</em> use <code>source</code> keyword argument for the <code>Rectangle</code> like this:</p>
<p><code>Rectangle(source=<path to image>)</code></p>
<p>Then again although you use <code>source</code> in your class that inherits from <code>Image</code>, you need to change that and fetch the <code>source</code> from kwargs:</p>
<p><code>self.source = kwargs.get('source')</code></p>
<p>then instead of <code>Rectangle(texture=self.texture)</code> do <code>Rectangle(source=self.source)</code></p>
| 1 | 2016-10-05T19:53:43Z | [
"python",
"image",
"canvas",
"graphics",
"kivy"
]
|
Kivy Image Child Class Produces Two Images | 39,801,977 | <p>I think this is probably a simple miss understanding about something deeper in kivy, but I have an RoundedImage class that is producing two images, where one is the original without rounded corners and one with the rounded corners off screen a bit. Whats going on?</p>
<p>Screenshot:
<a href="http://imgur.com/gallery/IRYfr" rel="nofollow">http://imgur.com/gallery/IRYfr</a></p>
<p>I think it may be something to do with subclassing Image?</p>
<pre><code>class RoundedImage(Image,StyleUnit):
_styleist = RadialGradientStyleist
_radius = [20]
_source = ''
_style = None
def __init__(self,**kwargs):
super(RoundedImage,self).__init__(**kwargs)
#self._source = source
#self.initalizeStyle()
with self.canvas:
StencilPush()
self.m_rect = RoundedRectangle( size = self.norm_image_size , \
pos=self.center, \
radius=self._radius)
StencilUse()
self.rect = Rectangle( size = self.norm_image_size , \
pos = self.center, \
texture = self.texture)
StencilUnUse()
StencilPop()
#Color(1,1,1)
#self.line = Line( rounded_rectangle=self.pos+self.size+self._radius,
# width=10)
self.bind(pos = self.update_rect,
size = self.update_rect)
def update_rect(self,*args):
self.m_rect.pos = self.center
self.m_rect.size = self.norm_image_size
self.rect.pos = self.center
self.rect.size = self.norm_image_size
</code></pre>
<p>The application code is simple:</p>
<pre><code>class ProfilesApp(App):
def build(self):
profile = RoundedImage( source = source,#self.imageLocation,\
allow_stretch=True)
return profile
profileApp = ProfilesApp()
profileApp.run()
</code></pre>
| 0 | 2016-10-01T00:59:31Z | 39,905,268 | <p>Ok so this ended up being an issue of not removing a mask in the stencil instructions.</p>
<p>I ended up adding this to the .kv definition for the RoundedRectangle</p>
<pre><code>'''
<-RoundedImage>:
canvas:
Color:
rgb: self.color
StencilPush
RoundedRectangle:
size: self.norm_image_size
pos: self.center[0] - self.norm_image_size[0]/2.0,self.center[1] - self.norm_image_size[1]/2.0
radius: self._radius
StencilUse
Rectangle:
texture: self.texture
size: self.norm_image_size
pos: self.center[0] - self.norm_image_size[0]/2.0,self.center[1] - self.norm_image_size[1]/2.0
StencilUnUse
RoundedRectangle:
size: self.norm_image_size
pos: self.center[0] - self.norm_image_size[0]/2.0,self.center[1] - self.norm_image_size[1]/2.0
radius: self._radius
StencilPop
'''
</code></pre>
| 0 | 2016-10-06T20:42:16Z | [
"python",
"image",
"canvas",
"graphics",
"kivy"
]
|
Output ascii characters to stdout in Python 3 | 39,801,978 | <p>I have a file named 'xxx.py' like this:</p>
<pre><code>print("a simple string")
</code></pre>
<p>and when I run that like this (Python 3):</p>
<pre><code>python xxx.py >atextfile.txt
</code></pre>
<p>I get a unicode file.</p>
<p>I would like an ascii file.</p>
<p>I don't mind if an exception is thrown if a non-ascii character is attempted to be printed.</p>
<p>What is a simple change I can make to my code that will output ascii characters?</p>
<p>My searches turn up solutions that all seem too verbose for such a simple problem.</p>
<p>[Edit] to report what I learned from setting LC_CTYPE:</p>
<p>I am running on windows 7.</p>
<ol>
<li>When running on the powershell commandline I get a unicode file (two bytes/character)</li>
<li>When running in a .bat file without LC_CTYPE set I get an ascii file (could be utf-8 as @jwodder pointed out).</li>
<li>When running in a .bat file with LC_CTYPE=ascii set I get presumable an ascii file (1 byte/character).</li>
</ol>
| 3 | 2016-10-01T00:59:39Z | 39,802,037 | <p>The <code>stdout</code> encoding is defined by the environment that is executing the python script, e.g.:</p>
<pre><code>$ python -c "import sys; print(sys.stdout.encoding)"
UTF-8
$ LC_CTYPE=ascii python -c "import sys; print(sys.stdout.encoding)"
US-ASCII
</code></pre>
<p>Try adjusting your environment before running the script. You can force the encoding value for Python by setting the <a href="https://docs.python.org/3.5/using/cmdline.html#envvar-PYTHONIOENCODING" rel="nofollow"><code>PYTHONIOENCODING</code></a> environment variable.</p>
| 0 | 2016-10-01T01:08:40Z | [
"python",
"windows",
"python-3.x",
"unicode",
"character-encoding"
]
|
Iterating through the Fibonacci sequence | 39,802,009 | <p>so i'd like to iterate through the Fibonacci sequence (but this could apply to any non-arithmetic sequence). i've written a function fibonacci:</p>
<pre><code>from math import sqrt
def F(n):
return ((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5))
</code></pre>
<p>which returns the fibonacci number for any given input. this bit seems to work OK. However, I'd like to include a couple of conditions, like even numbers and F(n) below a certain limit. I tried using an if loop like this:</p>
<pre><code>def ser():
count = 0
for i in F(n):
if F(n) <= 4000000 and F(n) % 2 == 0:
count = count + F(n)
</code></pre>
<p>But it seems like you can't use F(n) in the iteration for loop like I did. I'm a complete novice at python, so how would be best to use the F(n) function I created to iterate over the sequence? Thanks</p>
| 2 | 2016-10-01T01:04:10Z | 39,802,079 | <p>What is the range of <code>n</code> that you are looking to run the fibonacci number on?<br>
Your definition of fibonacci is in a closed form, so you need to give each number you want to calculate:</p>
<pre><code>import itertools
count = 0
for n in itertools.count(1):
if F(n) > 4000000:
break
if F(n) % 2 == 0:
count += F(n)
</code></pre>
<p>You can use a generator form of fibonacci and use <code>itertools.takewhile()</code> to limit the output:</p>
<pre><code>def F():
a,b = 0,1
yield b
while True:
a, b = b, a + b
yield b
count = sum(f for f in it.takewhile(lambda x: x <= 4000000, F()) if f % 2 == 0)
</code></pre>
| 0 | 2016-10-01T01:17:47Z | [
"python",
"iteration",
"sequences"
]
|
How to plot an equation with multiple variables in Python? | 39,802,010 | <p>Suppose I have a variable list z</p>
<pre><code>z = [1,2,3,4,5,6,7,8,9,10]
</code></pre>
<p>I am trying to plot the equation</p>
<pre><code>y = 1a + 2b + 3c + 4d + 5e + 6f + 7g + 8h + 9i + 10k
</code></pre>
<p>I am confused on how to plot a multi dimensional equation in python. I use the matplotlib library now. Any suggestions?</p>
| -3 | 2016-10-01T01:04:30Z | 39,802,078 | <p>Try this:</p>
<pre><code>z = [1,2,3,4,5,6,7,8,9,10]
equation="y ="
for i in range(len(z)):
if i>0:
equation=equation+" +"
equation=equation+" "+str(z[i])+chr(ord('a')+i)
print equation
</code></pre>
<p>The output is:</p>
<pre><code>y = 1a + 2b + 3c + 4d + 5e + 6f + 7g + 8h + 9i + 10j
</code></pre>
| -1 | 2016-10-01T01:17:42Z | [
"python",
"numpy",
"matplotlib"
]
|
pandas drop row based on index vs ix | 39,802,076 | <p>I'm trying to drop pandas dataframe row based on its index (not location).</p>
<p>The data frame looks like </p>
<pre><code> DO
129518 a developer and
20066 responsible for
571 responsible for
85629 responsible for
5956 by helping them
</code></pre>
<p>(FYI: "DO" is a column name)</p>
<p>I want to delete the row where its index is 571 so I did:</p>
<pre><code>df=df.drop(df.index[571])
</code></pre>
<p>then I check
df.ix[571]</p>
<p>then what the hell it's still there!</p>
<p>So I thought "ok, maybe index and ix are different!"</p>
<pre><code>In [539]: df.index[571]
17002
</code></pre>
<p>My question is</p>
<p>1) What is index? (compared to ix)</p>
<p>2) How do I delete the index row 571 using ix?</p>
| 2 | 2016-10-01T01:17:02Z | 39,802,240 | <p>You should <code>drop</code> the desired value from the index directly:</p>
<pre><code>df.drop(571, inplace=True)
</code></pre>
| 4 | 2016-10-01T01:48:10Z | [
"python",
"pandas",
"dataframe"
]
|
pandas drop row based on index vs ix | 39,802,076 | <p>I'm trying to drop pandas dataframe row based on its index (not location).</p>
<p>The data frame looks like </p>
<pre><code> DO
129518 a developer and
20066 responsible for
571 responsible for
85629 responsible for
5956 by helping them
</code></pre>
<p>(FYI: "DO" is a column name)</p>
<p>I want to delete the row where its index is 571 so I did:</p>
<pre><code>df=df.drop(df.index[571])
</code></pre>
<p>then I check
df.ix[571]</p>
<p>then what the hell it's still there!</p>
<p>So I thought "ok, maybe index and ix are different!"</p>
<pre><code>In [539]: df.index[571]
17002
</code></pre>
<p>My question is</p>
<p>1) What is index? (compared to ix)</p>
<p>2) How do I delete the index row 571 using ix?</p>
| 2 | 2016-10-01T01:17:02Z | 39,802,783 | <pre><code>df.index
</code></pre>
<p>Is the index of the dataframe. </p>
<pre><code>df.index[571]
</code></pre>
<p>Is the 571st element of the index. Then you dropped whatever that was. You didn't want positional but that's what you did. </p>
<p>Use @John Zwinck's answer</p>
| 2 | 2016-10-01T03:37:37Z | [
"python",
"pandas",
"dataframe"
]
|
Download SVG as JPEG using flask | 39,802,098 | <p>I'm trying to serve HTML page with SVG attributes on it; so as soon as I click "Create" I want to be able to download that file as .jpg instead of SVG. I looked over at multiple convertors that works with the command line for instance like this.</p>
<pre><code>os.system("rsvg-convert -h 32 save.svg > icon-32.jpg")
</code></pre>
<p>Similiary, I want to be able to click create and download the .jpg version of my file.
I'm currently trying to do this using Flask.</p>
<pre><code>without_filter = <svg viewBox="0 0 400 150" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" style="background: #40484b;">
<defs>
<!-- if you use the same shape multiple times, you put the reference here and reference it with <use> -->
<rect id="path-1" x="25" y="25" width="100" height="100"></rect>
<rect id="path-3" x="150" y="25" width="100" height="100"></rect>
<rect id="path-5" x="275" y="25" width="100" height="100"></rect>
<!-- gradient -->
<linearGradient x1="50%" y1="0%" x2="50%" y2="100%" id="gradient">
<stop stop-color="#FF8D77" offset="0%"></stop>
<stop stop-color="#FFBDB1" offset="50%"></stop>
<stop stop-color="#F4E3F6" offset="100%"></stop>
</linearGradient>
<!-- clip-path -->
<clipPath id="clip">
<circle cx="325" cy="75" r="50"></circle>
</clipPath>
<!-- filter -->
<filter x="-50%" y="-50%" width="200%" height="200%" filterUnits="objectBoundingBox" id="glow">
<feGaussianBlur stdDeviation="15" in="SourceGraphic">
<animate attributeName="stdDeviation" attributeType="XML"
begin="0s" dur="0.25s" repeatCount="indefinite"
values="15;20;15"/>
</feGaussianBlur>
</filter>
</defs>
<g fill-rule="evenodd">
<use xlink:href="#path-1" filter="url(#glow)" fill="#FF8D77" fill-opacity="0.5"></use>
<use xlink:href="#path-3" fill="url(#gradient)"></use>
<use xlink:href="#path-5" fill="#FF8D77" clip-path="url(#clip)"></use>
</g>
</svg>
</code></pre>
<p>So I'm trying to download the (html) as .jpeg as soon as the user clicks "create"
Here's my view function.</p>
<pre><code>@app.route('/filters/<filename>', methods=['GET','POST'])
def AddFiltersTag(filename):
form = AddFilterTags(request.form)
if form.validate_on_submit():
html = re.sub(r'(.*?<defs>)(.*)', r'\g<1>' + add_filter_tag + add_filter + end_tag + '\g<2>', without_filter)
save_html = open('save.svg','wb')
save_html.write(html)
os.system("rsvg-convert -h 32 save.svg > icon-32.jpg")
return download_html
</code></pre>
<p>So that function AddFilterTag gets trigged when a user clicks "Submit" at my form. but in that case I want to download, the above code simply saves the file as .svg and converts it later on using os.system, But I want to actually download the .jpg version directly. Is there a way to do that?</p>
| 0 | 2016-10-01T01:20:50Z | 39,805,224 | <p>After saving the file and converting it into an image.</p>
<p>You can directly return the file from the directory, which will give a download popup to the user.</p>
<pre><code>...
os.system("rsvg-convert -h 32 save.svg > icon-32.jpg")
return send_from_directory("/path/to/saved/image", "icon-32.jpg")
</code></pre>
<p>Be sure to import the method as follows: </p>
<pre><code>from flask import send_from_directory
</code></pre>
<p>If you're using this in production, make sure nginx or an actual web server is sending the file. You can read more at <a href="http://flask.pocoo.org/docs/0.11/api/#flask.send_from_directory" rel="nofollow">http://flask.pocoo.org/docs/0.11/api/#flask.send_from_directory</a></p>
| 0 | 2016-10-01T09:55:45Z | [
"python",
"flask",
"operating-system",
"jpeg",
"encode"
]
|
Catch links from a txt file | 39,802,143 | <p>I have a file txt, where there are severals lines... Some of these are links. My question is: How can I catch all this links and save them on another txt file? I'm a newbie.</p>
<p>I tried with this but it doesn't work:</p>
<pre><code>filee = open("myfile.txt").readlines()
out_file = open("out.txt","w")
out_file.write("")
out_file.close()
for x in filee:
if x.startswith("http"):
out_file.write(x)
print (x)
</code></pre>
| 1 | 2016-10-01T01:28:45Z | 39,802,335 | <p>You can't write to a closed file. Just move the out_file.close() at the end of your code:</p>
<pre><code>filee = open("myfile.txt").readlines()
out_file = open("out.txt","w")
out_file.write("")
for x in filee:
if x.startswith("http"):
out_file.write(x)
print (x)
out_file.close()
</code></pre>
<p>Here a cleaner version:</p>
<pre><code># open the input file (with auto close)
with open("myfile.txt") as input_file:
# open the output file (with auto close)
with open("out.txt", "w") as output_file:
# for each line of the file
for line in input_file:
# append the line to the output file if start with "http"
if line.startswith("http"):
output_file.write(line)
</code></pre>
<p>You can also combine the two with:</p>
<pre><code># open the input/output files (with auto close)
with open("myfile.txt") as input_file, open("out.txt", "w") as output_file:
# for each line of the file
for line in input_file:
# append the line to the output file if start with "http"
if line.startswith("http"):
output_file.write(line)
</code></pre>
| 4 | 2016-10-01T02:07:02Z | [
"python",
"python-3.x"
]
|
How can I delete a specific repetitive number in a list? | 39,802,166 | <p>For example I have </p>
<pre><code>[3, 4, 5, 5, 12, 13, 0, 0, 0, 8, 15, 17, 0, 0, 0]
</code></pre>
<p>I want delete just all the zeros.
Note: assume that we have an unknown number of zeros in a list that has an unknown length. </p>
| -4 | 2016-10-01T01:32:40Z | 39,802,199 | <p>List comprehensions make this easy:</p>
<pre><code>new_list = [x for x in orig_list if x != 0]
</code></pre>
<p>You can push the work to the C layer with <code>filter</code>:</p>
<pre><code># If they're all numbers, you can avoid work by using filter with None:
new_list = list(filter(None, orig_list)) # List wrapper not needed on Py2
# If falsy values that aren't numeric zero might be found, and should be kept, you'd do:
new_list = list(filter((0).__ne__, orig_list)) # List wrapper not needed on Py2
</code></pre>
| 4 | 2016-10-01T01:39:59Z | [
"python",
"list"
]
|
How does numpy handle data files with uncertainty values, e.g., 0.6499(6)? | 39,802,232 | <p>Here is a snippet of a large data set I am working with:</p>
<pre><code># p* T* P* U* P*_cs U*_cs Steps dt*
0.1 6.0 0.6499(6) -0.478(2) 0.6525 -0.452 30000 0.002
0.2 6.0 1.442(1) -0.942(2) 1.452 -0.890 30000 0.002
0.3 6.0 2.465(3) -1.376(1) 2.489 -1.298 30000 0.002
0.4 6.0 3.838(5) -1.785(3) 3.880 -1.681 20000 0.002
0.5 6.0 5.77(1) -2.131(3) 5.84 -2.000 20000 0.002
0.6 6.0 8.51(2) -2.382(5) 8.60 -2.225 20000 0.002
0.7 6.0 12.43(2) -2.501(4) 12.56 -2.318 20000 0.002
0.8 6.0 18.05(2) -2.416(4) 18.22 -2.207 20000 0.002
0.9 6.0 26.00(2) -2.058(4) 26.21 -1.823 20000 0.004
1.0 6.0 37.06(3) -1.361(6) 37.32 -1.100 20000 0.002
1.1 6.0 52.25(2) -0.216(4) 52.57 0.072 20000 0.002
1.2 6.0 72.90(5) 1.502(9) 73.28 1.816 20000 0.002
1.25 6.0 85.71(5) 2.612(8) 86.12 2.939 20000 0.002
</code></pre>
<p>Loading in this data set using <code>np.loadtxt</code> fails because of the uncertainties for the P* and U* values. Is there a built-in tool for handling this to avoid manually editing the data files? </p>
<p>I am looking at the <a href="https://pythonhosted.org/uncertainties/numpy_guide.html" rel="nofollow">uncertainties</a> package as a possible solution but I wonder if numpy already has something for this.</p>
| 0 | 2016-10-01T01:46:19Z | 39,802,254 | <p>No, there is nothing like that in NumPy. You will either need an external package (even Pandas won't do it), or you can load the columns as strings instead of numbers and process them yourself. For the string approach, the <code>str</code> methods in Pandas would be of some use, e.g. <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.split.html</a></p>
<p>All that said, it's not even clear how you would want to represent this once the data are loaded. Do you want to simply ignore the parentheses? Do you want to record the number of uncertain digits in an additional column? Both are possible, and probably easier in Pandas than NumPy.</p>
| 1 | 2016-10-01T01:50:00Z | [
"python",
"numpy",
"uncertainty"
]
|
How does numpy handle data files with uncertainty values, e.g., 0.6499(6)? | 39,802,232 | <p>Here is a snippet of a large data set I am working with:</p>
<pre><code># p* T* P* U* P*_cs U*_cs Steps dt*
0.1 6.0 0.6499(6) -0.478(2) 0.6525 -0.452 30000 0.002
0.2 6.0 1.442(1) -0.942(2) 1.452 -0.890 30000 0.002
0.3 6.0 2.465(3) -1.376(1) 2.489 -1.298 30000 0.002
0.4 6.0 3.838(5) -1.785(3) 3.880 -1.681 20000 0.002
0.5 6.0 5.77(1) -2.131(3) 5.84 -2.000 20000 0.002
0.6 6.0 8.51(2) -2.382(5) 8.60 -2.225 20000 0.002
0.7 6.0 12.43(2) -2.501(4) 12.56 -2.318 20000 0.002
0.8 6.0 18.05(2) -2.416(4) 18.22 -2.207 20000 0.002
0.9 6.0 26.00(2) -2.058(4) 26.21 -1.823 20000 0.004
1.0 6.0 37.06(3) -1.361(6) 37.32 -1.100 20000 0.002
1.1 6.0 52.25(2) -0.216(4) 52.57 0.072 20000 0.002
1.2 6.0 72.90(5) 1.502(9) 73.28 1.816 20000 0.002
1.25 6.0 85.71(5) 2.612(8) 86.12 2.939 20000 0.002
</code></pre>
<p>Loading in this data set using <code>np.loadtxt</code> fails because of the uncertainties for the P* and U* values. Is there a built-in tool for handling this to avoid manually editing the data files? </p>
<p>I am looking at the <a href="https://pythonhosted.org/uncertainties/numpy_guide.html" rel="nofollow">uncertainties</a> package as a possible solution but I wonder if numpy already has something for this.</p>
| 0 | 2016-10-01T01:46:19Z | 39,802,945 | <pre><code>In [1]: txt=b"""# p* T* P* U* P*_cs U*_cs Steps dt*
...: 0.1 6.0 0.6499(6) -0.478(2) 0.6525 -0.452 30000 0.002
...: 0.2 6.0 1.442(1) -0.942(2) 1.452 -0.890 30000 0.002
...: 0.3 6.0 2.465(3) -1.376(1) 2.489 -1.298 30000 0.002"""
In [2]: txt=txt.splitlines()
</code></pre>
<p><code>txt</code> is a file substitue (bytestring in PY3)</p>
<pre><code>In [3]: data=np.genfromtxt(txt, dtype=None, names=True)
In [4]: data
Out[4]:
array([(0.1, 6.0, b'0.6499(6)', b'-0.478(2)', 0.6525, -0.452, 30000, 0.002),
(0.2, 6.0, b'1.442(1)', b'-0.942(2)', 1.452, -0.89, 30000, 0.002),
(0.3, 6.0, b'2.465(3)', b'-1.376(1)', 2.489, -1.298, 30000, 0.002)],
dtype=[('p', '<f8'), ('T', '<f8'), ('P', 'S9'), ('U', 'S9'), ('P_cs', '<f8'), ('U_cs', '<f8'), ('Steps', '<i4'), ('dt', '<f8')])
</code></pre>
<p>'P' and 'U' are loaded as strings because they can't be parsed as numbers.</p>
<p>Now define a <code>converter</code> that strips off the <code>()</code> part (again with bytestrings)</p>
<pre><code>def rmvpar(astr):
return float(astr.split(b'(')[0])
In [9]: data=np.genfromtxt(txt, dtype=None, names=True,
converters={2:rmvpar, 3:rmvpar})
In [10]: data
Out[10]:
array([(0.1, 6.0, 0.6499, -0.478, 0.6525, -0.452, 30000, 0.002),
(0.2, 6.0, 1.442, -0.942, 1.452, -0.89, 30000, 0.002),
(0.3, 6.0, 2.465, -1.376, 2.489, -1.298, 30000, 0.002)],
dtype=[('p', '<f8'), ('T', '<f8'), ('P', '<f8'), ('U', '<f8'), ('P_cs', '<f8'), ('U_cs', '<f8'), ('Steps', '<i4'), ('dt', '<f8')])
</code></pre>
<p>Now those two fields are floats.</p>
<p>But converters can't return two numbers, so I can't keep the uncertainty this way.</p>
<p>Another approach is to pass the lines through a filter function</p>
<pre><code>def splt(astr):
strs=astr.split()
def foo(astr):
if b'(' in astr:
astr = astr.strip(b')').split(b'(')
return b','.join(astr)
return astr
return b','.join([foo(a) for a in strs])
In [26]: [splt(line) for line in txt]
Out[26]:
[b'#,p*,T*,P*,U*,P*_cs,U*_cs,Steps,dt*',
b'0.1,6.0,0.6499,6,-0.478,2,0.6525,-0.452,30000,0.002',
b'0.2,6.0,1.442,1,-0.942,2,1.452,-0.890,30000,0.002',
b'0.3,6.0,2.465,3,-1.376,1,2.489,-1.298,30000,0.002']
</code></pre>
<p>To use this I have to skip the header because the new lines have two added columns</p>
<pre><code>In [28]: data=np.genfromtxt([splt(line) for line in txt], delimiter=',',dtype=None, skip_header=1)
In [29]: data
Out[29]:
array([(0.1, 6.0, 0.6499, 6, -0.478, 2, 0.6525, -0.452, 30000, 0.002),
(0.2, 6.0, 1.442, 1, -0.942, 2, 1.452, -0.89, 30000, 0.002),
(0.3, 6.0, 2.465, 3, -1.376, 1, 2.489, -1.298, 30000, 0.002)],
dtype=[('f0', '<f8'), ('f1', '<f8'), ('f2', '<f8'), ('f3', '<i4'),
('f4', '<f8'), ('f5', '<i4'), ('f6', '<f8'), ('f7', '<f8'),
('f8', '<i4'), ('f9', '<f8')])
</code></pre>
<p>But I could modify the original <code>dtype</code> to make the 2 fields (sub)arrays:</p>
<pre><code>In [30]: dt=np.dtype([('p', '<f8'), ('T', '<f8'), ('P', '<f8',(2,)),
('U', '<f8',(2,)), ('P_cs', '<f8'), ('U_cs', '<f8'),
('Steps', '<i4'), ('dt', '<f8')])
In [31]: data = np.genfromtxt((splt(line) for line in txt), delimiter=',',dtype=dt, skip_header=1)
In [32]: data
Out[32]:
array([(0.1, 6.0, [0.6499, 6.0], [-0.478, 2.0], 0.6525, -0.452, 30000, 0.002),
(0.2, 6.0, [1.442, 1.0], [-0.942, 2.0], 1.452, -0.89, 30000, 0.002),
(0.3, 6.0, [2.465, 3.0], [-1.376, 1.0], 2.489, -1.298, 30000, 0.002)],
dtype=[('p', '<f8'), ('T', '<f8'), ('P', '<f8', (2,)), ('U', '<f8', (2,)),
('P_cs', '<f8'), ('U_cs', '<f8'), ('Steps', '<i4'), ('dt', '<f8')])
</code></pre>
<p>Such a field would look like:</p>
<pre><code>In [33]: data['P']
Out[33]:
array([[ 0.6499, 6. ],
[ 1.442 , 1. ],
[ 2.465 , 3. ]])
</code></pre>
<p>I could define other <code>dtypes</code>, just as long as the number of fields match.</p>
<p>With a file, rather than these text lines, I would use something like (not tested):</p>
<pre><code>with open(filename,'wb') as f:
data = np.genfromtxt((splt(line) for line in f),...
</code></pre>
<p>Here, and above, I'm using the generator expression <code>(splt(line) for line in x)</code>, though the list comprehension would be fine. Any code that opens the file and yields/returns the modified lines will work.</p>
| 2 | 2016-10-01T04:11:50Z | [
"python",
"numpy",
"uncertainty"
]
|
Overriding a class to be left hand side of in operator | 39,802,249 | <p>Apparently the <code>__contains__</code> special method allows to implement the <code>in</code> evaulation when the object with the method is on the right hand side of it. I have a piece of code where the <code>in</code> must be implemented by the left hand operand. How do I go about it?</p>
| 1 | 2016-10-01T01:49:41Z | 39,802,759 | <p>I was able to get this to work by overriding eq (how do you put underscores in the text?).</p>
<p>Consider the code "value in some_list". It will iterate through some_list until it finds value. But how does it know if it found value? By comparing it. That's what you want to override.</p>
<pre><code>class Twenty(object):
def __init__(self):
self.x = 20
def __eq__(self, y):
print "comparing", self.x, "to", y
return self.x == y
value = Twenty()
assert value in [10, 20, 30]
assert value not in [1, 2, 3]
</code></pre>
<p>output</p>
<pre><code>comparing 20 to 10
comparing 20 to 20
comparing 20 to 1
comparing 20 to 2
comparing 20 to 3
</code></pre>
| 1 | 2016-10-01T03:33:11Z | [
"python",
"contains"
]
|
Print Final Statement Outside For Loop | 39,802,259 | <p>I'm trying to print a final statement that says "The 50th bus arrives at HH:MM." But it appears my print statement is still in my for loop. How do I get it out of it? Also, it seems like my output is still in brackets. I'm not sure how to get rid of that. Sorry, I'm very new to programming.</p>
<pre><code>import numpy as np
import math
import random
l=[]
for i in range (50):
def nextTime(rateParameter):
return -math.log(1.0 - random.random()) / rateParameter
a = np.round(nextTime(1/15),0)
l.append(a)
cum_l = np.cumsum(l)
print(cum_l)
print("The 50th bus arrives at ", cum_l//60,":", cum_l%60,2)
</code></pre>
| 0 | 2016-10-01T01:50:24Z | 39,802,552 | <p><code>Print</code> is not in <code>for</code> loop. The reason you think that your <code>print</code> is in <code>for</code> loop is because you print <code>cum_l</code> which is a <code>list</code>. But you need only last element:</p>
<pre><code>import numpy as np
import math
import random
rateParameter = 1/15
def nextTime(rateParameter):
return -math.log(1.0 - random.random()) / rateParameter
l=[]
for i in range (50):
a = np.round(nextTime(rateParameter), 0)
l.append(a)
cum_l = np.cumsum(l)
#print(cum_l)
output = ""
last = len(cum_l) - 1
output += str(cum_l[-1]//60) + ":" + str(cum_l[-1]%60)
print("The 50th bus arrives at: ", output)
</code></pre>
| 0 | 2016-10-01T02:52:19Z | [
"python",
"python-3.x"
]
|
Print Value of Key in Lists of Dicts in Python | 39,802,429 | <p>I am trying to print the value of a specific key in a list of dicts:</p>
<p>eg:</p>
<pre><code>list = [{'a' : 123, 'b': 'xyz', 'c': [1,2]}, {'a' : 456, 'b': 'cde', 'c': [3,4]}]
</code></pre>
<p>I was hoping to be able to print the following for each dict:</p>
<pre><code>print ("a: ", a)
print ("b: ", b)
</code></pre>
| 0 | 2016-10-01T02:29:14Z | 39,802,454 | <p>If you're guaranteed those keys exist, a nice solution using <a href="https://docs.python.org/3/library/operator.html#operator.itemgetter" rel="nofollow"><code>operator.itemgetter</code></a>:</p>
<pre><code>from operator import itemgetter
# Renamed your list; don't name variables list
for a, b in map(itemgetter('a', 'b'), mylist):
print("a:", a)
print("b:", b)
</code></pre>
<p>The above is just a slightly optimized version of the import free code, pushing the work of fetching values to the builtins instead of doing it over and over yourself.</p>
<pre><code>for d in mylist: # Renamed your list; don't name variables list
print("a:", d['a'])
print("b:", d['b'])
</code></pre>
<p>Oh, and for completeness (Aaron Hall is right that it's nice to avoid redundant code), a tweak to <code>itemgetter</code> usage to observe DRY rules:</p>
<pre><code>keys = ('a', 'b')
for values in map(itemgetter(*keys), mylist):
for k, v in zip(keys, values):
print(k, v, sep=": ")
</code></pre>
| 1 | 2016-10-01T02:34:02Z | [
"python",
"dictionary"
]
|
Print Value of Key in Lists of Dicts in Python | 39,802,429 | <p>I am trying to print the value of a specific key in a list of dicts:</p>
<p>eg:</p>
<pre><code>list = [{'a' : 123, 'b': 'xyz', 'c': [1,2]}, {'a' : 456, 'b': 'cde', 'c': [3,4]}]
</code></pre>
<p>I was hoping to be able to print the following for each dict:</p>
<pre><code>print ("a: ", a)
print ("b: ", b)
</code></pre>
| 0 | 2016-10-01T02:29:14Z | 39,802,495 | <p>How about some nested loops, to avoid hard-coding it?</p>
<pre><code>for dictionary in list: # rename list so you don't overshadow the builtin list
for key in ('a', 'b'):
print(key + ':', dictionary[key])
</code></pre>
<p>which should output:</p>
<pre><code>a: 123
b: xyz
a: 456
b: cde
</code></pre>
| 0 | 2016-10-01T02:41:50Z | [
"python",
"dictionary"
]
|
Print Value of Key in Lists of Dicts in Python | 39,802,429 | <p>I am trying to print the value of a specific key in a list of dicts:</p>
<p>eg:</p>
<pre><code>list = [{'a' : 123, 'b': 'xyz', 'c': [1,2]}, {'a' : 456, 'b': 'cde', 'c': [3,4]}]
</code></pre>
<p>I was hoping to be able to print the following for each dict:</p>
<pre><code>print ("a: ", a)
print ("b: ", b)
</code></pre>
| 0 | 2016-10-01T02:29:14Z | 39,802,585 | <pre><code>lst = [{'a' : 123, 'b': 'xyz', 'c': [1,2]}, {'a' : 456, 'b': 'cde', 'c': [3,4]}]
output=['a','b']
for dct in lst:
for k in output:
print(k+': '+str(dct[k]))
</code></pre>
| 0 | 2016-10-01T02:57:25Z | [
"python",
"dictionary"
]
|
Storing Dataframe with Array Entries | 39,802,438 | <p>I have a Pandas DataFrame with the following structure, which contains both numbers and numpy arrays of fixed shape:</p>
<pre><code>import pandas as pd
import numpy as np
df = pd.DataFrame({"num":(23, 42), "list":(np.arange(3), np.arange(1,4))
</code></pre>
<p>Assuming I have large (more than 1 GB) amounts of this data that I would like to store and retrieve quickly, how should I go about storing it? If I use HDF5, the Numpy array gets pickled which will affect the ability to retrieve the data quickly. Is there some way to tell HDF5 how to store Numpy arrays? Alternatively, should I not be using HDF5 at all?</p>
<p>The following GitHub thread seems to suggest the following:</p>
<ol>
<li>Create a function that gets the desired Numpy array, which is stored in some other format <a href="https://github.com/pydata/pandas/issues/3032#issuecomment-15016217" rel="nofollow">[1]</a></li>
<li>Create a class to inform HDF5 <a href="https://github.com/pydata/pandas/issues/3032#issuecomment-15016217" rel="nofollow">[2]</a></li>
</ol>
<p>Both of these solutions seem oddly specific for how common I imagine this problem to be. Are there more general approaches? Am I just using the wrong tool?</p>
| 2 | 2016-10-01T02:31:26Z | 39,802,541 | <p>I mean something like this:</p>
<pre><code>df_x = pd.concat([df.num, pd.DataFrame(np.vstack(df.list))],
keys=["key", "arr"], axis=1)
</code></pre>
<p>the dataframe:</p>
<pre><code> key arr
num 0 1 2
0 23 0 1 2
1 42 1 2 3
</code></pre>
<hr>
<p>convert back with:</p>
<pre><code>pd.concat([df_x.key, pd.Series(tuple(df_x.arr.values), name='list')], axis=1)
num list
0 23 [0, 1, 2]
1 42 [1, 2, 3]
</code></pre>
| 3 | 2016-10-01T02:50:13Z | [
"python",
"pandas",
"numpy",
"serialization"
]
|
How to multiply a certain integer in list? | 39,802,442 | <p>I am very new to Python... If I were to give a list, my function should return the number of times "5" appears times 50. For example, if I were to call fivePoints([1,3,5,5]) it should return 100 since the number 5 appears twice (2*50). Is creating an empty list necessary? Do I use the count function? This is what I have but I'm probably way off. </p>
<pre><code> def fivePoints(aList):
for i in aList:
i.count(5*50)
return aList
</code></pre>
| 0 | 2016-10-01T02:31:49Z | 39,802,480 | <p>This is one option:</p>
<pre><code>x = [1, 2, 5, 5]
def fivePoints(aList):
y = [i for i in aList if i == 5]
z = len(y) * 50
return z
fivePoints(x)
100
</code></pre>
| 0 | 2016-10-01T02:39:04Z | [
"python",
"list",
"arguments"
]
|
How to multiply a certain integer in list? | 39,802,442 | <p>I am very new to Python... If I were to give a list, my function should return the number of times "5" appears times 50. For example, if I were to call fivePoints([1,3,5,5]) it should return 100 since the number 5 appears twice (2*50). Is creating an empty list necessary? Do I use the count function? This is what I have but I'm probably way off. </p>
<pre><code> def fivePoints(aList):
for i in aList:
i.count(5*50)
return aList
</code></pre>
| 0 | 2016-10-01T02:31:49Z | 39,802,481 | <p>You want to return a number. You just have to write:</p>
<pre><code>def fivePoints(aList):
return aList.count(5)*50
print(fivePoints([1,3,5,5]))
</code></pre>
| 3 | 2016-10-01T02:39:23Z | [
"python",
"list",
"arguments"
]
|
Python: Check if Twitter user A following user B | 39,802,469 | <p>I have been trying to use either Tweepy or Twython with the Twitter API to search for a specific hashtag, extract usernames of users tweeting with the hashtage, and then see how many of those users follow one another. My ultimate goal is to then visualize the connections with NetworkX.</p>
<p>So far, I have been able to search for the hashtag and get a list of users tweeting with it. However, I can't figure out how to see who is following whom on that list. I finally got a friendship lookup to work, but then realized that that parameter only searches friends of the authenticated user (me).</p>
<p>Here is the latest version of the code:</p>
<pre><code>from twython import Twython
import tweepy
# fill these in from Twitter API Dev
CONSUMER_KEY = ''
CONSUMER_SECRET = ''
ACCESS_KEY = ''
ACCESS_SECRET = ''
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True)
twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
# Search for hashtag, limit number of users
try:
search_results = twitter.search(q='energy', count=5)
except TwythonError as e:
print e
test5 = []
for tweet in search_results['statuses']:
if tweet['user']['screen_name'] not in test5:
test5.append((tweet['user']['screen_name']).encode('utf-8'))
print test5
# Lookup friendships
relationships = api.lookup_friendships(screen_names=test5[0:5])
for relationship in relationships:
if relationship.is_following:
print("User is following", relationship.screen_name)
</code></pre>
<p>Thanks!</p>
| 0 | 2016-10-01T02:36:31Z | 39,803,142 | <p>With Tweepy, you can check if <code>user_a</code> follows <code>user_b</code> using the <a href="http://tweepy.readthedocs.io/en/v3.5.0/api.html#API.exists_friendship" rel="nofollow">API.exists_friendship</a> method. The code would look something like:</p>
<pre><code>auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True)
is_following = api.exists_friendship(user_a, user_b)
</code></pre>
<p>You can specify users by id or screenname.</p>
<p>Alternatively, you can fetch the entire list of followers using the <a href="http://tweepy.readthedocs.io/en/v3.5.0/api.html#API.followers_ids" rel="nofollow">API.followers_ids</a> method:</p>
<pre><code>auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth, wait_on_rate_limit=True)
user_b_followers = api.followers_ids(user_b)
is_following = user_a in user_b_followers
</code></pre>
<p>This approach would make more sense for large networks of users.</p>
<p>Keep in mind that, for either approach, you will only be able to see friendships that are visible to the authenticated user. This is a restriction put in place by Twitter for privacy reasons.</p>
| 1 | 2016-10-01T04:48:52Z | [
"python",
"twitter",
"tweepy",
"twython"
]
|
Cannot parse the following text file into a pandas dataframe? | 39,802,476 | <p>I have the following text file <code>file1.txt</code> in this format (showing it exactly as I see it):</p>
<pre><code> 3612 11.4 21.5 1.3 cat3 10469 11447 9239174 - Smith David
484 25.1 13.2 0.0 cat3 11505 11675 9238946 - John Mary
239 29.4 1.9 1.0 cat3 11678 11780 9238841 + Weiz Parker
318 23.0 3.7 0.0 cat3 15265 15355 9235266 + Cohen Charles
18 23.2 0.0 2.0 cat3 15798 15849 9234772 + Lopez Beth
463 1.3 0.6 1.7 cat3 10001 10468 9240153 + Brown Charlie
</code></pre>
<p>I wanted to immediately load this into a Pandas DataFrame with </p>
<pre><code>import pandas as pd
df = pd.DataFrame("file1.txt")
</code></pre>
<p>But this gives me a dataframe with only one column. </p>
<p>So, I tried to parse this file into a <code>.csv</code> with Python. The problem is that this isn't a "constant" delimiter, i.e. it's not a tab. </p>
<pre><code>import csv
input_text = csv.reader(open("file1.txt", "r"), delimiter = "\t")
output_csv = csv.writer(open("file1.csv", 'w'))
output_csv.writerows(input_text) # this should write a csv "file1.csv"
</code></pre>
<p>However, this gives the same results. The delimiter <code>delimiter = ""</code> also doesn't work. </p>
<p>How can I parse this text file into csv format? Can I do this with Python? (or do I need awk?) Should I be "skipping" the intermediary csv step and try to do this entirely in pandas? </p>
<p>Any help appreciated!</p>
| 2 | 2016-10-01T02:37:38Z | 39,802,521 | <p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html" rel="nofollow">pd.read_csv()</a> with a separator and specify the column names and also specify that there are no column headers already included in the csv file.</p>
<pre><code>In [24]: pd.read_csv("file1.txt", header=None, names=[chr(i) for i in range(65, 75)], sep="\s+")
Out[24]:
A B C D E F G H I J
3612 11.4 21.5 1.3 cat3 10469 11447 9239174 - Smith David
484 25.1 13.2 0.0 cat3 11505 11675 9238946 - John Mary
239 29.4 1.9 1.0 cat3 11678 11780 9238841 + Weiz Parker
318 23.0 3.7 0.0 cat3 15265 15355 9235266 + Cohen Charles
18 23.2 0.0 2.0 cat3 15798 15849 9234772 + Lopez Beth
463 1.3 0.6 1.7 cat3 10001 10468 9240153 + Brown Charlie
</code></pre>
| 2 | 2016-10-01T02:47:03Z | [
"python",
"csv",
"pandas",
"awk",
"dataframe"
]
|
How to study python to take part in GSoC? | 39,802,513 | <p>I'm new to python. I have learnt the basics from learnpythonthehardway.org/book and now I'm unable to understand the codes and libraries method of my favorite projects on github. </p>
<p>What should I do now in step by step manner so that I become capable enough to contribute and hence take part in GSoC no matter how much time it takes?
Some says I should practise python questions on hackerrank and other says I should work on my own project and learn from it. Which should I follow?</p>
| -1 | 2016-10-01T02:45:22Z | 39,802,549 | <p>If you are just trying to learn Python I know YouTube has a lot of fantastic resources. Since you've already read <em>Learn Python the Hard Way</em>, I would suggest you look for YouTube videos where the host is creating a project (Look for something which interests you), and follow along until you come across something you don't know. Research it, rinse and repeat. As a bonus, you'll end up with some neat Python projects in the end, too.</p>
<p>Another great way to get some Python experience is to find different sources of tutorials. I learned Python from Codecademy, but there are plenty out there.</p>
<p>However, all said, there is simply nothing like figuring things out yourself. Set a goal - think of a project to create - and get as far as you can, and look for as many opportunities to learn as possible. That's my favorite way to learn.</p>
<p>Good luck! :)</p>
| 2 | 2016-10-01T02:51:57Z | [
"python"
]
|
How to study python to take part in GSoC? | 39,802,513 | <p>I'm new to python. I have learnt the basics from learnpythonthehardway.org/book and now I'm unable to understand the codes and libraries method of my favorite projects on github. </p>
<p>What should I do now in step by step manner so that I become capable enough to contribute and hence take part in GSoC no matter how much time it takes?
Some says I should practise python questions on hackerrank and other says I should work on my own project and learn from it. Which should I follow?</p>
| -1 | 2016-10-01T02:45:22Z | 39,802,713 | <p>As mentioned by @Dylan, YouTube hosts a lot of Python tutorials which are helpful for learning more about Python.</p>
<p>Additionally, I would invest your time in reading some eBooks. They have a wealth of knowledge that can expand your horizons beyond learning the basics of Python and personally I found it to be a huge help in understanding the language. Read these and take some good notes.</p>
<ul>
<li><em>Python Cookbook (Second or Third Edition)</em> by David Beazley </li>
<li><em>Automate
the Boring Stuff With Python</em> by Al Sweigart</li>
<li><em>A Byte of Python</em> by
Swaroop C.H.</li>
<li><p><em>Test-Driven Development with Python</em> by Henry Percival</p></li>
<li><p><em>Real Python for the Web</em> by Michael Herman</p></li>
</ul>
<p>Good luck and happy coding! </p>
| 0 | 2016-10-01T03:24:40Z | [
"python"
]
|
Making Python go a webpage that has a lot of links, scraping each link and seeing if they have a specific piece of text | 39,802,626 | <p><strong>I have a question pertaining to Python that I hope can be remedied.</strong>
I'm not asking to be spoonfed, but any advice will be extremely helpful. </p>
<p>I'm working on a mini-project of sorts where I "crawl" the WW1 Database of Canadian Soldiers who died and seeing which pages lack info. </p>
<p><a href="http://www.canadaatwar.ca/memorial/world-war-i/" rel="nofollow">http://www.canadaatwar.ca/memorial/world-war-i/</a></p>
<p>I'm trying to make Python go to each soldiers page, and seeing if the "biography" section is empty. </p>
<p>This is my code (not mine, I'll give credit and link the original page later) so far. It's very messy, and it may make senior developers tear their hair out in frustration, but bear with me.</p>
<pre><code>import requests
from bs4 import BeautifulSoup
import time
url_to_scrape = 'http://www.canadaatwar.ca/memorial/world-war-i/'
r = requests.get(url_to_scrape)
soup = BeautifulSoup(r.text)
soldier_links = []
for table_row in soup.select(".soldierslist tr"):
table_cells = table_row.findAll('td')
if len(table_cells) > 0:
relative_link_to_soldier_details = table_cells[0].find('a')['href']
absolute_link_to_soldier_details = url_to_scrape + relative_link_to_soldier_details
soldier_links.append(absolute_link_to_soldier_details)
inmates = []
r = requests.get(soldier_link)
soup = BeautifulSoup(r.text)
soldier_details = {}
soldier_profile_rows = soup.select("#soldierProfile tr")
soldier_details['additional text information is avalable on this individual just yet. If you have more information please'] = soldier_profile_rows[0].findAll('td')[0].text.strip()
soldiers.append(soldier_details)
</code></pre>
<p>It would be great to know how to make Python go to the next page once it's done scraping everything from the page it's scraping, and making Python print only the links that have information in the biography section. </p>
| 0 | 2016-10-01T03:07:33Z | 39,802,891 | <p>I would like suggest you use Scrapy Framework. In building scrapy spiders, </p>
<ol>
<li>You can specify how to start request, e.g., the simplest way by setting <code>start_urls</code> or overwrite function <code>start_request</code></li>
<li>You can specify how to parse response. Here you can do the xpath selection, if the condition is satisfied, yield the result as items and at same time yield a new request (in this way, you are following the next request).</li>
</ol>
<p>Hope this would be helpful.</p>
| 0 | 2016-10-01T04:01:49Z | [
"python"
]
|
TypeError for Python program (string formatting with %d) | 39,802,699 | <p>My program: A Math Quiz that prompts a user for a choice of difficulty (Beginner, Intermediate, Advanced) and then generates five questions (with random #'s) depending on their choice.</p>
<p>It was working completely fine until I started adding the comments and doc strings (I apologize if it's hard to read with the mess, instructor requires an exorbitant amount of comments.)</p>
<p>I apologize in advance for the messiness of the code (the instructor wants an exorbitant amount of comments).</p>
<pre><code># Import randint so program can generate random numbers
from random import randint
'''
Set the variable choice equal to the users input for choosing which level
they want to do. Then, we created an if statement equal to beginner
(for user's input). The range is the amount of questions for that
particular type of problem (addition, multiplication, etc.)
n1 is a random number from the range 1 to 10, program picks two
The variable 'sum' is set to the value n1 plus n2
'''
choice = input("Choose Level: Beginner,Intermediate, or Advanced?").lower()
if choice == "beginner":
correct = 0
for i in range(2):
n1 = randint(1, 10)
n2 = randint(1, 10)
# Set variable 'ans' to the input "What is (n1) plus (n2)"
# %d = program generates a random number for the problem
# correct = correct + 1 -> adds one point to the user's overall score
ans = input("What's %d plus %d?" % (n1, n2))
if int(ans) == sum:
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No it's not correct. The answer is %d.\n" % sum) ## < Here is where I'm getting the error message.**
for i in range(3):
n1 = randint(1, 10)
n2 = randint(1, 10)
difference = n1 - n2
ans = input("What's %d minus %d?" % (n1, n2))
if int(ans) == difference:
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No, that's not correct. The answer is %d.\n" % difference)
# This is where the program calculates the score, and tells the user
# "Well Done", "Need more practice" or "Ask teacher for help".
if(correct/5 >= 2/3):
print("Well done!")
elif(correct/5 >= 1/3):
print("You need more practice.")
else:
print("Contact the instructor.")
if choice == "intermediate":
correct = 0
for i in range(3):
n1 = randint(1, 25)
n2 = randint(1, 25)
product = n1 * n2
ans = input("What's %d times %d?" % (n1, n2))
if int(ans) == product:
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No, that's not correct. The answer is %d.\n" % product)
for i in range(2):
n1 = randint(1, 25)
n2 = randint(1, 25)
quotient = n1 / n2
# For this section, we had to use a float input type and 'round' so that
# the program will take in a decimal point, and tell the user to round.
ans = float(input("What's %d divided by %d? (Round 2 decimal places)" \
% (n1, n2)))
if round(ans, 2) == round(quotient, 2):
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No, that's not correct. The answer is %f.\n" % quotient)
if(correct/5 >= 2/3):
print("Well done!")
elif(correct/5 >= 1/3):
print("You need more practice.")
else:
print("Contact the instructor.")
if choice == "advanced":
correct = 0
for i in range(3):
n1 = randint(11, 20)
n2 = randint(1, 10)
modulus = n1 % n2
ans = input("What's %d modulus %d?" % (n1, n2))
if int(ans) == modulus:
print("That's correct, well done!\n")
else:
print("No, that's not correct. The answer is %d.\n" % modulus)
for i in range(2):
n1 = randint(1, 10)
n2 = randint(1, 10)
exponent = n1 ** n2
ans = input("What's %d to the power of %d? \
Don't need commas for answers)" % (n1, n2))
if int(ans) == exponent:
print("That's correct, well done!\n")
else:
print("No, that's not correct. The answer is %d.\n" % exponent)
if(correct/5 >= 2/3):
print("Well done!")
elif(correct/5 >= 1/3):
print("You need more practice.")
else:
print("Contact the instructor.")
</code></pre>
<p>I'm getting this type error (on the first else print statement):</p>
<p><a href="http://i.stack.imgur.com/KwJpK.png" rel="nofollow"><img src="http://i.stack.imgur.com/KwJpK.png" alt="enter image description here"></a></p>
<p>I'm not sure if I messed something up when I added the comments, but I can't seem to figure out what it is.</p>
| -1 | 2016-10-01T03:21:22Z | 39,802,745 | <p>You are using <code>sum</code> as a variable name, but that shadows a builtin function <a href="https://docs.python.org/2/library/functions.html#sum" rel="nofollow"><code>sum</code></a>. Change your variable name to something else and the error will go away.</p>
<p>With <code>if int(ans) == sum:</code>, all you are doing is comparing <code>int(ans)</code> to the <code>sum</code> function itself, rather than the result it returns when passed some numbers. You want to do something like <code>if int(ans) == sum(n1, n2):</code>. What you should probably do instead though, is save this sum to a variable (not named <code>sum</code>, and then replace all your <code>sum</code>s with it. For example:</p>
<pre><code>_sum = sum(n1, n2)
...
if int(ans) == _sum:
...
print("No it's not correct. The answer is %d.\n" % _sum)
</code></pre>
| 0 | 2016-10-01T03:29:11Z | [
"python",
"typeerror",
"modulus"
]
|
TypeError for Python program (string formatting with %d) | 39,802,699 | <p>My program: A Math Quiz that prompts a user for a choice of difficulty (Beginner, Intermediate, Advanced) and then generates five questions (with random #'s) depending on their choice.</p>
<p>It was working completely fine until I started adding the comments and doc strings (I apologize if it's hard to read with the mess, instructor requires an exorbitant amount of comments.)</p>
<p>I apologize in advance for the messiness of the code (the instructor wants an exorbitant amount of comments).</p>
<pre><code># Import randint so program can generate random numbers
from random import randint
'''
Set the variable choice equal to the users input for choosing which level
they want to do. Then, we created an if statement equal to beginner
(for user's input). The range is the amount of questions for that
particular type of problem (addition, multiplication, etc.)
n1 is a random number from the range 1 to 10, program picks two
The variable 'sum' is set to the value n1 plus n2
'''
choice = input("Choose Level: Beginner,Intermediate, or Advanced?").lower()
if choice == "beginner":
correct = 0
for i in range(2):
n1 = randint(1, 10)
n2 = randint(1, 10)
# Set variable 'ans' to the input "What is (n1) plus (n2)"
# %d = program generates a random number for the problem
# correct = correct + 1 -> adds one point to the user's overall score
ans = input("What's %d plus %d?" % (n1, n2))
if int(ans) == sum:
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No it's not correct. The answer is %d.\n" % sum) ## < Here is where I'm getting the error message.**
for i in range(3):
n1 = randint(1, 10)
n2 = randint(1, 10)
difference = n1 - n2
ans = input("What's %d minus %d?" % (n1, n2))
if int(ans) == difference:
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No, that's not correct. The answer is %d.\n" % difference)
# This is where the program calculates the score, and tells the user
# "Well Done", "Need more practice" or "Ask teacher for help".
if(correct/5 >= 2/3):
print("Well done!")
elif(correct/5 >= 1/3):
print("You need more practice.")
else:
print("Contact the instructor.")
if choice == "intermediate":
correct = 0
for i in range(3):
n1 = randint(1, 25)
n2 = randint(1, 25)
product = n1 * n2
ans = input("What's %d times %d?" % (n1, n2))
if int(ans) == product:
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No, that's not correct. The answer is %d.\n" % product)
for i in range(2):
n1 = randint(1, 25)
n2 = randint(1, 25)
quotient = n1 / n2
# For this section, we had to use a float input type and 'round' so that
# the program will take in a decimal point, and tell the user to round.
ans = float(input("What's %d divided by %d? (Round 2 decimal places)" \
% (n1, n2)))
if round(ans, 2) == round(quotient, 2):
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No, that's not correct. The answer is %f.\n" % quotient)
if(correct/5 >= 2/3):
print("Well done!")
elif(correct/5 >= 1/3):
print("You need more practice.")
else:
print("Contact the instructor.")
if choice == "advanced":
correct = 0
for i in range(3):
n1 = randint(11, 20)
n2 = randint(1, 10)
modulus = n1 % n2
ans = input("What's %d modulus %d?" % (n1, n2))
if int(ans) == modulus:
print("That's correct, well done!\n")
else:
print("No, that's not correct. The answer is %d.\n" % modulus)
for i in range(2):
n1 = randint(1, 10)
n2 = randint(1, 10)
exponent = n1 ** n2
ans = input("What's %d to the power of %d? \
Don't need commas for answers)" % (n1, n2))
if int(ans) == exponent:
print("That's correct, well done!\n")
else:
print("No, that's not correct. The answer is %d.\n" % exponent)
if(correct/5 >= 2/3):
print("Well done!")
elif(correct/5 >= 1/3):
print("You need more practice.")
else:
print("Contact the instructor.")
</code></pre>
<p>I'm getting this type error (on the first else print statement):</p>
<p><a href="http://i.stack.imgur.com/KwJpK.png" rel="nofollow"><img src="http://i.stack.imgur.com/KwJpK.png" alt="enter image description here"></a></p>
<p>I'm not sure if I messed something up when I added the comments, but I can't seem to figure out what it is.</p>
| -1 | 2016-10-01T03:21:22Z | 39,802,750 | <p>You use a variable called <code>sum</code> but don't define it. Python has a builtin function called <code>sum</code> - and you really should change your variable name so you don't get this type of problem - and python tried using that function for the <code>%d</code> calculation. Rename it <code>my_sum</code> and you'll get a different error saying its not defined. Then you can fix that!</p>
| 0 | 2016-10-01T03:30:20Z | [
"python",
"typeerror",
"modulus"
]
|
TypeError for Python program (string formatting with %d) | 39,802,699 | <p>My program: A Math Quiz that prompts a user for a choice of difficulty (Beginner, Intermediate, Advanced) and then generates five questions (with random #'s) depending on their choice.</p>
<p>It was working completely fine until I started adding the comments and doc strings (I apologize if it's hard to read with the mess, instructor requires an exorbitant amount of comments.)</p>
<p>I apologize in advance for the messiness of the code (the instructor wants an exorbitant amount of comments).</p>
<pre><code># Import randint so program can generate random numbers
from random import randint
'''
Set the variable choice equal to the users input for choosing which level
they want to do. Then, we created an if statement equal to beginner
(for user's input). The range is the amount of questions for that
particular type of problem (addition, multiplication, etc.)
n1 is a random number from the range 1 to 10, program picks two
The variable 'sum' is set to the value n1 plus n2
'''
choice = input("Choose Level: Beginner,Intermediate, or Advanced?").lower()
if choice == "beginner":
correct = 0
for i in range(2):
n1 = randint(1, 10)
n2 = randint(1, 10)
# Set variable 'ans' to the input "What is (n1) plus (n2)"
# %d = program generates a random number for the problem
# correct = correct + 1 -> adds one point to the user's overall score
ans = input("What's %d plus %d?" % (n1, n2))
if int(ans) == sum:
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No it's not correct. The answer is %d.\n" % sum) ## < Here is where I'm getting the error message.**
for i in range(3):
n1 = randint(1, 10)
n2 = randint(1, 10)
difference = n1 - n2
ans = input("What's %d minus %d?" % (n1, n2))
if int(ans) == difference:
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No, that's not correct. The answer is %d.\n" % difference)
# This is where the program calculates the score, and tells the user
# "Well Done", "Need more practice" or "Ask teacher for help".
if(correct/5 >= 2/3):
print("Well done!")
elif(correct/5 >= 1/3):
print("You need more practice.")
else:
print("Contact the instructor.")
if choice == "intermediate":
correct = 0
for i in range(3):
n1 = randint(1, 25)
n2 = randint(1, 25)
product = n1 * n2
ans = input("What's %d times %d?" % (n1, n2))
if int(ans) == product:
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No, that's not correct. The answer is %d.\n" % product)
for i in range(2):
n1 = randint(1, 25)
n2 = randint(1, 25)
quotient = n1 / n2
# For this section, we had to use a float input type and 'round' so that
# the program will take in a decimal point, and tell the user to round.
ans = float(input("What's %d divided by %d? (Round 2 decimal places)" \
% (n1, n2)))
if round(ans, 2) == round(quotient, 2):
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No, that's not correct. The answer is %f.\n" % quotient)
if(correct/5 >= 2/3):
print("Well done!")
elif(correct/5 >= 1/3):
print("You need more practice.")
else:
print("Contact the instructor.")
if choice == "advanced":
correct = 0
for i in range(3):
n1 = randint(11, 20)
n2 = randint(1, 10)
modulus = n1 % n2
ans = input("What's %d modulus %d?" % (n1, n2))
if int(ans) == modulus:
print("That's correct, well done!\n")
else:
print("No, that's not correct. The answer is %d.\n" % modulus)
for i in range(2):
n1 = randint(1, 10)
n2 = randint(1, 10)
exponent = n1 ** n2
ans = input("What's %d to the power of %d? \
Don't need commas for answers)" % (n1, n2))
if int(ans) == exponent:
print("That's correct, well done!\n")
else:
print("No, that's not correct. The answer is %d.\n" % exponent)
if(correct/5 >= 2/3):
print("Well done!")
elif(correct/5 >= 1/3):
print("You need more practice.")
else:
print("Contact the instructor.")
</code></pre>
<p>I'm getting this type error (on the first else print statement):</p>
<p><a href="http://i.stack.imgur.com/KwJpK.png" rel="nofollow"><img src="http://i.stack.imgur.com/KwJpK.png" alt="enter image description here"></a></p>
<p>I'm not sure if I messed something up when I added the comments, but I can't seem to figure out what it is.</p>
| -1 | 2016-10-01T03:21:22Z | 39,802,775 | <p>You need to change some values.</p>
<p>In line</p>
<pre><code>ans = input("What's %d plus %d?" % (n1, n2))
</code></pre>
<p>Add</p>
<pre><code>result = n1 + n2
if int(ans) == result:
print("That's correct, well done!\n")
correct = correct + 1
else:
print("No it's not correct. The answer is %d.\n" % result) # Here is where I'm getting the error message.**
...
...
</code></pre>
| 0 | 2016-10-01T03:36:32Z | [
"python",
"typeerror",
"modulus"
]
|
Function to return True if integer k and n in list? | 39,802,828 | <p>Very new to python... If I give a list that has two integers n and k, the function should return Boolean True. K has to be in the list the number of n times. For example, if I call matchingValues([1, 2, 1, 4, 1, 1], 1, 4) should return True since 1 is in the list 4 times. I'm guessing I have to use the .count() option but not sure how to write it... Wish I could give more code but unfortunately I am very lost</p>
<pre><code> def matchingValues(aList,n,k):
</code></pre>
| -2 | 2016-10-01T03:49:19Z | 39,802,845 | <p>Better than a solution involving <code>len()</code> is to use the <code>.count()</code> method for lists. It takes an argument, and returns the number of times that argument appears in the list that it is called on.</p>
| 1 | 2016-10-01T03:52:07Z | [
"python",
"list"
]
|
Function to return True if integer k and n in list? | 39,802,828 | <p>Very new to python... If I give a list that has two integers n and k, the function should return Boolean True. K has to be in the list the number of n times. For example, if I call matchingValues([1, 2, 1, 4, 1, 1], 1, 4) should return True since 1 is in the list 4 times. I'm guessing I have to use the .count() option but not sure how to write it... Wish I could give more code but unfortunately I am very lost</p>
<pre><code> def matchingValues(aList,n,k):
</code></pre>
| -2 | 2016-10-01T03:49:19Z | 39,802,872 | <p>What you want to do is define a variable which counts how many times n is in the list</p>
<pre><code>found = 0
</code></pre>
<p>and then, iterate over your list with a loop</p>
<pre><code>for x in range(0, len(aList)):
if aList[x] == n:
found += 1
return(found == k)
</code></pre>
<p>This is, however, if you want to avoid using the <code>count</code> function:</p>
<pre><code>return(aList.count(n)==k)
</code></pre>
<p>Using the manual, hand-written loop will allow you to exit the loop as soon as you know there are <code>k</code> <code>n</code>s in the list, if you want the loop to work like that (however, I have not provided that code. I have only written exactly what <code>count</code> does)</p>
<p>If you want there to be AT LEAST <code>k</code> <code>n</code>s in <code>aList</code>, this would work for you</p>
<pre><code>found = 0
for x in range(0, len(aList)):
if aList[x] == n:
found += 1
if found == k:
return True
return False
</code></pre>
| 1 | 2016-10-01T03:57:01Z | [
"python",
"list"
]
|
Raise an exception in python3 for this method which check dictionary.get with default value? | 39,802,857 | <p>I have a requirement that I have to raise an exception in method "meth(a)", only way I can achieve is to declare dictionary "a" to some value such that a.get('v', 0) raise an exception</p>
<pre class="lang-python prettyprint-override"><code>def meth(a):
if isinstance(a, dict):
return a.get('v', 0)# I have to raise an exception from here
return 0
a = {} #I have to give some value into this dictionary so that my meth(a) raises an exception'''
import re
import sys
import traceback
try:
meth(a)
except Exception:
print("meth exception!")
sys.exit()
raise
else:
sys.stderr.write("meth has no exception")
</code></pre>
| -1 | 2016-10-01T03:54:15Z | 39,803,064 | <p>Depends on what you mean by <em>declare dictionary "a" to some value</em>. You can create your own class that inherits from <code>dict</code> so that the <code>isinstance</code> test works and implement an unfriendly <code>get</code>.</p>
<pre><code>class MyDict(dict):
def get(self, name, default=None):
raise NameError("No way am I getting you a value. "
"What kind of a dict do you think I am?")
a = MyDict()
</code></pre>
<p>and the rest is just your program...</p>
| 1 | 2016-10-01T04:32:53Z | [
"python",
"dictionary",
"exception-handling",
"default"
]
|
Maximum value of certain element of all arrays in np array | 39,802,867 | <p>I have a numpy array with arrays within it:</p>
<pre><code>array([[1,2,3],[4,5,6],[7,8,9]])
</code></pre>
<p>How am I able to find the maximum of all of the last elements of these inner arrays? ie. for this case the return would be 9 <code>(max(3,6,9))</code></p>
<p>I'm able to do this by converting to a Pandas dataframe first, but this is slowing down the program and I'm sure there's an easier way just using np.</p>
| 0 | 2016-10-01T03:55:50Z | 39,802,879 | <p>Assuming that you meant to write</p>
<pre><code>array([[1,2,3],[4,5,6],[7,8,9]])
</code></pre>
<p>then you can slice the last column with <code>A[:,-1]</code> and call <code>.max()</code>.</p>
| 1 | 2016-10-01T03:58:32Z | [
"python",
"numpy"
]
|
Sending email with python script | 39,803,160 | <p>What I'm trying to do is get my python code to send an email. This code is supposed to use the yahoo smtp to send the email. I don't need any attachments or anything else. The code bugs out where it says <code>Error: unable to send email.</code> Other than the obvious of putting in correct email receiver and sender addresses, what can I do to get this thing to work? </p>
<pre><code>#!/usr/bin/env python
from smtplib import SMTP
from smtplib import SMTP_SSL
from smtplib import SMTPException
from email.mime.text import MIMEText
import sys
#Global varialbes
EMAIL_SUBJECT = "Email from Python script"
EMAIL_RECEIVERS = ['receiverId@gmail.com']
EMAIL_SENDER = 'senderId@yahoo.com'
TEXT_SUBTYPE = "plain"
YAHOO_SMTP = "smtp.mail.yahoo.com"
YAHOO_SMTP_PORT = 465
def listToStr(lst):
"""This method makes comma separated list item string"""
return ','.join(lst)
def send_email(content, pswd):
"""This method sends an email"""
msg = MIMEText(content, TEXT_SUBTYPE)
msg["Subject"] = EMAIL_SUBJECT
msg["From"] = EMAIL_SENDER
msg["To"] = listToStr(EMAIL_RECEIVERS)
try:
#Yahoo allows SMTP connection over SSL.
smtpObj = SMTP_SSL(YAHOO_SMTP, YAHOO_SMTP_PORT)
#If SMTP_SSL is used then ehlo and starttls call are not required.
smtpObj.login(user=EMAIL_SENDER, password=pswd)
smtpObj.sendmail(EMAIL_SENDER, EMAIL_RECEIVERS, msg.as_string())
smtpObj.quit();
except SMTPException as error:
print "Error: unable to send email : {err}".format(err=error)
def main(pswd):
"""This is a simple main() function which demonstrates sending of email using smtplib."""
send_email("Test email was generated by Python using smtplib and email libraries", pswd);
if __name__ == "__main__":
"""If this script is executed as stand alone then call main() function."""
if len(sys.argv) == 2:
main(sys.argv[1])
else:
print "Please provide password"
sys.exit(0)
</code></pre>
| 1 | 2016-10-01T04:51:54Z | 39,805,628 | <p>I don't know about Yahoo, but Google blocked the login via their smtp-port.
It would be way too easy to conduct brute force attacks otherwise. So even if your code is perfectly ok, the login might still fail because of that. I have tried to do the exact same thing for my gmail account.</p>
| 0 | 2016-10-01T10:41:01Z | [
"python",
"email",
"smtp",
"yahoo-api"
]
|
Sending email with python script | 39,803,160 | <p>What I'm trying to do is get my python code to send an email. This code is supposed to use the yahoo smtp to send the email. I don't need any attachments or anything else. The code bugs out where it says <code>Error: unable to send email.</code> Other than the obvious of putting in correct email receiver and sender addresses, what can I do to get this thing to work? </p>
<pre><code>#!/usr/bin/env python
from smtplib import SMTP
from smtplib import SMTP_SSL
from smtplib import SMTPException
from email.mime.text import MIMEText
import sys
#Global varialbes
EMAIL_SUBJECT = "Email from Python script"
EMAIL_RECEIVERS = ['receiverId@gmail.com']
EMAIL_SENDER = 'senderId@yahoo.com'
TEXT_SUBTYPE = "plain"
YAHOO_SMTP = "smtp.mail.yahoo.com"
YAHOO_SMTP_PORT = 465
def listToStr(lst):
"""This method makes comma separated list item string"""
return ','.join(lst)
def send_email(content, pswd):
"""This method sends an email"""
msg = MIMEText(content, TEXT_SUBTYPE)
msg["Subject"] = EMAIL_SUBJECT
msg["From"] = EMAIL_SENDER
msg["To"] = listToStr(EMAIL_RECEIVERS)
try:
#Yahoo allows SMTP connection over SSL.
smtpObj = SMTP_SSL(YAHOO_SMTP, YAHOO_SMTP_PORT)
#If SMTP_SSL is used then ehlo and starttls call are not required.
smtpObj.login(user=EMAIL_SENDER, password=pswd)
smtpObj.sendmail(EMAIL_SENDER, EMAIL_RECEIVERS, msg.as_string())
smtpObj.quit();
except SMTPException as error:
print "Error: unable to send email : {err}".format(err=error)
def main(pswd):
"""This is a simple main() function which demonstrates sending of email using smtplib."""
send_email("Test email was generated by Python using smtplib and email libraries", pswd);
if __name__ == "__main__":
"""If this script is executed as stand alone then call main() function."""
if len(sys.argv) == 2:
main(sys.argv[1])
else:
print "Please provide password"
sys.exit(0)
</code></pre>
| 1 | 2016-10-01T04:51:54Z | 39,807,354 | <p>As developer I suggest: <a href="https://github.com/kootenpv/yagmail" rel="nofollow">yagmail</a></p>
| 0 | 2016-10-01T13:43:56Z | [
"python",
"email",
"smtp",
"yahoo-api"
]
|
scrapy response.xpath only picking out the first item | 39,803,253 | <p>I have the html structure</p>
<pre><code> <div class="column first">
<div class="detail">
<strong>Phone: </strong>
<span class="value"> 012-345-6789</span>
</div>
<div class="detail">
<span class="value">1 Street Address, Big Road, City, Country</span>
</div>
<div class="detail">
<h3 class="inline">Area:</h3>
<span class="value">Georgetown</span>
</div>
<div class="detail">
<h3 class="inline">Nearest Train:</h3>
<span class="value">Georgetown Station</span>
</div>
<div class="detail">
<h3 class="inline">Website:</h3>
<span class="value"><a href='http://www.website.com' target='_blank'>www.website.com</a></span>
</div>
</div>
</code></pre>
<p>When I run <code>sel = response.xpath('//span[@class="value"]/text()')</code> in scrapy shell I get what I expect back, which is:</p>
<pre><code>[<Selector xpath='//span[@class="value"]/text()' data=u' 012-345-6789'>, <Selector xpath='//span[@class="value"]/text()' data=u'1 Street Address, Big Road, City, Country'>, <Selector xpath='//span[@class="value"]/text()' data=u'Georgetown Station'>, <Selector xpath='//span[@class="value"]/text()' data=u' '>, <Selector xpath='//span[@class="value"]/text()' data=u'January, 2016'>]
</code></pre>
<p>However, in the parse block in my scrapy spider, it's only returning the first item</p>
<pre><code>def parse(self, response):
def extract_with_xpath(query):
return response.xpath(query).extract_first().strip()
yield {
'details': extract_with_xpath('//span[@class="value"]/text()')
}
</code></pre>
<p>I realise I am using <code>extract_first()</code> but if I use <code>extract()</code> it breaks, even though I know <code>extract()</code> is a legitimate function.</p>
<p>What I am doing wrong? Do I need to loop through the
<code>extract_with_xpath('//span[@class="value"]/text()')</code> part?</p>
<p>Thanks for any enlightenment!</p>
| 0 | 2016-10-01T05:11:54Z | 39,803,354 | <p>in items.py, specify-</p>
<pre><code>from scrapy.item import Item, Field
class yourProjectNameItem(Item):
# define the fields for your item here like:
name = Field()
details= Field()
</code></pre>
<p>in your scrapy spider:
imports:</p>
<pre><code>from scrapy.selector import HtmlXPathSelector
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.contrib.spiders import CrawlSpider, Rule
from yourProjectName.items import yourProjectNameItem
import re
</code></pre>
<p>and the parse function as follows:</p>
<pre><code>def parse_item(self, response):
hxs = HtmlXPathSelector(response)
i = yourProjectNameItem()
i['name'] = hxs.select('YourXPathHere').extract()
i['details'] = hxs.select('YourXPathHere').extract()
return i
</code></pre>
<p>Hope this solves the issue.
You can refer to my project on git:<a href="https://github.com/omkar-dsd/SRMSE/tree/master/Scrapers/NasaScraper" rel="nofollow">https://github.com/omkar-dsd/SRMSE/tree/master/Scrapers/NasaScraper</a></p>
| 0 | 2016-10-01T05:30:25Z | [
"python",
"scrapy"
]
|
modifying many columns in pandas dataframe | 39,803,254 | <p>I have been stuck on this for a while and no amount of googling seems to help. </p>
<p>I am reading in a lot of raw data. Some of the variables come in as objects due to the source using letters for various reasons for missing (which I do not care about).</p>
<p>So I want to run a fairly large subset of columns through <code>pandas.to_numeric(___ ,error='coerce')</code> just to force these to be cast as int or float (again, I do not care too much which, just that they are numeric.</p>
<p>I can make this happen column by column easy:</p>
<pre><code>df['col_name'] = pd.to_numeric(df['col_name'], errors='coerce')
</code></pre>
<p>However, I have some 60 columns I want to cast like this .. so I thought this would work:</p>
<pre><code>numeric = ['lots', 'a', 'columns']
for item in numeric:
df_[item] = pd.to_numeric(df[item], errors='coerce')
</code></pre>
<p>The error I get is:</p>
<pre><code>Traceback (most recent call last):
File "/Users/____/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2885, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-53-43b873fbd712>", line 2, in <module>
df_detail[item] = pd.to_numeric(dfl[item], errors='coerce')
File "/Users/____/anaconda/lib/python2.7/site-packages/pandas/tools/util.py", line 101, in to_numeric
raise TypeError('arg must be a list, tuple, 1-d array, or Series')
TypeError: arg must be a list, tuple, 1-d array, or Series
</code></pre>
<p>I tried many versions. This is has something to do with the list or looking through it. I get the very same error when the for-loop simply calls for <code>df(item).describe()</code> </p>
<p>From my (still novice) understanding of Python, this should work. I am at loss.
Thanks</p>
| 2 | 2016-10-01T05:12:12Z | 39,803,974 | <p>First of all, see <a href="http://stackoverflow.com/a/39801222/2336654">this answer</a></p>
<pre><code># Let
numeric = ['lots', 'a', 'columns']
</code></pre>
<p><strong><em>Option 1</em></strong></p>
<pre><code>df[numeric] = df[numeric].apply(pd.to_numeric, errors='coerce')
</code></pre>
<p><strong><em>Option 2</em></strong></p>
<pre><code>df.loc[:, numeric] = pd.to_numeric(df[numeric].values.ravel(), 'coerce') \
.reshape(-1, len(numeric))
</code></pre>
<p><strong><em>Demonstration</em></strong><br>
Consider the dataframe <code>df</code></p>
<pre><code>df = pd.DataFrame([
[1, 'a', 2],
['b', 3, 'c'],
['4', 'd', '5']
], columns=['A', 'B', 'C'])
</code></pre>
<p>Then both <strong><em>options</em></strong> above yield</p>
<p><a href="http://i.stack.imgur.com/t8sub.png" rel="nofollow"><img src="http://i.stack.imgur.com/t8sub.png" alt="enter image description here"></a></p>
| 1 | 2016-10-01T07:13:55Z | [
"python",
"list",
"pandas",
"dataframe"
]
|
Is it possible to set two or more types(Integre or float) for 1 field by setting codition in Odoo 9? | 39,803,321 | <p>I am try to learn how to customize the odoo system to sovle specific problem in business. I am using odoo9.0.
Could we set two types of value(integre and float) for a file by setting the specific conditions for each of them? if it is possible, please teach me ththe right steps to follow. Thanks for your time.</p>
| 0 | 2016-10-01T05:23:59Z | 39,817,870 | <p>In Odoo it's not possible to set two data-type for single field.
But you can create 2 fields Integer and Float and show/hide by setting condition in view.</p>
<p>.py file</p>
<pre><code>is_integer = fields.Boolean('Is Integer?')
integer_field = fields.Integer('Integer Field')
float_field = fields.Float('Float Field')
</code></pre>
<p>.xml file</p>
<pre><code><field name="is_integer" invisible="1" />
<field name="integer_field" attrs="{'invisible': [('is_intiger', '==', False)]}"/>
<field name="float_field" attrs="{'invisible': [('is_intiger', '==', True)]}"/>
</code></pre>
| 1 | 2016-10-02T14:13:38Z | [
"python",
"file-type",
"odoo-9"
]
|
How to call a view function with argument from template and return a python object in Django? | 39,803,339 | <p>Here is the questions
now I want call a view function from template/html with argument
the function most like </p>
<pre><code>def function(PageToken,ID):
'''Do Something Here'''
comments = [[User1,Comment1],[User2,Comment2]]
return comments
</code></pre>
<p>And how I call this function and Use like</p>
<pre><code>{%for comment in comments %}
<li>
{{comment.1}}
{{comment.2}}
</li>
{%endfor%}
</code></pre>
<p>And I dont want
Reload the page
how to do that</p>
| 0 | 2016-10-01T05:27:59Z | 39,803,890 | <p>you can define your own custom template filter that takes arguments. </p>
<pre><code># in custom_tags.py
from django import template
register = template.Library()
def build_comments(pagetoken, id):
# build comments
return comments # it can also be queryset
register.assignment_tag(build_comments)
</code></pre>
<p>in template: </p>
<pre><code>{% load custom_tags %}
{% build_comments pagetoken id as comments %}
{% for comment in comments %}
<li>
{{comment.1}}
{{comment.2}}
</li>
{% endfor %}
</code></pre>
<p>full documentation ---> <a href="https://docs.djangoproject.com/en/1.10/howto/custom-template-tags/#custom-template-tags-and-filters" rel="nofollow">here</a> </p>
| 0 | 2016-10-01T07:01:45Z | [
"javascript",
"python",
"html",
"ajax",
"django"
]
|
Python plotting on remote server using PyCharm | 39,803,373 | <p>I have started to learn Python and so far my setup has been following - Python 3.5 installation on Win10 64bit local machine with PyCharm as a great IDE. Everything works, matplotlib charts and other visual outputs display fine, debugging works, etc.</p>
<p>Now, I have came across some libraries which works only on Linux. I have set up Ubuntu 16.4 64bit VPS on Digital Ocean, installed Python 3.5. In PyCharm I have set up SFTP connection to remote host. Code running works, debugging works, however, I am not able to bring display output (matplotlib plots,...) to local (Win10) machine. As I am not at all familiar with Linux GUI environments (X11?), after googling I have following questions: </p>
<p>1) Should anything be installed on remote Linux machine? (e.g. x11 client/server/smth?)</p>
<p>2) Should anything be installed on local Win machine? (e.g. Xming?)</p>
<p>3) Should anything be configured on remote Linx machine? (e.g. X11 forwarding)</p>
<p>4) Should anything be configured on local Win machine PyCharm?</p>
<p>5) There are X11 forwarding settings in Putty and some have suggested to use those but I am not sure, should Putty session run in paraller with PyCharm and can that be avoided. </p>
<p>Thanks a lot! </p>
<p>PS - I have installed Jupyter Notebook (and latest Jupyter Lab) on remote machine and it works excellent, however I am still prefering PyCharm as primary IDE with better code completion, debugger and other perks.</p>
| 0 | 2016-10-01T05:34:26Z | 40,006,878 | <p>Ok, after some more googling I finally managed to get this process working, hope it helps somebody: </p>
<p>1) on remote host (VPS, Ubuntu 16.04) I had to install X11 server, which I did by: </p>
<pre><code>sudo apt-get install xorg
sudo apt-get install openbox
</code></pre>
<p>2) On remote host I had to make sure that X11Forwarding is enabled in /etc/ssh/sshd_config</p>
<p>3) On local Win10 machine I had to install Xming server and launch it with default settings.</p>
<p>4) On local Win10 machine I had to configure Putty to use X11 forwarding (Connection-> SSH -> X11 Forwarding) with default settings and keep connection open while running PyCharm (it seems there is no option in PyCharm to enable x11 forwarding, so putty must be running in the background)</p>
<p>5) On remote machine I had to check Display number (echo $DISPLAY) - this can be different for everyone. For me it was localhost:10.0</p>
<p>6) In PyCharm Run configuration -> Environment variables I had to add DISPLAY=localhost:10.0</p>
<p>After all these steps and Putty+Xming running in backgroud, I was able to execute remote code and bring graphic back to my Windows 10 PC!</p>
<p>PS - process is actually slow, I have to wait around 10 seconds before image is brought back to me. I am not sure why or how to speed it up. Might be another question. (reducing chipher strength and enabling compression does not help. It seems some sort of initialization problem with x11 remote and local)</p>
| 0 | 2016-10-12T19:31:46Z | [
"python",
"linux",
"windows",
"matplotlib",
"x11"
]
|
What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib? | 39,803,385 | <p>In the <a href="http://matplotlib.org/users/legend_guide.html#legend-location" rel="nofollow">"Legend location"</a> section of the "Legend guide" in the matplotlib website, there's a small script where line 9 is <code>plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2, mode="expand", borderaxespad=0.)</code>. All the tuples I've seen passed to <code>bbox_to_anchor</code> have 2 elements in it, but this one has 4. What does each element mean if the tuple passed has 4 elements?
<br><br>
I was looking at it in the <code>pyplot.legend</code> <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend" rel="nofollow">docs</a>, and it said something about <code>bbox_transform</code> coordinates. So I looked around and found <code>matplotlib.transforms.Bbox</code> with a <a href="http://matplotlib.org/devel/transformations.html#matplotlib.transforms.Bbox" rel="nofollow"><code>static from_bounds(x0, y0, width, height)</code></a>.
<br><br>
I was guessing the setup for the 4-tuple parameter was based on this <code>from_bounds</code>. I copied the script to Spyder, did <code>%matplotlib</code> in an Ipython console, and changed some values. It seemed to make sense, but when I tried only changing <code>.102</code> to something like <code>0.9</code>, the legend didn't change. I think the tuple is based on <code>from_bounds</code>, I just don't know why changing the last value in the tuple did nothing. </p>
| 0 | 2016-10-01T05:36:24Z | 39,806,180 | <p>You're right, the 4-tuple in <code>plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3)</code> is set as <code>(x0, y0, width, height)</code> where <code>(x0,y0)</code> are the lower left corner coordinates of the bounding box.</p>
<p>While those parameters set the bounding box for the legend, the legend's actual vertical size is shrunk to the size that is needed to put the elements in. Further its position is determined only in conjunction with the <code>loc</code> parameter. The loc parameter sets the alignment of the legend inside the bounding box, such that for some cases, no difference will by seen when changing the <code>height</code>, compare e.g. plot (2) and (4).</p>
<p><a href="http://i.stack.imgur.com/OtHbK.png" rel="nofollow"><img src="http://i.stack.imgur.com/OtHbK.png" alt="enter image description here"></a> </p>
| 3 | 2016-10-01T11:40:28Z | [
"python",
"matplotlib"
]
|
How to create buttons, text boxes and label in loop in tkinter | 39,803,630 | <p>I am trying to create a framework to create a label, text box and button as an object, I can extend it easily.</p>
<p>Idea:</p>
<p><a href="http://i.stack.imgur.com/gsSAR.png" rel="nofollow">Original</a></p>
<p><a href="http://i.stack.imgur.com/x8q8C.png" rel="nofollow">after extend</a></p>
<p>and it could extend to have 3, 4, 5 or more if it have more file, just declare in dictionary list, it will extend automatically. </p>
<p>The code I have:</p>
<pre><code>def getpath(entry_box, type):
# path or file
if type == 'path':
entry_box.set(filedial.askdirectory())
elif type == 'file':
entry_box.set(filedial.askopenfilename())
MainWin = tk.Tk() # Create main windows
MainWin.title('Get file and path') # App name
# Create root container to hold Frames
mainFrame = ttk.Frame(MainWin)
mainFrame.grid(column=1, row=1)
# define the object to create in dictionary, format:
# {object name:[title name, default path, button name, file or folder path]}
obj2create ={'file1':['ABC Location: ', r'C:/', 'Get ABC','file'],
'file2': ['DEF Location:', r'C:/1/', 'Get DEF', 'file']}
ttl_obj = 0
for key in obj2create:
ttl_obj +=1
vir = obj2create[key]
# Module for get file:
obj_name = key
title = vir[0]
default_path = vir[1]
btn_name = vir[2]
get_type = vir[3]
# Create main container
pa_frame = ttk.Frame(mainFrame)
pa_frame.grid(column=1, row=10*ttl_obj, sticky=tk.W)
pa_frame.config(width = 100)
# Row 1: Label
frame_name = obj_name + '_name'
print(frame_name)
frame_name = ttk.Label(pa_frame, text= title).grid(column=1, row=10*ttl_obj,sticky=tk.W)
# Row 2: path and button
# assign type
path_loc = obj_name + '_path'
path_loc = tk.StringVar()
path_loc.set(default_path)
# put in frame
fileLocPath = obj_name + '_loc_path'
fileLocPath = ttk.Entry(pa_frame, width=70, textvariable=path_loc)
fileLocPath.grid(column=1, row=30*ttl_obj) # Assign position
# Get file button
# define button display text and assign the command / function
bt_get_file_path = obj_name + '_btn'
bt_get_file_path = ttk.Button(pa_frame, text= btn_name,
command=lambda: getpath(path_loc, get_type))
# Position Button in second row, second column (zero-based)
bt_get_file_path.grid(column=2, row=30*ttl_obj)
# Auto popup when open
MainWin.mainloop() # Let the window keep running until close
</code></pre>
<p><strong>Issue:</strong></p>
<ol>
<li><p>Default file path appear in second text box only.</p></li>
<li><p>All the button location point to second box.</p></li>
</ol>
<p>I also not sure how could I get the value in different box, the "path_loc = obj_name + '_path'" not able to get the correct object.</p>
<p>How should I make it work? Or the way I use is wrong?</p>
| 0 | 2016-10-01T06:18:05Z | 39,804,134 | <p>You have a lot of unnecessary code written like creating a string and assigning a widget to the same variable.<br>
Now, I am not certain what the code should look like but I'll give you a way where, in case of making new variables every time in a loop, there is this built-in function <code>exec</code> that might help.<br>
This funtion will help you use string as a python syntax command.<br>
for e.g:</p>
<pre><code>for i in range(5):
exec ("lbl_%s = tk.Label(mainFrame)" % (str(i)) )
</code></pre>
<p>In this above way, the <code>exec</code> will treat the string as a python command/syntax, so it will actually create 5 Tkinter labels:</p>
<pre><code>In [10]: lbl_0
Out[10]: <Tkinter.Label instance at 0x03471C10>
In [11]: lbl_1
Out[11]: <Tkinter.Label instance at 0x03442828>
...
...
In [14]: lbl_4
Out[14]: <Tkinter.Label instance at 0x03471B20>
</code></pre>
<p>Now this way you would be able to access those objects using their variable names and also would be able to modify them individually.</p>
| 0 | 2016-10-01T07:34:26Z | [
"python",
"tkinter"
]
|
How to create buttons, text boxes and label in loop in tkinter | 39,803,630 | <p>I am trying to create a framework to create a label, text box and button as an object, I can extend it easily.</p>
<p>Idea:</p>
<p><a href="http://i.stack.imgur.com/gsSAR.png" rel="nofollow">Original</a></p>
<p><a href="http://i.stack.imgur.com/x8q8C.png" rel="nofollow">after extend</a></p>
<p>and it could extend to have 3, 4, 5 or more if it have more file, just declare in dictionary list, it will extend automatically. </p>
<p>The code I have:</p>
<pre><code>def getpath(entry_box, type):
# path or file
if type == 'path':
entry_box.set(filedial.askdirectory())
elif type == 'file':
entry_box.set(filedial.askopenfilename())
MainWin = tk.Tk() # Create main windows
MainWin.title('Get file and path') # App name
# Create root container to hold Frames
mainFrame = ttk.Frame(MainWin)
mainFrame.grid(column=1, row=1)
# define the object to create in dictionary, format:
# {object name:[title name, default path, button name, file or folder path]}
obj2create ={'file1':['ABC Location: ', r'C:/', 'Get ABC','file'],
'file2': ['DEF Location:', r'C:/1/', 'Get DEF', 'file']}
ttl_obj = 0
for key in obj2create:
ttl_obj +=1
vir = obj2create[key]
# Module for get file:
obj_name = key
title = vir[0]
default_path = vir[1]
btn_name = vir[2]
get_type = vir[3]
# Create main container
pa_frame = ttk.Frame(mainFrame)
pa_frame.grid(column=1, row=10*ttl_obj, sticky=tk.W)
pa_frame.config(width = 100)
# Row 1: Label
frame_name = obj_name + '_name'
print(frame_name)
frame_name = ttk.Label(pa_frame, text= title).grid(column=1, row=10*ttl_obj,sticky=tk.W)
# Row 2: path and button
# assign type
path_loc = obj_name + '_path'
path_loc = tk.StringVar()
path_loc.set(default_path)
# put in frame
fileLocPath = obj_name + '_loc_path'
fileLocPath = ttk.Entry(pa_frame, width=70, textvariable=path_loc)
fileLocPath.grid(column=1, row=30*ttl_obj) # Assign position
# Get file button
# define button display text and assign the command / function
bt_get_file_path = obj_name + '_btn'
bt_get_file_path = ttk.Button(pa_frame, text= btn_name,
command=lambda: getpath(path_loc, get_type))
# Position Button in second row, second column (zero-based)
bt_get_file_path.grid(column=2, row=30*ttl_obj)
# Auto popup when open
MainWin.mainloop() # Let the window keep running until close
</code></pre>
<p><strong>Issue:</strong></p>
<ol>
<li><p>Default file path appear in second text box only.</p></li>
<li><p>All the button location point to second box.</p></li>
</ol>
<p>I also not sure how could I get the value in different box, the "path_loc = obj_name + '_path'" not able to get the correct object.</p>
<p>How should I make it work? Or the way I use is wrong?</p>
| 0 | 2016-10-01T06:18:05Z | 39,816,274 | <p>Tkinter widgets are no different than any other python objects with respect to creating them in a loop. Your problem seems to be that you don't know how to create a unique variable for an unknown number of widgets. </p>
<p>The important thing to know is that you don't need a unique variable for each widget. Instead, you can use a list or dictionary, either of which can be easily extended at runtime. </p>
<h2>Saving widget references in a dictionary</h2>
<p>Here is a solution using a dictionary:</p>
<pre><code>entries = {}
for key in obj2create:
...
entries[key] = ttk.Entry(...)
...
...
print("the value for file1 is", entries["file1"].get()
</code></pre>
<h2>Creating a custom compound widget</h2>
<p>If you're wanting to create sets of widgets that are to be treated as a group, it may be better to create a class. In effect, you're creating your own custom widget. This type of class is often called a "compound widget" or "megawidget". </p>
<p>For example:</p>
<pre><code>class FileWidget(ttk.Frame):
def __init__(self, parent, name):
ttk.Frame.__init__(self, parent)
self.label = ttk.Label(self, text="%s Location" % name)
self.fileLocPath = ttk.Entry(self)
self.bt_get_file_path = ttk.Button(self, text=name, command=self.get_path)
...
def get_path(self):
return self.fileLocPath.get()
</code></pre>
<p>You can then create each row in your GUI like this:</p>
<pre><code>widgets = {}
for key in obj2create:
widgets[key] = FileWidget(mainFrame, key)
widgets[key].pack(side="top", fill="x")
</code></pre>
<p>Later, you can get back the values like this:</p>
<pre><code>for key in obj2create:
widget = widgets[key]
print("%s: %s" % (key, widget.get_path())
</code></pre>
| 0 | 2016-10-02T10:57:24Z | [
"python",
"tkinter"
]
|
DictVectorizer with a large dataset | 39,803,650 | <p>I have a large dataset with categorical values and tried to encode them using <code>DictVectorizer</code>. The following is a snippet of the code I tried.</p>
<pre><code>dv = DictVectorizer(sparse=True)
_dicts = []
for line in fp:
_dict = create_dict_feature(line)
_dicts.append(_dict)
dv.fit_transform(_dicts)
</code></pre>
<p>But, <code>MemoryError</code> occurs in <code>_dicts.append(_dict)</code>. I am wondering what would be an efficient way of getting around this problem. </p>
| 1 | 2016-10-01T06:20:11Z | 39,804,103 | <p>According to the docs, <code>fit_transform</code> can take an iterable. If the memory issue is coming from the size of the list, consider using a generator instead of a <code>list</code>, which will yield your <code>dict</code>s one at a time as it is iterated.
</p>
<pre><code>_dicts = (create_dict_feature(line) for line in fp)
dv = DictVectorizer(sparse=True)
dv.fit_transform(_dicts)
</code></pre>
<p>This won't help much if <code>fit_transform</code> accumulates the <code>dict</code>s or <code>Mapping</code>s just as you were doing before.</p>
| 1 | 2016-10-01T07:30:31Z | [
"python",
"scikit-learn"
]
|
speech to text processing - python | 39,803,688 | <p>I have a project in which the user will send an audio file from android/web to the server.
I need to perform speech to text processing on the server and return some files to the user back on android/web. However the server side is to be done using Python.
Please guide me as to how it could be done?</p>
| 0 | 2016-10-01T06:27:11Z | 39,804,001 | <p>Alongside your web application, you can have a queue of tasks that need to be run and worker process(es) to run and track those tasks. This is a popular pattern when web requests need to either start tasks in the background, check in on tasks, or get the result of a task. An introduction to this pattern can be found in the <a href="https://www.fullstackpython.com/task-queues.html" rel="nofollow">Task Queues section of the Full Stack Python open book</a>. <a href="http://www.celeryproject.org/" rel="nofollow">Celery</a> and <a href="http://python-rq.org/" rel="nofollow">RQ</a> are two popular projects that supply task queue management and can plug into an existing Python web application, such as one built with Django or Flask.</p>
<p>Once you have task management, you'll have to decide how to keep the user up to date on the status of a task. If you're stuck with having to use RPC-style web service calls only, then you can have clients (e.g. Android or browser) poll for the status by making a call to a web service you've created that checks on the task via your task queue manager's API.</p>
<p>If you want the user to be informed faster or want to reduce wasteful overhead from constant polling, consider supplying a websocket instead. Through a websocket connection, clients could subscribe to notifications of events such as the completion of a speech-to-text job. The <a href="http://autobahn.ws/python/" rel="nofollow">Autobahn|Python library</a> provides server code for implementing websockets as well as support for a protocol on top called <em>WAMP</em> that can be used to communicate subscriptions and messages or call upon services. If you need to stick with Django, consider something like <a href="https://django-websocket-redis.readthedocs.io/" rel="nofollow">django-websocket-redis</a> instead.</p>
| 0 | 2016-10-01T07:16:52Z | [
"python",
"speech-recognition",
"speech-to-text"
]
|
Implementing BFS algorithm with a max depth and that prints all shortest paths | 39,803,712 | <p>This is the BFS algorithm I came up with to print all the shortest paths from root node to any other node in the graph:</p>
<pre><code>d = deque()
d.append(root)
level = 0
while len(d) >= 0 and level <= max_depth:
u = d.popleft()
print(adjacency_list[u])
for v in adjacency_list[u]:
if visited[v] == 'N':
if nodes2distances[u] + 1 <= nodes2distances[v]:
nodes2distances[v] = nodes2distances[u] + 1
node2parents[v].append(u)
d.extend(v)
level += 1
visited[u] = 'Y'
</code></pre>
<p>The above code works fine when I don't specify the max level condition, however, the output varies every time I run this algorithm with a restriction on level.</p>
<p>1) Could you explain how i could implement this algorithm with level restriction(i.e specifying the maximum level)?</p>
<p>2) Also, could you please let me know if the approach I have taken to solve the problem can be better?</p>
<p>Edit :
Ok!!Sorry, I didn't do it before!!
Say I have the following edges in a unweighted graph: </p>
<p><strong>('A', 'B'), ('A', 'C'), ('B', 'C'), ('B', 'D'),('D', 'E'), ('D', 'F'), ('D', 'G'), ('E', 'F'), ('G', 'F')</strong></p>
<p>After implementing my code without the restriction of depth, I get the following output when i call the algorithm for node <strong>'B'</strong>,</p>
<pre><code>[('A', ['B']), ('C', ['B']), ('D', ['B']), ('E', ['D']), ('F', ['D']), ('G', ['D'])]
</code></pre>
<p>However, when I call the same function with a level restriction of 2, i.e., <code>myFunction(graph,'E',2)</code>, I get the following output:</p>
<pre><code>[('A', ['B']), ('C', ['B']), ('D', ['B'])]
</code></pre>
<p>whereas, the expected output is </p>
<pre><code>[('A', ['B']), ('C', ['B']), ('D', ['B']),('E',['D']),('F', ['D']),('G',['D'])]
</code></pre>
| 0 | 2016-10-01T06:31:26Z | 39,809,079 | <p>You are incrementing level at the wrong place. Each node's level is equal to its parent level plus 1. You should not increment level globally in the <code>while</code> loop. Instead you should store the level of each node you put in the queue. Something like this:</p>
<pre><code>d = deque()
#node,level
d.append( (root,0 ) )
while len(d) >= 0:
front = d.popleft()
u = front[0]
level = front[1]
if level >= max_depth:
break
print(adjacency_list[u])
for v in adjacency_list[u]:
if visited[v] == 'N':
if nodes2distances[u] + 1 <= nodes2distances[v]:
nodes2distances[v] = nodes2distances[u] + 1
node2parents[v].append(u)
d.append( (v,level+1) )
visited[u] = 'Y'
</code></pre>
| 1 | 2016-10-01T16:42:20Z | [
"python",
"algorithm",
"shortest-path",
"bfs"
]
|
peewee and peewee-async: why is async slower | 39,803,746 | <p>I am trying to wrap my head around Tornado and async connections to Postgresql. I found a library that can do this at <a href="http://peewee-async.readthedocs.io/en/latest/" rel="nofollow">http://peewee-async.readthedocs.io/en/latest/</a>.</p>
<p>I devised a little test to compare traditional Peewee and Peewee-async, but somehow async works slower.</p>
<p>This is my app:</p>
<pre><code>import peewee
import tornado.web
import logging
import asyncio
import peewee_async
import tornado.gen
import tornado.httpclient
from tornado.platform.asyncio import AsyncIOMainLoop
AsyncIOMainLoop().install()
app = tornado.web.Application(debug=True)
app.listen(port=8888)
# ===========
# Defining Async model
async_db = peewee_async.PooledPostgresqlDatabase(
'reminderbot',
user='reminderbot',
password='reminderbot',
host='localhost'
)
app.objects = peewee_async.Manager(async_db)
class AsyncHuman(peewee.Model):
first_name = peewee.CharField()
messenger_id = peewee.CharField()
class Meta:
database = async_db
db_table = 'chats_human'
# ==========
# Defining Sync model
sync_db = peewee.PostgresqlDatabase(
'reminderbot',
user='reminderbot',
password='reminderbot',
host='localhost'
)
class SyncHuman(peewee.Model):
first_name = peewee.CharField()
messenger_id = peewee.CharField()
class Meta:
database = sync_db
db_table = 'chats_human'
# defining two handlers - async and sync
class AsyncHandler(tornado.web.RequestHandler):
async def get(self):
"""
An asynchronous way to create an object and return its ID
"""
obj = await self.application.objects.create(
AsyncHuman, messenger_id='12345')
self.write(
{'id': obj.id,
'messenger_id': obj.messenger_id}
)
class SyncHandler(tornado.web.RequestHandler):
def get(self):
"""
An traditional synchronous way
"""
obj = SyncHuman.create(messenger_id='12345')
self.write({
'id': obj.id,
'messenger_id': obj.messenger_id
})
app.add_handlers('', [
(r"/receive_async", AsyncHandler),
(r"/receive_sync", SyncHandler),
])
# Run loop
loop = asyncio.get_event_loop()
try:
loop.run_forever()
except KeyboardInterrupt:
print(" server stopped")
</code></pre>
<p>and this is what I get from Apache Benchmark:</p>
<pre><code>ab -n 100 -c 100 http://127.0.0.1:8888/receive_async
Connection Times (ms)
min mean[+/-sd] median max
Connect: 2 4 1.5 5 7
Processing: 621 1049 256.6 1054 1486
Waiting: 621 1048 256.6 1053 1485
Total: 628 1053 255.3 1058 1492
Percentage of the requests served within a certain time (ms)
50% 1058
66% 1196
75% 1274
80% 1324
90% 1409
95% 1452
98% 1485
99% 1492
100% 1492 (longest request)
ab -n 100 -c 100 http://127.0.0.1:8888/receive_sync
Connection Times (ms)
min mean[+/-sd] median max
Connect: 2 5 1.9 5 8
Processing: 8 476 277.7 479 1052
Waiting: 7 476 277.7 478 1052
Total: 15 481 276.2 483 1060
Percentage of the requests served within a certain time (ms)
50% 483
66% 629
75% 714
80% 759
90% 853
95% 899
98% 1051
99% 1060
100% 1060 (longest request)
</code></pre>
<p>why is sync faster? where is the bottleneck I'm missing?</p>
| 2 | 2016-10-01T06:37:17Z | 39,807,456 | <p>For a long explanation:</p>
<p><a href="http://techspot.zzzeek.org/2015/02/15/asynchronous-python-and-databases/" rel="nofollow">http://techspot.zzzeek.org/2015/02/15/asynchronous-python-and-databases/</a></p>
<p>For a short explanation: synchronous Python code is simple and mostly implemented in the standard library's socket module, which is pure C. Async Python code is more complex than synchronous code. Each request requires several executions of the main event loop code, which is written in Python (in the <code>asyncio</code> case here) and therefore has a lot of overhead compared to C code.</p>
<p>Benchmarks like yours show async's overhead dramatically, because there's no network latency between your application and your database, and you're doing a large number of very small database operations. Since every <em>other</em> aspect of the benchmark is fast, these many executions of the event loop logic add a large proportion of the total runtime.</p>
<p>Mike Bayer's argument, linked above, is that low-latency scenarios like this are typical for database applications, and therefore database operations shouldn't be run on the event loop.</p>
<p>Async is best for high-latency scenarios, like websockets and web crawlers, where the application spends most of its time waiting for the peer, rather than spending most of its time executing Python.</p>
<p>In conclusion: if your application has a good reason to be async (it deals with slow peers), having an async database driver is a good idea for the sake of consistent code, but expect some overhead.</p>
<p>If you don't need async for another reason, don't do async database calls, because they're a bit slower.</p>
| 2 | 2016-10-01T13:54:58Z | [
"python",
"postgresql",
"tornado",
"python-asyncio",
"peewee"
]
|
peewee and peewee-async: why is async slower | 39,803,746 | <p>I am trying to wrap my head around Tornado and async connections to Postgresql. I found a library that can do this at <a href="http://peewee-async.readthedocs.io/en/latest/" rel="nofollow">http://peewee-async.readthedocs.io/en/latest/</a>.</p>
<p>I devised a little test to compare traditional Peewee and Peewee-async, but somehow async works slower.</p>
<p>This is my app:</p>
<pre><code>import peewee
import tornado.web
import logging
import asyncio
import peewee_async
import tornado.gen
import tornado.httpclient
from tornado.platform.asyncio import AsyncIOMainLoop
AsyncIOMainLoop().install()
app = tornado.web.Application(debug=True)
app.listen(port=8888)
# ===========
# Defining Async model
async_db = peewee_async.PooledPostgresqlDatabase(
'reminderbot',
user='reminderbot',
password='reminderbot',
host='localhost'
)
app.objects = peewee_async.Manager(async_db)
class AsyncHuman(peewee.Model):
first_name = peewee.CharField()
messenger_id = peewee.CharField()
class Meta:
database = async_db
db_table = 'chats_human'
# ==========
# Defining Sync model
sync_db = peewee.PostgresqlDatabase(
'reminderbot',
user='reminderbot',
password='reminderbot',
host='localhost'
)
class SyncHuman(peewee.Model):
first_name = peewee.CharField()
messenger_id = peewee.CharField()
class Meta:
database = sync_db
db_table = 'chats_human'
# defining two handlers - async and sync
class AsyncHandler(tornado.web.RequestHandler):
async def get(self):
"""
An asynchronous way to create an object and return its ID
"""
obj = await self.application.objects.create(
AsyncHuman, messenger_id='12345')
self.write(
{'id': obj.id,
'messenger_id': obj.messenger_id}
)
class SyncHandler(tornado.web.RequestHandler):
def get(self):
"""
An traditional synchronous way
"""
obj = SyncHuman.create(messenger_id='12345')
self.write({
'id': obj.id,
'messenger_id': obj.messenger_id
})
app.add_handlers('', [
(r"/receive_async", AsyncHandler),
(r"/receive_sync", SyncHandler),
])
# Run loop
loop = asyncio.get_event_loop()
try:
loop.run_forever()
except KeyboardInterrupt:
print(" server stopped")
</code></pre>
<p>and this is what I get from Apache Benchmark:</p>
<pre><code>ab -n 100 -c 100 http://127.0.0.1:8888/receive_async
Connection Times (ms)
min mean[+/-sd] median max
Connect: 2 4 1.5 5 7
Processing: 621 1049 256.6 1054 1486
Waiting: 621 1048 256.6 1053 1485
Total: 628 1053 255.3 1058 1492
Percentage of the requests served within a certain time (ms)
50% 1058
66% 1196
75% 1274
80% 1324
90% 1409
95% 1452
98% 1485
99% 1492
100% 1492 (longest request)
ab -n 100 -c 100 http://127.0.0.1:8888/receive_sync
Connection Times (ms)
min mean[+/-sd] median max
Connect: 2 5 1.9 5 8
Processing: 8 476 277.7 479 1052
Waiting: 7 476 277.7 478 1052
Total: 15 481 276.2 483 1060
Percentage of the requests served within a certain time (ms)
50% 483
66% 629
75% 714
80% 759
90% 853
95% 899
98% 1051
99% 1060
100% 1060 (longest request)
</code></pre>
<p>why is sync faster? where is the bottleneck I'm missing?</p>
| 2 | 2016-10-01T06:37:17Z | 39,811,365 | <p>Database ORMs introduce many complexities for async architectures. There are several places within an ORM where blocking may take place and can be overwhelming to alter to an async form. The places where blocking takes place can also vary depending on the database. My guess as to why your results are so slow is because there's a lot of unoptimized calls to and from the event loop (I could be severely wrong, I mostly use SQLAlchemy or raw SQL these days). In my experience, it's generally quicker to execute database code in a thread and yield the result when it's available. I can't really speak for PeeWee, but SQLAlchemy is well suited to run in multiple threads and there aren't too many down sides (but the ones that do exist are very VERY annoying).</p>
<p>I'd recommend you try your experiment using <a href="https://docs.python.org/dev/library/concurrent.futures.html#threadpoolexecutor" rel="nofollow">ThreadPoolExecutor</a> and the synchronous Peewee module and run database functions in a thread. You will have to make changes to your main code, however it would be worth it if you ask me. For example, let's say you opt to use callback code, then your ORM queries might look like this:</p>
<pre class="lang-python prettyprint-override"><code>from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(max_workers=10)
def queryByName(name):
query = executor.submit(db_model.findOne, name=name)
query.add_done_callback(processResult)
def processResult(query):
orm_obj = query.results()
# do stuff with the results
</code></pre>
<p>You could use <code>yeild from</code> or <code>await</code> in coroutines, but it was a bit problematic for me. Also, I'm not well versed in coroutines yet. This snippet should work well with Tornado so long as devs are careful about deadlocks, db sessions, and transactions. These factors can really slow down your application if something goes wrong in the thread.</p>
<p>If you're feeling very adventurous, MagicStack (the company behind asyncio) has a project called <a href="https://github.com/magicstack/asyncpg" rel="nofollow"><code>asyncpg</code></a> and its supposed to be very fast! I've been meaning to try, but haven't found the time :(</p>
| 1 | 2016-10-01T20:51:27Z | [
"python",
"postgresql",
"tornado",
"python-asyncio",
"peewee"
]
|
Can't reshape array with numpy | 39,803,776 | <p>i want to change a image(17x15) to 2d array with code:</p>
<pre><code>from PIL import Image
import numpy as np
list = []
im = Image.open('plus1.jpg')
row,col = im.size
print(row,col)
for i in range (row):
for j in range (col):
r, g, b = im.getpixel((i, j))
list.append([r,g,b])
print(list)
print(len(list))
list = np.array(list)
print(list)
list.reshape(17,15)
</code></pre>
<p>It change okay to 1D array but when i using reshape to make 2D array with <code>list.reshape(17,15)</code> got the error:</p>
<pre><code>ValueError: total size of new array must be unchanged
</code></pre>
<p>The size is 17x15, and change to 1D array have 255 elements, so why the error appear and how to make it run normaly?</p>
| 2 | 2016-10-01T06:42:54Z | 39,804,185 | <p>Your image is 17x15, so there are 255 pixels. For each pixel, there are three color values (r,g,b). This means that your array <code>list</code> has shape <code>(255,1,3)</code>. This means that it contains 755 elements, and an error is raised when you try to reshape it to <code>(17,15)</code>, which does not preserve the number of elements. To obtain an array that has the first two dimensions the same as your image <code>(17,15)</code>, and a third axis that contains the rgb values, you should write:</p>
<pre><code>np.reshape(list, (17,15,3) )
</code></pre>
| 1 | 2016-10-01T07:40:39Z | [
"python",
"arrays",
"numpy"
]
|
How can I condense a 'for x in range' statement within a 'if' 'elif' statement within a 'while' statement | 39,803,878 | <p>I have a code that makes a math table and I feel has the possibility to be reduced as I have three of the same codes repeated but with only slightly different solutions for each of the if/elif statements. </p>
<pre><code>num=10
x=str(input("Enter Math Operation (+, -, *): "))
while (x != "+" and x != "-" and x != "*"):
x=str(input("\tEnter Math Operation: "))
if x=="+":
for table in range(1,11):
print(str(num),str(x),table,"=",num+table)
elif x=="-":
for table in range(1,11):
print(str(num),str(x),table,"=",num-table)
elif x=="*":
for table in range(1,11):
print(str(num),str(x),table,"=",num*table)
</code></pre>
<p>Please tell me how this code can be condensed.</p>
| 2 | 2016-10-01T06:58:53Z | 39,803,912 | <p>You can use a lookup table to store the different functions</p>
<pre><code>num=10
x=str(input("Enter Math Operation (+, -, *): "))
while (x != "+" and x != "-" and x != "*"):
x=str(input("\tEnter Math Operation: "))
ops = {
'+': lambda x, y: x+y,
'-': lambda x, y: x-y,
'*': lambda x, y: x*y}
fn = ops[x]
for table in range(1,11):
print(str(num),str(x),table,"=",fn(num,table))
</code></pre>
| 2 | 2016-10-01T07:05:00Z | [
"python",
"python-3.x"
]
|
How can I condense a 'for x in range' statement within a 'if' 'elif' statement within a 'while' statement | 39,803,878 | <p>I have a code that makes a math table and I feel has the possibility to be reduced as I have three of the same codes repeated but with only slightly different solutions for each of the if/elif statements. </p>
<pre><code>num=10
x=str(input("Enter Math Operation (+, -, *): "))
while (x != "+" and x != "-" and x != "*"):
x=str(input("\tEnter Math Operation: "))
if x=="+":
for table in range(1,11):
print(str(num),str(x),table,"=",num+table)
elif x=="-":
for table in range(1,11):
print(str(num),str(x),table,"=",num-table)
elif x=="*":
for table in range(1,11):
print(str(num),str(x),table,"=",num*table)
</code></pre>
<p>Please tell me how this code can be condensed.</p>
| 2 | 2016-10-01T06:58:53Z | 39,803,919 | <p>Functions are first class objects in python. Assign the right function to a variable, and then use it.</p>
<pre><code>num=10
x=str(input("Enter Math Operation (+, -, *): "))
# Read operation
while (x != "+" and x != "-" and x != "*"):
x=str(input("\tEnter Math Operation: "))
# Select appropriate function
if x=="+":
op = lambda x, y : x + y
elif x=="-":
op = lambda x, y : x - y
elif x=="*":
op = lambda x, y : x * y
# Use function
for table in range(1,11):
val = op(num, table)
print(str(num), str(x),table,"=", val)
</code></pre>
| 2 | 2016-10-01T07:06:22Z | [
"python",
"python-3.x"
]
|
How can I condense a 'for x in range' statement within a 'if' 'elif' statement within a 'while' statement | 39,803,878 | <p>I have a code that makes a math table and I feel has the possibility to be reduced as I have three of the same codes repeated but with only slightly different solutions for each of the if/elif statements. </p>
<pre><code>num=10
x=str(input("Enter Math Operation (+, -, *): "))
while (x != "+" and x != "-" and x != "*"):
x=str(input("\tEnter Math Operation: "))
if x=="+":
for table in range(1,11):
print(str(num),str(x),table,"=",num+table)
elif x=="-":
for table in range(1,11):
print(str(num),str(x),table,"=",num-table)
elif x=="*":
for table in range(1,11):
print(str(num),str(x),table,"=",num*table)
</code></pre>
<p>Please tell me how this code can be condensed.</p>
| 2 | 2016-10-01T06:58:53Z | 39,803,920 | <p>You would typically do something like this:</p>
<ul>
<li><p>Store the operator as a function in a variable</p></li>
<li><p>Use a dictionary to look up operators</p></li>
<li><p>Use <code>.format()</code> instead of putting lots of string pieces together</p></li>
<li><p>Don't use <code>str()</code> if the argument is already a string</p></li>
</ul>
<p>Here is what that looks like:</p>
<pre><code>import operator
x = 10
operators = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
}
while True:
op_name = input('Enter Math Operation ({}): '.format(', '.join(operators)))
op_func = operators.get(op_name)
if op_func is not None:
break
for y in range(1, 11):
print('{} {} {} = {}'.format(x, op_name, y, op_func(x, y)))
</code></pre>
| 6 | 2016-10-01T07:07:01Z | [
"python",
"python-3.x"
]
|
Setting global variables between classes with tKinter | 39,803,906 | <p>I am currently struggling to use input derived from another class (which uses tkinter) to alter outputs in a different class. This is my code:</p>
<pre><code>#there are many of these defs, this is just one i used as an example
def command_ssumowrestler(self):
self.master.withdraw()
toplevel = tk.Toplevel(self.master)
toplevel.geometry("30x70")
app=ClassConfirmation(toplevel)
global cs_hobby
cs_hobby = 'sumo_wrestler'
class ClassConfirmation:
def __init__ (self, master):
self.master = master
self.frame = tk.Frame(self.master)
confirmclass_label = tk.Label(master, width = 20, fg = 'blue',text= "Do You Wish to Proceed as:")
confirmclass_label.pack()
#here i use the variable defined and set globally in the previously block, which always leaves me with an error saying cs_hobby is not defined
classdescription_label = tk.Label(master, width =50, text='test ' + cs_hobby + ' hello')
classdescription_label.pack()
self.confirmclassButton = tk.Button(self.frame, text = 'Confirm', width = 20, command = self.close_windows)
self.confirmclassButton.pack()
self.frame.pack()
def close_windows (self):
self.master.withdraw()
app=dragonrealmP1
#this just opens a different class
</code></pre>
| -1 | 2016-10-01T07:04:20Z | 39,804,244 | <p><code>global</code> doesn't create variable - it only informs function/method to use global variable instead of local variable. First you have to create this variable before classes.</p>
<hr>
<p>BTW: if you use classes so why don't you use in first class</p>
<pre><code>self.cs_hobby = 'sumo_wrestler'
</code></pre>
<p>and in <code>ClassConfirmation</code></p>
<pre><code>sone_object_name.cs_hobby
</code></pre>
<p>or</p>
<pre><code>app = ClassConfirmation(toplevel, 'sumo_wrestler')
class ClassConfirmation:
def __init__ (self, master, cs_hobby):
# here use cs_hobby
</code></pre>
<hr>
<p><strong>EDIT:</strong></p>
<p>First: <code>global cs_hobby</code> doesn't create global variable. It only inform function to use global <code>cs_hobby</code> instead of local <code>cs_hobby</code></p>
<p>to work with <code>global</code> you need </p>
<pre><code>cs_hobby = "" # create global variable (outside classes)
def command_ssumowrestler(self):
global cs_hobby # inform function to use global variable
# rest
cs_hobby = 'sumo_wrestler' # set value in global variable
app = ClassConfirmation(toplevel)
class ClassConfirmation:
def __init__ (self, master):
global cs_hobby # inform function to use global variable
# rest
print(cs_hobby) # get value from global variable
cs_hobby = 'tenis' # set value in global variable
</code></pre>
<p>to work without global variable you need </p>
<pre><code>def command_ssumowrestler(self):
self.cs_hobby = 'sumo_wrestler' # create local variable
app = ClassConfirmation(toplevel, self.cs_hobby) # send local value to another class
self.cs_hobby = app.cs_hobby # receive value from another class
class ClassConfirmation:
def __init__ (self, master, hobby):
self.cs_hobby = hobby # create local variable and assign value
# rest
print(self.cs_hobby) # use local value
self.cs_hobby = 'tenis' # use local value
</code></pre>
| 1 | 2016-10-01T07:49:51Z | [
"python",
"class",
"variables",
"tkinter"
]
|
Why is `self` not used in this method? | 39,803,950 | <p>I was under the impression that methods within Python classes <em>always</em> require the <code>self</code> argument (I know that it doesn't actually have to be <code>self</code>, just some keyword). But, this class that I wrote doesn't require it:</p>
<pre><code>import ZipFile
import os
class Zipper:
def make_archive(dir_to_zip):
zf = zipfile.ZipFile(dir_to_zip + '.zip', 'w')
for filename in files:
zf.write(os.path.join(dirname, filename))
zf.close()
</code></pre>
<p>See? No <code>self</code>. When I include a <code>self</code> argument to <code>make_archive</code>, I get a <code>TypeError: make_archive() missing one positional argument</code> error. In my search to figure out why this is happening, I actually copied and tried to run a similar program from the docs:</p>
<pre><code>class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
print(MyClass.f()) # I added this statement to have a call line
</code></pre>
<p>and I get the same error! </p>
<pre><code>TypeError: f() missing 1 required positional argument: 'self'
</code></pre>
<p>In the same module that contains the <code>Zipper()</code> class, I have multiple classes that all make use of <code>self</code>. I don't understand the theory here, which makes it difficult to know when to do what, especially since a program copied directly from the docs (<a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow">this is the docs page</a>) failed when I ran it. I'm using Python 3.5 and 3.4 on Debian Linux. The only thing that I can think of is that it's a static method (and the <code>Zipper.make_archive()</code> as written above works fine if you include <code>@staticmethod</code> above the <code>make_archive</code> method), but I can't find a good explanation to be sure.</p>
| 1 | 2016-10-01T07:10:45Z | 39,803,983 | <p>You are trying to use it as a static method. In your example;</p>
<pre><code>class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
a = MyClass()
a.f() # This should work.
</code></pre>
<p>Calling <code>MyClass.f()</code> assumes <code>f</code> is static for <code>MyClass</code>. You can make it static as:</p>
<pre><code>class MyClass:
@staticmethod
def f(): # No self here
return 'hello world'
MyClass.f()
</code></pre>
| 0 | 2016-10-01T07:14:52Z | [
"python",
"python-3.x",
"typeerror",
"self"
]
|
Why is `self` not used in this method? | 39,803,950 | <p>I was under the impression that methods within Python classes <em>always</em> require the <code>self</code> argument (I know that it doesn't actually have to be <code>self</code>, just some keyword). But, this class that I wrote doesn't require it:</p>
<pre><code>import ZipFile
import os
class Zipper:
def make_archive(dir_to_zip):
zf = zipfile.ZipFile(dir_to_zip + '.zip', 'w')
for filename in files:
zf.write(os.path.join(dirname, filename))
zf.close()
</code></pre>
<p>See? No <code>self</code>. When I include a <code>self</code> argument to <code>make_archive</code>, I get a <code>TypeError: make_archive() missing one positional argument</code> error. In my search to figure out why this is happening, I actually copied and tried to run a similar program from the docs:</p>
<pre><code>class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
print(MyClass.f()) # I added this statement to have a call line
</code></pre>
<p>and I get the same error! </p>
<pre><code>TypeError: f() missing 1 required positional argument: 'self'
</code></pre>
<p>In the same module that contains the <code>Zipper()</code> class, I have multiple classes that all make use of <code>self</code>. I don't understand the theory here, which makes it difficult to know when to do what, especially since a program copied directly from the docs (<a href="https://docs.python.org/3/tutorial/classes.html" rel="nofollow">this is the docs page</a>) failed when I ran it. I'm using Python 3.5 and 3.4 on Debian Linux. The only thing that I can think of is that it's a static method (and the <code>Zipper.make_archive()</code> as written above works fine if you include <code>@staticmethod</code> above the <code>make_archive</code> method), but I can't find a good explanation to be sure.</p>
| 1 | 2016-10-01T07:10:45Z | 39,805,148 | <p>The thing with <code>self</code> is that it's added <em>implicitly</em>. That is, the calling code says <code>Myclass().f()</code>, but the callee sees <code>Myclass().f(self)</code>. It also implies that the method is called from some instance of <code>Myclass</code>, which is placed in <code>self</code> variable. The point is that methods are probably somehow using and/or modifying instance data (otherwise why would they be in that class?) and it's handy to have the instance in question automatically supplied.</p>
<p>If you don't need the instance data, you should use either <code>@staticmethod</code> if it's actually more like a function than object method or <code>@classmethod</code> if the method is meant to be inherited and possibly used differently by different classes. See @pankaj-daga answer for a little intro to staticmethods.</p>
<p>The <code>Foo.bar()</code> syntax is also used by functions imported via <code>import Foo</code> instead of <code>from Foo import bar</code>, which is also a possible source of confusion. That, for your purposes, is an entirely different thing.</p>
| 0 | 2016-10-01T09:45:50Z | [
"python",
"python-3.x",
"typeerror",
"self"
]
|
using numpy to calculate mean | 39,803,952 | <p>I am trying to calculate the mean of GNP for each country from 2006 to 2015. But when I apply the aggregation with mean function, it will not calculate the mean from 2006 to 2015. Instead, it just display the values for each year. Pls tell me what went wrong? I am able to sort by country but the mean just wont work on the data.</p>
<pre><code>wb_indicator = 'NY.GNP.ATLS.CD'
start_year = 2006
end_year = 2015
df_ex = wb.download(indicator = wb_indicator,
country = ['all'],
start = start_year,
end = end_year)
df_ex1 = df_ex.reset_index()
df_ex1.groupby(['country']).agg({'NY.GNP.ATLS.CD': [np.mean]})
df_ex1.head(20)
</code></pre>
<p>Output:</p>
<blockquote>
<p>country year NY.GNP.ATLS.CD 0 Arab World 2015 2.767920e+12 1 Arab
World 2014 2.897113e+12 2 Arab World 2013 2.832769e+12 3 Arab
World 2012 2.590610e+12 4 Arab World 2011 2.190786e+12 5 Arab
World 2010 2.055967e+12 6 Arab World 2009 1.932056e+12 7 Arab
World 2008 1.858270e+12 8 Arab World 2007 1.547924e+12 9 Arab
World 2006 1.312967e+12 10 Caribbean small states 2015 6.680302e+10
11 Caribbean small states 2014 6.664219e+10</p>
</blockquote>
| 0 | 2016-10-01T07:11:02Z | 39,804,414 | <p>This should work</p>
<pre><code>import pandas as pd
import wbdata as wb
import datetime
wb_indicator = 'NY.GNP.ATLS.CD'
data_date = (datetime.datetime(2006, 1, 1), datetime.datetime(2015, 1, 1))
data = wb.get_data(wb_indicator, data_date=data_date, pandas=True)
gnp_means = data.reset_index().groupby('country').mean()
</code></pre>
| 0 | 2016-10-01T08:14:07Z | [
"python",
"python-2.7"
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.