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 |
|---|---|---|---|---|---|---|---|---|---|
Class definition from shelve | 37,953,631 | <p>I'm using python 3.5. Fairly new to python but not new to programming. I have three source files as follows (a much simplified version of what I'm actually doing):</p>
<p>c.py</p>
<pre><code>class C:
def __init__(self, x):
self.x = x
def method(self):
print(self.x)
</code></pre>
<p>init.py</p>
<pre><... | 1 | 2016-06-21T20:05:28Z | 37,953,756 | <p>When shelve serializes an object (I believe by pickling it), it stores the import path to the class for unpickling later. When it retrieves the object, <code>pickle</code> imports the module (<code>c</code>) and returns an instance of <code>C</code> back to you (that is equivalent to the one that was originally ser... | 4 | 2016-06-21T20:13:15Z | [
"python",
"python-3.x"
] |
Class definition from shelve | 37,953,631 | <p>I'm using python 3.5. Fairly new to python but not new to programming. I have three source files as follows (a much simplified version of what I'm actually doing):</p>
<p>c.py</p>
<pre><code>class C:
def __init__(self, x):
self.x = x
def method(self):
print(self.x)
</code></pre>
<p>init.py</p>
<pre><... | 1 | 2016-06-21T20:05:28Z | 37,954,382 | <p>What you have doesn't work for the reasons stated in <a href="http://stackoverflow.com/a/37953756/355230">mgilson's answer</a>.</p>
<p>A work-around for the problem would be to manually import the class from the module and assign the class to the name <code>C</code> â something along these lines (tested with Pyth... | 1 | 2016-06-21T20:53:13Z | [
"python",
"python-3.x"
] |
How to check in a file if the string with another string exists in file? | 37,953,704 | <p>How to check in file if the string exists and some string is next to it.
To be precise, I have the following code:</p>
<pre><code>with open ('CTF.txt', 'r') as myfile:
strings = (validationforvote, "voted")
for line in myfile:
if any(s in line for s in strings):
pr... | 0 | 2016-06-21T20:09:31Z | 37,953,873 | <p>Currently, it'll print if <em>either</em> validationforvote <em>or</em> 'voted' is in the line- which means every time 'voted' is there, it prints. Your conditional should be more like:</p>
<pre><code>if (" ".join(strings) in line):
</code></pre>
<p>So it constructs the thing you're looking for, i.e. <code>"9779 v... | -1 | 2016-06-21T20:21:25Z | [
"python"
] |
How to check in a file if the string with another string exists in file? | 37,953,704 | <p>How to check in file if the string exists and some string is next to it.
To be precise, I have the following code:</p>
<pre><code>with open ('CTF.txt', 'r') as myfile:
strings = (validationforvote, "voted")
for line in myfile:
if any(s in line for s in strings):
pr... | 0 | 2016-06-21T20:09:31Z | 37,953,918 | <p>You can try to use regular expression operations:</p>
<pre><code>import re
with open ('CTF.txt', 'r') as myfile:
result=re.search(str(validationforvote)+' voted$', myfile.read())
if result:
print "you cannot vote twice"
myfile.close()
</code></pre>
| 0 | 2016-06-21T20:23:43Z | [
"python"
] |
How to check in a file if the string with another string exists in file? | 37,953,704 | <p>How to check in file if the string exists and some string is next to it.
To be precise, I have the following code:</p>
<pre><code>with open ('CTF.txt', 'r') as myfile:
strings = (validationforvote, "voted")
for line in myfile:
if any(s in line for s in strings):
pr... | 0 | 2016-06-21T20:09:31Z | 37,953,951 | <p>You have a few issues.</p>
<blockquote>
<p>First is that your <code>if</code> statement is checking if <code>validationforvote</code> or <code>voted</code> is in the line, that is preventing your code from functioning as you expect. </p>
<p>Second, if you open a file using <code>with open(...) as myfile</cod... | 0 | 2016-06-21T20:25:55Z | [
"python"
] |
How to check in a file if the string with another string exists in file? | 37,953,704 | <p>How to check in file if the string exists and some string is next to it.
To be precise, I have the following code:</p>
<pre><code>with open ('CTF.txt', 'r') as myfile:
strings = (validationforvote, "voted")
for line in myfile:
if any(s in line for s in strings):
pr... | 0 | 2016-06-21T20:09:31Z | 37,954,076 | <p>If your data is structured just like in your example you can do this:</p>
<pre><code>with open("myfile") as open_file:
# read the file and split it on each newline
f=open_file.read().split('\n')
for line in f:
# check if any of the lines start with validationforvote
# and has allready voted
... | 0 | 2016-06-21T20:33:44Z | [
"python"
] |
Why does passing a tuple cause a key error in pandas? | 37,953,707 | <p>I know that I can select multiple columns if I pass a <em>list</em> of the column names. I was surprised to find that I can't pass a <em>tuple</em> of column names.</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[2,3,4],[3,4,5]],columns=['a','b','c'])
print df[['a','b']]
print df[('a','b')] # Key error
</c... | 4 | 2016-06-21T20:09:43Z | 37,953,759 | <p>You can have column name as <code>tuple</code>, so then use for selecting <code>tuple</code>:</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[2,3,4],[3,4,5]],columns=[('a', 'b'),'b','c'])
print (df)
(a, b) b c
0 2 3 4
1 3 4 5
print (df[('a','b')])
0 2
1 3
Name: (a, b), dtype: int... | 4 | 2016-06-21T20:13:23Z | [
"python",
"pandas"
] |
Why does passing a tuple cause a key error in pandas? | 37,953,707 | <p>I know that I can select multiple columns if I pass a <em>list</em> of the column names. I was surprised to find that I can't pass a <em>tuple</em> of column names.</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[2,3,4],[3,4,5]],columns=['a','b','c'])
print df[['a','b']]
print df[('a','b')] # Key error
</c... | 4 | 2016-06-21T20:09:43Z | 37,953,803 | <pre><code>df = pd.DataFrame([[2,3,4],[3,4,5]],columns=[('a','b','c'])
df.columns
#Index([u'a', u'b', u'c'], dtype='object')
</code></pre>
<p>You do not have key <code>('a','b')</code>, only <code>'a', 'b', 'c'</code> keys exits.. </p>
| 3 | 2016-06-21T20:16:17Z | [
"python",
"pandas"
] |
Why does passing a tuple cause a key error in pandas? | 37,953,707 | <p>I know that I can select multiple columns if I pass a <em>list</em> of the column names. I was surprised to find that I can't pass a <em>tuple</em> of column names.</p>
<pre><code>import pandas as pd
df = pd.DataFrame([[2,3,4],[3,4,5]],columns=['a','b','c'])
print df[['a','b']]
print df[('a','b')] # Key error
</c... | 4 | 2016-06-21T20:09:43Z | 37,953,909 | <p>Tuples are also used to select a column from a DataFrame with a MultiIndex:</p>
<pre><code>import pandas as pd
columns = pd.MultiIndex.from_arrays([['a','b','c'], ['X','Y','Z']])
df = pd.DataFrame([[2,3,4],[3,4,5]], columns=columns)
# a b c
# X Y Z
# 0 2 3 4
# 1 3 4 5
</code></pre>
<p>then</p>
<pr... | 3 | 2016-06-21T20:22:50Z | [
"python",
"pandas"
] |
Spark SQL performance - JOIN on value BETWEEN min and max | 37,953,830 | <p>I have two files in which I store:</p>
<ol>
<li>an IP range - country lookup </li>
<li>a list of requests coming from different IPs</li>
</ol>
<p>The IPs are stored as integers (using inet_aton()). </p>
<p>I tried using Spark SQL to join these pieces of data by loading both files into dataframes and registering t... | 1 | 2016-06-21T20:18:26Z | 37,955,947 | <p>The source of the problem is pretty simple. When you execute join and join condition is not equality based the only thing that Spark can do right now is expand it to Cartesian product followed by filter what is pretty much what happens inside <code>BroadcastNestedLoopJoin</code>. So logically you have this huge nest... | 0 | 2016-06-21T23:01:06Z | [
"python",
"apache-spark",
"pyspark",
"apache-spark-sql"
] |
Date Class - Method to figure out day of the week of the Date object that calls it | 37,953,857 | <p>I built a Date Class that has a tomorrow method, add_n_days method, equals method, before and after methods, and a difference method. What I'm trying to figure out is how to use my difference method to create a new method where I figure out the day of the week the Date object falls on.</p>
<pre><code> # A class to ... | 1 | 2016-06-21T20:19:59Z | 37,953,932 | <p>If I told you that 1/1/2000 was a Monday and asked you what day of the week was 50 days later, it would be easy to figure out. </p>
<p>It's simply 50 % 7, which is 1. Therefore, we know that the day of the week we are looking at is one day past the day we know.</p>
<p>So 50 days later would be a Tuesday, or 1 day ... | 3 | 2016-06-21T20:24:26Z | [
"python",
"class",
"oop",
"object",
"methods"
] |
Date Class - Method to figure out day of the week of the Date object that calls it | 37,953,857 | <p>I built a Date Class that has a tomorrow method, add_n_days method, equals method, before and after methods, and a difference method. What I'm trying to figure out is how to use my difference method to create a new method where I figure out the day of the week the Date object falls on.</p>
<pre><code> # A class to ... | 1 | 2016-06-21T20:19:59Z | 37,954,170 | <p>The following pseudo code, cited from <a href="https://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week#Other_purely_mathematical_algorithms" rel="nofollow">wikipedia</a> should help you get started. It depends on integer division, so remember to use <code>//</code> in python to get 'c-like' integer divisi... | 0 | 2016-06-21T20:39:25Z | [
"python",
"class",
"oop",
"object",
"methods"
] |
Create Sparse Matrix in Python | 37,953,877 | <p>Working with data and would like to create a sparse matrix to later be used for clustering purposes.</p>
<pre><code>fileHandle = open('data', 'r')
for line in fileHandle:
json_list = []
fields = line.split('\t')
json_list.append(fields[0])
json_list.append(fields[1])
json_list.append(fields[3])... | 0 | 2016-06-21T20:21:34Z | 37,954,457 | <p>I have a lazy method</p>
<pre><code>data = [['term', 'ids', 'quantity'],
... ['buick', ['123', '234'], 500],
... ['chevy', ['345', '456'], 300],
... ['suv', ['123', '567'], 100]]
res = []
for i,line in enumerate(data):
... if i == 0:
... header = line
... else:
... temp = {}
... for... | 0 | 2016-06-21T20:58:40Z | [
"python",
"numpy",
"scikit-learn",
"sparse-matrix",
"sklearn-pandas"
] |
Create Sparse Matrix in Python | 37,953,877 | <p>Working with data and would like to create a sparse matrix to later be used for clustering purposes.</p>
<pre><code>fileHandle = open('data', 'r')
for line in fileHandle:
json_list = []
fields = line.split('\t')
json_list.append(fields[0])
json_list.append(fields[1])
json_list.append(fields[3])... | 0 | 2016-06-21T20:21:34Z | 37,958,713 | <p><code>scikit_learn</code> probably has the tools to do this easily, but I'll demonstrate a basic Python/numpy solution.</p>
<p>The raw data - a list of lists</p>
<pre><code>In [1150]: data=[['buick', '123,234', '500'],
['chevy', '345,456', '300'],
['suv','123', '100']]
</code></pr... | 0 | 2016-06-22T04:42:26Z | [
"python",
"numpy",
"scikit-learn",
"sparse-matrix",
"sklearn-pandas"
] |
Is it possible to use psycopg2 with IronPython in a Windows Form app? | 37,953,926 | <p>I built a Windows Form to gather information about projects. This information is then uploaded to a database. </p>
<p>Actually, I'm using a Python script to do that (the required information is therefore hardcoded in the script by the user).</p>
<p>I would like to use my WindowsForm to set the variable for my scri... | 1 | 2016-06-21T20:24:10Z | 37,954,200 | <p>The psycopg2 module uses a CPython extension and will therefore not work with IronPython. There is an experimental <a href="https://github.com/mvantellingen/psycopg2-ctypes" rel="nofollow">ctypes version</a> which is no longer supported by the author.</p>
<p>In any case, you need to install the according package. D... | 2 | 2016-06-21T20:41:24Z | [
"c#",
"python",
".net",
"ironpython",
"psycopg2"
] |
GenButton alignment wxpython | 37,953,970 | <p>i am struggling to find an answer to the alignment of my GenButton,
i have looked through the docs on wxpython website and cant see any option in there to address this, hopefully one of you guys can point me in the right direction, as i need to align my buttons to the center of the catpanel, here is my code so far.<... | 1 | 2016-06-21T20:27:23Z | 37,962,264 | <p>GUI toolkits tend to be smart about size of controls: You specified the height of our <code>GenButton</code> instance but not the width (<code>size=(-1, 40)</code>). If you adapt the button width to the parent panel width, you will get what you want (<code>size=(1024, 40)</code>).</p>
<p>However, this is not what y... | 1 | 2016-06-22T08:14:16Z | [
"python",
"wxpython"
] |
Process multiple directories and all files within using snakemake | 37,953,972 | <p>I've got a directory with 10 sub-directories (dir01 to dir10) and a number of files in each of those (new files are added every day to the sub-directories).</p>
<p>I'm trying to write a <code>snakemake</code> file that will go through all of the sub-directories and all the files and process them (run my <code>conve... | 0 | 2016-06-21T20:27:25Z | 39,229,546 | <p>Have you checked this <a href="https://bitbucket.org/snakemake/snakemake/wiki/FAQ#markdown-header-how-do-i-run-my-rule-on-all-files-of-a-certain-directory" rel="nofollow">FAQ entry</a>?</p>
<p>Try this:</p>
<pre><code>directories, files = glob_wildcards("data01/{dir}/{file}")
rule all:
input:
expand("... | 0 | 2016-08-30T13:58:09Z | [
"python",
"linux",
"snakemake"
] |
Proper way to install pip on Ubuntu | 37,954,008 | <p>I'm trying to install the latest version of pip (currently 8.1.2) on the official ubuntu/trusty64 Vagrant box. The box comes with Python 2.7.6 and 3.4.3 pre-installed with apt-get.</p>
<p>I read the <a href="https://pip.pypa.io/en/stable/installing/" rel="nofollow">pip installation doc</a> and it contains the follo... | 0 | 2016-06-21T20:29:43Z | 37,954,088 | <p>Try download install package from <a href="https://pypi.python.org/pypi/pip#downloads" rel="nofollow">https://pypi.python.org/pypi/pip#downloads</a> and use <code>python setup.py install</code> </p>
| 0 | 2016-06-21T20:34:28Z | [
"python",
"pip"
] |
Proper way to install pip on Ubuntu | 37,954,008 | <p>I'm trying to install the latest version of pip (currently 8.1.2) on the official ubuntu/trusty64 Vagrant box. The box comes with Python 2.7.6 and 3.4.3 pre-installed with apt-get.</p>
<p>I read the <a href="https://pip.pypa.io/en/stable/installing/" rel="nofollow">pip installation doc</a> and it contains the follo... | 0 | 2016-06-21T20:29:43Z | 37,954,136 | <p>I believe that you can install it on Ubuntu with</p>
<pre><code>sudo apt-get install python-pip
</code></pre>
<p>or </p>
<pre><code>sudo apt-get install python3-pip
</code></pre>
<p>for Python 3. Sure, it's an older version but its functionality is there.</p>
| 0 | 2016-06-21T20:37:09Z | [
"python",
"pip"
] |
identifying an individual usb device in python | 37,954,014 | <p>I'm working with some python where I have 5 usb devices plugged into the computer and I'm interacting with them. I've been programming for a number of years in php, but I'm pretty new to the application side. I am currently looking for a way to uniquely identify a device such as a device serial number, one that isn'... | 0 | 2016-06-21T20:30:11Z | 37,955,162 | <p>I'm not sure what platform you're using, but a cross-platform solution to dealing with serial ports is PySerial:</p>
<p><a href="https://pypi.python.org/pypi/pyserial" rel="nofollow">https://pypi.python.org/pypi/pyserial</a></p>
| 0 | 2016-06-21T21:48:45Z | [
"python"
] |
__repr__ on Windows doesn't show carriage return in terminal | 37,954,072 | <p>I am trying to test csv files generated using <code>csv.writer</code> on python 2 & 3 on Linux (Ubuntu 16.04 x64) and Windows(x64). Unfortunately, Windows adds an extra <code>\r</code> everytime it writes to a file. </p>
<p>I thought I would debug this by trying to print <code>repr</code> of the lines in these ... | 0 | 2016-06-21T20:33:34Z | 37,955,063 | <p>I found a utility called <code>dos2unix</code> installable through <code>pip</code>.</p>
<p>To convert all <code>\r\n</code> instances to <code>\n</code> instances of my csv file, I can use this code:</p>
<pre><code>import os
os.system("dos2unix -n "+filename+" "+filename)
</code></pre>
| 0 | 2016-06-21T21:42:08Z | [
"python",
"windows",
"csv",
"carriage-return",
"repr"
] |
__repr__ on Windows doesn't show carriage return in terminal | 37,954,072 | <p>I am trying to test csv files generated using <code>csv.writer</code> on python 2 & 3 on Linux (Ubuntu 16.04 x64) and Windows(x64). Unfortunately, Windows adds an extra <code>\r</code> everytime it writes to a file. </p>
<p>I thought I would debug this by trying to print <code>repr</code> of the lines in these ... | 0 | 2016-06-21T20:33:34Z | 37,960,429 | <p>The problem is that windows and linux define the end of line marker differently. For linux it's just line feed <code>'\n'</code>, but for windows it is line feed followed by carriage return <code>'\r\n'</code>. </p>
<p>When you open a file for writing in text mode in Python on Windows any line feed characters are a... | 0 | 2016-06-22T06:44:18Z | [
"python",
"windows",
"csv",
"carriage-return",
"repr"
] |
python 4 way recursive Flood Fill of a curve | 37,954,082 | <p>I am trying to use the flood fill algorithm to fill in one of the two colors of this curve, which is defined with red being 1 and blue being zero. However, when I try to run my code, it says that the syntax for the line <code>if m[i][j]=1:</code> is incorrect. Any advice on how to debug this? Thanks. In this code... | 0 | 2016-06-21T20:34:06Z | 37,954,178 | <p>You didn't post the exact error, but I can tell you that this is incorrect:</p>
<pre><code>m[i,j]=sin(i+j+0.1*i*j+0.1*j*j)+cos(i-j+0.2*i*i)
</code></pre>
<p><code>m[i,j]</code> is incorrect. <code>i,j</code> is a tuple, but list indices (the thing inside the <code>m[]</code> brackets) can only be integers</p>
| 2 | 2016-06-21T20:39:51Z | [
"python",
"python-2.7",
"python-3.x",
"flood-fill"
] |
python 4 way recursive Flood Fill of a curve | 37,954,082 | <p>I am trying to use the flood fill algorithm to fill in one of the two colors of this curve, which is defined with red being 1 and blue being zero. However, when I try to run my code, it says that the syntax for the line <code>if m[i][j]=1:</code> is incorrect. Any advice on how to debug this? Thanks. In this code... | 0 | 2016-06-21T20:34:06Z | 37,954,189 | <p>Values are to be compared for equality using <code>==</code> operator rather than a single <code>=</code> which is used for assignment expressions. So you should replace <code>if m[i][j]=1:</code> with <code>if m[i][j] == 1</code>. </p>
<p>And BTW, it did say "Syntax Error", so you should check the syntax of the li... | 2 | 2016-06-21T20:40:27Z | [
"python",
"python-2.7",
"python-3.x",
"flood-fill"
] |
run custom django manage.py command with shell script while passing in settings | 37,954,167 | <p>Using django 1.5</p>
<p>I want to use a shell script to run a custom django manage.py command while I'm passing in the settings (i.e. not using the settings from the same directory).</p>
<p><strong>As an example of passing in my settings, if I run my django development server I'd do so like this:</strong></p>
<p>... | 0 | 2016-06-21T20:39:09Z | 37,957,733 | <p>The problem is likely with you <code>INSTALLED_APPS</code> list. Check your <code>settings.py</code> file to confirm that <code>my.namespace</code> is included in the <code>INSTALLED_APPS</code> settings.</p>
| 1 | 2016-06-22T02:55:11Z | [
"python",
"linux",
"django",
"bash",
"shell"
] |
How does Django ModelBackend.authenticate work? | 37,954,187 | <p>I am looking into the <a href="https://github.com/django/django/blob/master/django/contrib/auth/backends.py" rel="nofollow">ModelBackend</a>. </p>
<pre><code>def authenticate(self, username=None, password=None, **kwargs):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserMo... | 0 | 2016-06-21T20:40:18Z | 37,955,110 | <p><code>authenticate()</code> doesn't 'work' by itself.</p>
<p>If your project or application implements a login form then you, or the developer of the app you use for authentication, will call <code>authenticate()</code>.</p>
<p>For example, if you have a login form with a <code>username</code> & <code>password... | 1 | 2016-06-21T21:45:40Z | [
"python",
"django",
"authentication"
] |
upgrade version of Pandas | 37,954,195 | <p>I am running python on a windows machine at the following path:</p>
<pre><code>C:\WinPython-64bit-3.4.4.1
</code></pre>
<p>I am trying to upgrade to the latest version of pandas (currently running '0.17.1') but am having problems.</p>
<p>I have looked at previous posts and have tried on the command line using :</... | -2 | 2016-06-21T20:40:54Z | 37,966,719 | <p>Type the following command:</p>
<pre><code>conda update pandas
</code></pre>
<p>Type this in your preferred shell (on Windows, use cmd).</p>
| 1 | 2016-06-22T11:29:01Z | [
"python",
"pandas"
] |
upgrade version of Pandas | 37,954,195 | <p>I am running python on a windows machine at the following path:</p>
<pre><code>C:\WinPython-64bit-3.4.4.1
</code></pre>
<p>I am trying to upgrade to the latest version of pandas (currently running '0.17.1') but am having problems.</p>
<p>I have looked at previous posts and have tried on the command line using :</... | -2 | 2016-06-21T20:40:54Z | 37,966,781 | <p>try </p>
<pre><code>pip3 -install --upgrade pandas
</code></pre>
| 0 | 2016-06-22T11:31:55Z | [
"python",
"pandas"
] |
upgrade version of Pandas | 37,954,195 | <p>I am running python on a windows machine at the following path:</p>
<pre><code>C:\WinPython-64bit-3.4.4.1
</code></pre>
<p>I am trying to upgrade to the latest version of pandas (currently running '0.17.1') but am having problems.</p>
<p>I have looked at previous posts and have tried on the command line using :</... | -2 | 2016-06-21T20:40:54Z | 37,968,438 | <p>Add your C:\WinPython-64bit-3.4.4.1\python_***\Scripts folder to your system PATH variable by doing the following:</p>
<ol>
<li>Select Start, select Control Panel. double click System, and select
the Advanced tab.</li>
<li><p>Click Environment Variables. ...</p></li>
<li><p>In the Edit System Variable (or New Syste... | 1 | 2016-06-22T12:44:46Z | [
"python",
"pandas"
] |
Tab indent in Linux and Jedit | 37,954,211 | <p>Ive been using Jedit for programming for a few days and I wonder how I can change the tab indent in Jedit. Or can I change the Indent for whole Linux? My second question: I use Python and I would like to have an Indent in the next line after colons. where are the settings for this? </p>
| 0 | 2016-06-21T20:42:10Z | 37,954,337 | <p>Indentation can be configured by navigating to <strong>Utilities > Global Options > Editing > Tab width</strong>. You said you are coding in python so I strongly recommend that you leave the indentation as it is as python only accepts indentation with standard tabs (4 spaces long).</p>
<p><em>Obs: I see no reason w... | 0 | 2016-06-21T20:50:30Z | [
"python",
"linux",
"python-3.x"
] |
Poor sympy linsolve/ solve performance | 37,954,278 | <p>I'm using sympy to solve a simple linear system of equations.</p>
<p>It's a coupled ODE, there are time-derivatives of variables and I need to solve the system of equations for the highest derivatives.
Since sympy doesn't allow me to solve for statements like <code>phi_1.diff(t)</code>, I've replaced all derivative... | 2 | 2016-06-21T20:45:49Z | 38,022,049 | <p><code>solve</code> (not <code>linsolve</code>) has some flags that you can set which can make it faster:</p>
<ul>
<li><code>simplify=False</code>: disables simplification of the result. </li>
<li><code>rational=False</code>: disables the automatic conversion of floats to rationals.</li>
</ul>
<p>There is a warning... | 2 | 2016-06-24T20:59:47Z | [
"python",
"performance",
"math",
"simulation",
"sympy"
] |
How to load one line at a time from a pickle file? | 37,954,324 | <p>I have a large dataset: 20,000 x 40,000 as a numpy array. I have saved it as a pickle file.</p>
<p>Instead of reading this huge dataset into memory, I'd like to only read a few (say 100) rows of it at a time, for use as a minibatch.</p>
<p>How can I read only a few randomly-chosen (without replacement) lines from ... | 4 | 2016-06-21T20:49:10Z | 37,954,716 | <p>Since you do not know the internal workings of pickle, you need to use another storing method. The script below uses the <code>tobytes()</code> functions to save the data line-wise in a raw file.</p>
<p>Since the length of each line is known, it's offset in the file can be computed and accessed via <code>seek()</co... | 2 | 2016-06-21T21:16:27Z | [
"python",
"numpy",
"pickle"
] |
How to load one line at a time from a pickle file? | 37,954,324 | <p>I have a large dataset: 20,000 x 40,000 as a numpy array. I have saved it as a pickle file.</p>
<p>Instead of reading this huge dataset into memory, I'd like to only read a few (say 100) rows of it at a time, for use as a minibatch.</p>
<p>How can I read only a few randomly-chosen (without replacement) lines from ... | 4 | 2016-06-21T20:49:10Z | 37,955,250 | <p>You can write pickles incrementally to a file, which allows you to load them
incrementally as well.</p>
<p>Take the following example. Here, we iterate over the items of a list, and
pickle each one in turn.</p>
<pre><code>>>> import cPickle
>>> myData = [1, 2, 3]
>>> f = open('mydata.pkl... | 1 | 2016-06-21T21:56:01Z | [
"python",
"numpy",
"pickle"
] |
How to load one line at a time from a pickle file? | 37,954,324 | <p>I have a large dataset: 20,000 x 40,000 as a numpy array. I have saved it as a pickle file.</p>
<p>Instead of reading this huge dataset into memory, I'd like to only read a few (say 100) rows of it at a time, for use as a minibatch.</p>
<p>How can I read only a few randomly-chosen (without replacement) lines from ... | 4 | 2016-06-21T20:49:10Z | 38,003,329 | <p>Thanks everyone. I ended up finding a workaround (a machine with more RAM so I could actually load the dataset into memory). </p>
| 0 | 2016-06-23T23:13:10Z | [
"python",
"numpy",
"pickle"
] |
Regular expression groups not finding generic token | 37,954,426 | <p>I'm trying to reduce a string down to the following tokens: singlequote, right paren, lparen, integer, whitespace and ID. ID being anything that isn't any of the others. My tokenizer isn't finding IDs.</p>
<pre><code>import re
import collections
QUOTE = r'(?P<QUOTE>\')'
LPAREN = r'(?P<LPAREN>\()'
RPAR... | -1 | 2016-06-21T20:56:22Z | 37,954,562 | <pre><code>ID = r'(?P<ID>[^\d\'\(\)\s]+)'
</code></pre>
<p>Fixed a typo, and grab everything that isn't one of the other tokens.</p>
| 1 | 2016-06-21T21:05:12Z | [
"python",
"regex"
] |
Concatinate to pandas data frame from OrderedDict - Python equivalent to R´s do.call(merge, list) | 37,954,450 | <p>I have an ordered dictionary <code>"my_dict</code>", which gets filled with <code>n</code> time series during a loop. All <code>n</code> time series have the same length and are 1-dimensional. They all have a datetime index.</p>
<p>In R I just run <code>do.call(merge, my_dict)</code>, where <code>my_dict</code> is ... | -2 | 2016-06-21T20:58:26Z | 37,958,347 | <p>A <code>pandas.DataFrame</code> can be constructed directly from a dictionary so all you need to do is pass <code>my_dict</code> to the <code>pandas.DataFrame</code> constructor (i.e., <code>pandas.DataFrame(my_dict)</code>). For example:</p>
<pre><code>import pandas
from collections import OrderedDict
import nump... | 0 | 2016-06-22T04:03:37Z | [
"python",
"pandas",
"concat"
] |
register_blueprint doesn't add route to Flask app | 37,954,472 | <p>I created a blueprint with a route and registered the blueprint with my Flask app. However, I get a 404 when requesting the route. What is wrong with my code?</p>
<pre><code>from flask import Flask, Blueprint
bp = Blueprint('test', __name__)
app = Flask(__name__)
app.register_blueprint(test_blueprint, url_prefix... | 1 | 2016-06-21T20:59:33Z | 37,954,554 | <p>You registered the blueprint before the code that registered the route executed. Move <code>register_blueprint</code> after the blueprint has been fully defined.</p>
<pre><code>bp = Blueprint('test', __name__, url_prefix='/test')
@bp.route('/')
def home():
return 'Hello, World!'
app.register_blueprint(bp)
</... | 1 | 2016-06-21T21:04:48Z | [
"python",
"flask"
] |
PANDAS TimeGrouper with individualized starting point for downsample | 37,954,489 | <p><strong>TL:DR</strong> </p>
<p>I'd like to group by subject and 30 day time period, but the 30 day time period isn't individualized by subject. </p>
<p>What's the best way to handle this?</p>
<p><strong>Full explanation</strong> </p>
<p>I've got a sample of participants who all started a scientific study at diff... | 2 | 2016-06-21T21:00:42Z | 37,955,493 | <p>To get the <code>TimeGrouper</code> to be at the participant level, first do a <code>groupby</code> on <code>'participantID'</code> and then within each group, do another <code>groupby</code> on the <code>TimeGrouper</code>. For the sake of clarity, I've separated out the second <code>groupby</code> as a separate f... | 2 | 2016-06-21T22:16:33Z | [
"python",
"datetime",
"pandas"
] |
Copying string from a specific index from one file to pasting that string on a specific place in another file | 37,954,503 | <p>My intention was to copy a piece of string after either a colon or equal sign from File 1 , and pasting that string in File 2 in a similar location after either a colon or equal sign. </p>
<p>For instance, if File 1 has:
username: Stack </p>
<p>File 2 is originally empty:
username= </p>
<p>I want Stack to be cop... | 0 | 2016-06-21T21:01:30Z | 37,981,693 | <p>I think something like this will get you what you need in a more maintainable and Pythonic way.</p>
<p>Note the use of regex as well as some string methods (e.g., <code>startswith</code>)</p>
<pre><code>import re
SOURCE_PATH = "C:/Users/SO//Downloads//f1.txt"
TARGET_PATH = "C:/Users/SO//Downloads//f2.txt"
def _g... | 1 | 2016-06-23T03:12:08Z | [
"python",
"python-3.x"
] |
Access SRI in python (redhawksdr) | 37,954,724 | <p>I am trying to access keywords in the SRI using python. There are no examples or documentation for doing this in python. </p>
<p>I want to grab the SRI, check for a keyword, and if present, copy the corresponding value. </p>
<p>I think the SRI will copy over as a tuple, but there are probably CF transformations an... | 1 | 2016-06-21T21:16:50Z | 37,998,562 | <p>As you may have seen, you can receive the SRI object in python in the same way as the HardLimit python implementation shown <a href="https://github.com/RedhawkSDR/HardLimit/blob/master/python/HardLimit.py#L53" rel="nofollow">here</a>.</p>
<blockquote>
<p>data, T, EOS, streamID, sri, sriChanged, inputQueueFlushed ... | 0 | 2016-06-23T17:49:12Z | [
"python",
"redhawksdr"
] |
Access SRI in python (redhawksdr) | 37,954,724 | <p>I am trying to access keywords in the SRI using python. There are no examples or documentation for doing this in python. </p>
<p>I want to grab the SRI, check for a keyword, and if present, copy the corresponding value. </p>
<p>I think the SRI will copy over as a tuple, but there are probably CF transformations an... | 1 | 2016-06-21T21:16:50Z | 37,998,818 | <p>The keywords are passed with the SRI as a list of CF DataTypes, which are string/CORBA::Any pairs. In Python, the keywords can be accessed using something like:</p>
<pre><code>from omniORB import any
packet = self.port_myPortName.getPacket() # note that the return value is a little different for REDHAWK versions &l... | 0 | 2016-06-23T18:05:50Z | [
"python",
"redhawksdr"
] |
Measuring the response's time using Tornado AsyncHTTPClient | 37,954,725 | <p>I want to send GET requests to a server at fixed time intervals and log the request and response time. This interval can be in the order of tens of milliseconds.
My first approach was to use a thread pool, as described in this answer <a href="http://stackoverflow.com/a/2635066/2390362">http://stackoverflow.com/a/26... | 0 | 2016-06-21T21:16:59Z | 37,954,966 | <p>In <code>handle_request</code>, the request duration can be reasonably measured with <code>resp_time - req_time</code>.</p>
<p>The problem is that you're blocking the event loop with <code>time.sleep</code>, which means most of the processing doesn't make progress until the initial <code>for</code> loop completes. ... | 0 | 2016-06-21T21:34:37Z | [
"python",
"python-3.x",
"http",
"tornado"
] |
how to continuously change background color in tkinter | 37,954,874 | <p>Python beginner here.<br>
I need a way to display a sequence of colors in Python and I chose to do that with Tkinter.<br>
I managed to have a Button and make it change it's background color when clicked, but when I do multiple changes, only the last one is rendered. </p>
<p>I'm almost sure that it's not a problem ... | 0 | 2016-06-21T21:27:08Z | 37,954,983 | <p>Here's your issue:</p>
<pre><code>time.sleep(1)
</code></pre>
<p>Never sleep in a GUI program. It stops the mainloop from doing anything (i.e. updating your graphics). It will freeze the gui, giving you no responses for a second as well.</p>
<p>Instead, separate it into two callbacks, and have the first schedule ... | 2 | 2016-06-21T21:36:10Z | [
"python",
"tkinter"
] |
Pandas applymap on multilevel dataframe | 37,954,906 | <p>I have a square matrix as a dataframe in pandas. It should be symmetric, and nearly is, except for a few missing values that I filled with 0. I want to use the fact that it should be symmetric to fill the missing values, by taking the max of the absolute value over df.ix[x,y] and df.ix[y,x]. I.e.:</p>
<pre><code>df... | 2 | 2016-06-21T21:29:53Z | 37,955,027 | <p>I think you can first convert <code>df</code> to <code>numpy array</code>, use <a href="http://stackoverflow.com/a/2573982/2901002"><code>numpy solution</code></a> and last create <code>DataFrame</code> with <code>constructor</code>:</p>
<pre><code>a = df.values
print (pd.DataFrame(data=a + a.T - np.diag(a.diagonal... | 2 | 2016-06-21T21:39:40Z | [
"python",
"pandas",
"multi-level"
] |
Parsing a symbolic equation in Python | 37,954,965 | <p>I'm new to Python and find myself in the following situation. I work with equations stored as strings, such as:</p>
<pre><code>>>> my_eqn = "A + 3.1B - 4.7D"
</code></pre>
<p>I'm looking to parse the string and store the numeric and alphabetic parts separately in two lists, or some other container. A (<st... | 0 | 2016-06-21T21:34:33Z | 37,955,766 | <p>This works for your simple scenario if you don't want to include any non standard python libraries.</p>
<pre><code>class Foo:
def __init__(self):
self.numbers = []
self.letters = []
def split_symbol(symbol, operator):
name = ''
multiplier = ''
for letter in symbol:
if letter... | 1 | 2016-06-21T22:42:13Z | [
"python"
] |
Plus instead of a space in the url | 37,954,987 | <p>I'm getting a string url request, I want to handle it and send the parameters, because it is very long.
I get plus in <code>req.url</code> instead of a space like <code>query</code>.</p>
<pre><code>query = "https://www.superjob.ru/resume/search_resume.html?sbmit=1&detail_search=1&keywords%5B0%5D%5Bkeys%5D=%... | 0 | 2016-06-21T21:36:37Z | 37,956,765 | <p>Have you looked at the url you are posting?
you set </p>
<pre><code>query = "https://www.superjob.ru/resume/search_resume.html?sbmit=1&detail_search=1&keywords%5B0%5D%5Bkeys%5D=%D0%9A%D0%BB%D0%B0%D0%B4%D0%BE%D0%B2%D1%89%D0%B8%D0%BA+%D0%9A%D0%BE%D0%BC%D0%BF%D0%BB%D0%B5%D0%BA%D1%82%D0%BE%D0%B2%D1%89%D0%B8%D0... | 0 | 2016-06-22T00:37:21Z | [
"python",
"url",
"utf-8",
"request",
"ascii"
] |
Plus instead of a space in the url | 37,954,987 | <p>I'm getting a string url request, I want to handle it and send the parameters, because it is very long.
I get plus in <code>req.url</code> instead of a space like <code>query</code>.</p>
<pre><code>query = "https://www.superjob.ru/resume/search_resume.html?sbmit=1&detail_search=1&keywords%5B0%5D%5Bkeys%5D=%... | 0 | 2016-06-21T21:36:37Z | 37,997,599 | <p>I solved this problem like this:</p>
<pre><code>query = "https://www.superjob.ru/resume/search_resume.html?sbmit=1&detail_search=1&keywords%5B0%5D%5Bkeys%5D=%D0%9A%D0%BB%D0%B0%D0%B4%D0%BE%D0%B2%D1%89%D0%B8%D0%BA+%D0%9A%D0%BE%D0%BC%D0%BF%D0%BB%D0%B5%D0%BA%D1%82%D0%BE%D0%B2%D1%89%D0%B8%D0%BA+%D0%93%D1%80%D1%8... | 0 | 2016-06-23T16:56:24Z | [
"python",
"url",
"utf-8",
"request",
"ascii"
] |
Python Tkinter - Quit Button Not Working if Other Button Clicked First | 37,954,993 | <p>I would like my "Quit" button to close the window and end the program no matter when it is pressed. Right now it works if it is pressed first, but if the "Roll" button is pressed first then the "Quit" button doesn't close the window. I am a beginner programmer, so I'm sure there are unrelated issues with my code, bu... | 0 | 2016-06-21T21:36:59Z | 37,970,924 | <p>(For later programmers with this issue who stumble here)</p>
<p>The issue with this is you have the <em>function</em> <code>self.quit</code> and <em>also</em> a button <code>self.quit</code>. Python won't overload names - <code>self.quit</code> after initialization is a function, but after the first time you call <... | 0 | 2016-06-22T14:23:29Z | [
"python",
"python-2.7",
"tkinter"
] |
How to make sure, when mod_wsgi is loaded, Apache is running the module | 37,955,015 | <p>On an OS X server, I followed the mod_wsgi installation instructions and when I run <code>apachectl -M</code> the output says that mod_wsgi is loaded. On the other hand, when opening the Apache logs after restarting the service, there is no indication that mod_wsgi is loaded. I have tried using mod_wsgi-express and ... | 1 | 2016-06-21T21:38:40Z | 37,976,581 | <p>Add this section to your Apache config (perhaps in <code>/etc/httpd/conf.d</code>) and see if it errors?</p>
<pre><code>WSGISocketPrefix /var/run/wsgi
<VirtualHost *:80>
ServerName yoursite.com
WSGIDaemonProcess yoursite-http python-home=/home/vagrant/.virtualenvs/yoursite
WSGIScriptAlias / /var/www/... | 0 | 2016-06-22T19:20:59Z | [
"python",
"osx",
"apache",
"mod-wsgi"
] |
Parse plist file in Python | 37,955,056 | <p>I have an issue with my Python code. I have a plist file.</p>
<p><strong>Info.plist</strong></p>
<pre><code><plist>
<dict>
<key>Apple Car Version</key>
<string>1.0</string>
<key>Last Backup Date</key>
<date/>
<key>Product Type</ke... | 0 | 2016-06-21T21:41:39Z | 37,956,773 | <p>That plist file isn't well formed xml at all, so I doubt it will work. I think you need (at a minimum) a root plist element and a dict wrapper:</p>
<pre><code><plist>
<dict>
<key>Apple Car Version</key>
<string>1.0</string>
</dict>
</plist>
</code></pre>
... | 0 | 2016-06-22T00:38:32Z | [
"python",
"plist"
] |
Removing personal information from the comments in a word file using python | 37,955,062 | <p>I want to remove all the personal information from the comments inside a word file.</p>
<p>Removing the Authors name is fine, I did that using the following,</p>
<pre><code>document = Document('sampleFile.docx')
core_properties = document.core_properties
core_properties.author = ""
document.save('new-filename.docx... | 3 | 2016-06-21T21:41:58Z | 37,955,295 | <p>The core properties recognised by the CoreProperties class are listed in the official documentation: <a href="http://python-docx.readthedocs.io/en/latest/api/document.html#coreproperties-objects" rel="nofollow">http://python-docx.readthedocs.io/en/latest/api/document.html#coreproperties-objects</a></p>
<p>To overwr... | 4 | 2016-06-21T22:00:13Z | [
"python",
"python-docx"
] |
Removing personal information from the comments in a word file using python | 37,955,062 | <p>I want to remove all the personal information from the comments inside a word file.</p>
<p>Removing the Authors name is fine, I did that using the following,</p>
<pre><code>document = Document('sampleFile.docx')
core_properties = document.core_properties
core_properties.author = ""
document.save('new-filename.docx... | 3 | 2016-06-21T21:41:58Z | 37,956,562 | <p>If you want to remove personal information from the comments in <code>.docx</code> file, you'll have to dive deep into the file itself.</p>
<p>So, <code>.docx</code> is just a <code>.zip</code> archive with word-specific files. We need to overwrite some internal files of it, and the easiest way to do it that I coul... | 2 | 2016-06-22T00:09:50Z | [
"python",
"python-docx"
] |
Python NameError, variable 'not defined' | 37,955,081 | <p>the error it returns is:</p>
<pre><code>NameError: name 'lives' is not defined
</code></pre>
<p>I know the code isn't as efficient as possible, this is one of my first projects, however whatever i try to do this error pops up, I've tried making a global for it but that didn't help. I would really appreciate some h... | 0 | 2016-06-21T21:43:13Z | 37,955,095 | <p>You didn't declare <code>lives</code> to be global inside <code>main()</code>, so it is local to that function.</p>
<pre><code>def main():
global guess, rand_num, lives
...
</code></pre>
| 1 | 2016-06-21T21:44:25Z | [
"python",
"variables",
"python-3.5"
] |
Python NameError, variable 'not defined' | 37,955,081 | <p>the error it returns is:</p>
<pre><code>NameError: name 'lives' is not defined
</code></pre>
<p>I know the code isn't as efficient as possible, this is one of my first projects, however whatever i try to do this error pops up, I've tried making a global for it but that didn't help. I would really appreciate some h... | 0 | 2016-06-21T21:43:13Z | 37,955,161 | <p>When you declare it inside function they are only available in that function scope, so declare global variables outside functions and code will work fine.</p>
<pre><code>import random
import time
guess = None
random_num = None
lives = 3
win = False
def main():
global guess,rand_num
win = False
rand_num = 45
... | 0 | 2016-06-21T21:48:40Z | [
"python",
"variables",
"python-3.5"
] |
Python NameError, variable 'not defined' | 37,955,081 | <p>the error it returns is:</p>
<pre><code>NameError: name 'lives' is not defined
</code></pre>
<p>I know the code isn't as efficient as possible, this is one of my first projects, however whatever i try to do this error pops up, I've tried making a global for it but that didn't help. I would really appreciate some h... | 0 | 2016-06-21T21:43:13Z | 37,955,325 | <p>You need to define the variable "lives" outside of the function main, then any function where you want to reference that global variable you say "global lives." When you are in a function and assign a value to a variable, it assumes it is in the local scope. using "global lives" tells that function to look to the gl... | 0 | 2016-06-21T22:02:49Z | [
"python",
"variables",
"python-3.5"
] |
How to get indices of values of numpy array which are zero | 37,955,109 | <p>Lets say I have a numpy array as below: </p>
<pre><code>array([ 1. , 2. , 0. , 3.4, 0. , 1.1])
</code></pre>
<p>Now I want to get indices of all the elements which are zero. Reason being I want to get those indices and then for a different array I want to convert the elements on same indices to zero. </p>
<p... | 0 | 2016-06-21T21:45:40Z | 37,955,167 | <p>If you just want to use the result for indexing purposes, it's more efficient to make a boolean array than an array of indices:</p>
<pre><code>a == 0
</code></pre>
<p>You can index with that the same way you would have used the array of indices:</p>
<pre><code>b[a == 0] = 0
</code></pre>
<p>If you really want an... | 4 | 2016-06-21T21:49:18Z | [
"python",
"numpy"
] |
When to make a django app, rather than just a model | 37,955,199 | <p>Recently I've been making a few test projects in Django and while I've found the structure to be better than that of other Web Frameworks, I am a little confused on the concept of different 'apps'.</p>
<p>Here is a test case example:</p>
<p>Suppose I have a simple CRUD application where users post a picture and a ... | 0 | 2016-06-21T21:51:31Z | 37,955,276 | <blockquote>
<p>The term application describes a Python package that provides some
<strong>set of features</strong>. Applications may be reused in various projects.</p>
</blockquote>
<p>So in this case, better to have both <code>Post</code> and <code>Review</code> as two models in one app, since both of them apply... | 0 | 2016-06-21T21:58:15Z | [
"python",
"django",
"django-models"
] |
When to make a django app, rather than just a model | 37,955,199 | <p>Recently I've been making a few test projects in Django and while I've found the structure to be better than that of other Web Frameworks, I am a little confused on the concept of different 'apps'.</p>
<p>Here is a test case example:</p>
<p>Suppose I have a simple CRUD application where users post a picture and a ... | 0 | 2016-06-21T21:51:31Z | 37,961,101 | <p>In your case, I think the better is to put your two models in one app. </p>
| 0 | 2016-06-22T07:20:27Z | [
"python",
"django",
"django-models"
] |
Python 3 For loop vs next() iterator | 37,955,249 | <p>I'm learning Python 3 (my first language since BASIC), and I have a general question:</p>
<p>If I want to iterate over something, how do I determine if the best way is to use a For loop or a generator? They appear to be closely related.</p>
| 0 | 2016-06-21T21:55:50Z | 37,955,310 | <p>Use a for-loop if you can. It's simple, and it uses iterators behind the scenes. One of the great things about python's iterator system is that you don't need to think about them most of the time. It is quite rare that you'll need to explicitly call <code>next()</code> on something.</p>
<p>This is kind of general, ... | 2 | 2016-06-21T22:01:32Z | [
"python"
] |
How to parse variable code, contained within a string, as if it were part of the python script | 37,955,254 | <p>The root question is how to take something that is stored (elsewhere/earlier) as a string containing un-translated variables and force python to re-evaluate it so that the variables written within the string can be converted to their now-known values.</p>
<p>I have a variable that is defined something like (there a... | 0 | 2016-06-21T21:56:23Z | 37,956,094 | <p>That is what functions are for.</p>
<pre><code>def get_src_check(row):
return "SELECT daily_installs FROM mr_app WHERE report_date = '" + row[0] + "' AND country = '" + row[3] + "'"
....
row = ...
cursor.execute(get_src_check(row))
</code></pre>
| 0 | 2016-06-21T23:17:19Z | [
"python",
"string",
"variables",
"eval"
] |
How to parse variable code, contained within a string, as if it were part of the python script | 37,955,254 | <p>The root question is how to take something that is stored (elsewhere/earlier) as a string containing un-translated variables and force python to re-evaluate it so that the variables written within the string can be converted to their now-known values.</p>
<p>I have a variable that is defined something like (there a... | 0 | 2016-06-21T21:56:23Z | 37,956,123 | <p>You can run cursor.execute with string variable.</p>
<p>from django.db import connection</p>
<p>cursor = connection.cursor()</p>
<p>src_check = str("SELECT daily_installs FROM mr_app WHERE report_date ='" + row[0] + "' AND country = '" + row[3] + "'")</p>
<p>cursor.execute(src_check)</p>
<p>row = cursor.fetchon... | 0 | 2016-06-21T23:20:35Z | [
"python",
"string",
"variables",
"eval"
] |
How can i reload a picture with Tkinter after GPIO button press? | 37,955,277 | <p>I have the following script based on a solution of another Stackoverflow question. I have a tkinter GUI with a picture that should refresh when there is taken a new one.</p>
<pre><code>class App(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.start()
def callback... | 0 | 2016-06-21T21:58:25Z | 37,956,441 | <p>tkinter is <strong>not</strong> thread-safe (by default). All operations dealing with the GUI must be done in the main thread. You can do what you are asking using callbacks on events, but threading can and will break tkinter unless you implement an event queue that feeds into the mainloop.</p>
<p>Additionally, the... | 0 | 2016-06-21T23:57:19Z | [
"python",
"python-3.x",
"tkinter",
"raspberry-pi",
"gpio"
] |
How do I iterate through a list of related objects in a django template? | 37,955,301 | <p>I'm new to Django and I'm trying to get related models printing in a view. I'm pretty sure the DB itself is set up properly, including keys and such, and there is data in the table to play with. What I'm not sure about is</p>
<ul>
<li>Am I wiring the models to the correct table and column names?</li>
<li>Am I loadi... | 0 | 2016-06-21T22:00:54Z | 37,955,978 | <p>If you do not use Django to create database, you need to specify table name for the VoterPhone class. Django would not choose voterphones table as the intermediate table. I think by setting
<em>class Meta:
db_table = 'voterphones'</em>
for VoterPhone class you should be able to see related phone numbers.</... | 0 | 2016-06-21T23:03:56Z | [
"python",
"django",
"many-to-many"
] |
How do I iterate through a list of related objects in a django template? | 37,955,301 | <p>I'm new to Django and I'm trying to get related models printing in a view. I'm pretty sure the DB itself is set up properly, including keys and such, and there is data in the table to play with. What I'm not sure about is</p>
<ul>
<li>Am I wiring the models to the correct table and column names?</li>
<li>Am I loadi... | 0 | 2016-06-21T22:00:54Z | 37,975,080 | <p>I finally got something working. I had to make the following changes:</p>
<ul>
<li><p>got the tables renamed to their default django names (namely, voters_phones instead of voter_phones)</p></li>
<li><p>found that the foreign keys in voters_phones were int(11) while the primary keys in both voters and phones were b... | 0 | 2016-06-22T17:52:40Z | [
"python",
"django",
"many-to-many"
] |
Python: Adding hours to pandas timestamp | 37,955,332 | <p>I read a csv file into pandas dataframe <code>df</code> and I get the following:</p>
<pre><code>df.columns
Index([u'TDate', u'Hour', u'SPP'], dtype='object')
>>> type(df['TDate'][0])
<class 'pandas.tslib.Timestamp'>
type(df['Hour'][0])
<type 'numpy.int64'>
>>> type(df['TradingDate'])... | 3 | 2016-06-21T22:03:14Z | 37,955,390 | <p>I think you can add to column <code>TDate</code> column <code>Hour</code> converted <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow"><code>to_timedelta</code></a> with <code>unit='h'</code>:</p>
<pre><code>df = pd.DataFrame({'TDate':['2005-01-03','2005-01-04','... | 3 | 2016-06-21T22:08:00Z | [
"python",
"datetime",
"pandas",
"dataframe",
"timedelta"
] |
"label" for process to be able to kill it by "label" | 37,955,353 | <p>I need to run more player programs at once (in linux), but I want to kill it by subprocess separately. So I am thinking about something like adding "label" for each player process when I start it, e.g. player "1", player "2", player "3", player "3", player "3" and then I would like to call subprocess to kill all ins... | -3 | 2016-06-21T22:05:30Z | 37,955,465 | <p>If all your labels are unique you can simply save the <code>popen</code> instances in a dictionary with the label as the key.</p>
<pre><code>import subprocess
process_dict = {}
def startNewProcess(command, label):
p = subprocess.Popen(command, shell=True)
process_dict[label] = p
def killProcess(label):
... | 0 | 2016-06-21T22:13:58Z | [
"python",
"python-2.7"
] |
How do I read an integer from a file, and then read that many lines after the integer in that file (Python)? | 37,955,393 | <p>I'm having some trouble with this problem. I'm a beginner to Python and have been searching this website but can't seem to figure out how to do this specific problem. If I have a file that looks something like this:</p>
<pre><code>3
Alpha
Beta
Gamma
4
Delta
Epsilon
Omega
Zeta
</code></pre>
<p>I want to read that f... | -2 | 2016-06-21T22:08:16Z | 37,955,533 | <p>If your goal is to read a file that is perfectly formatted such that the first line is a number N, the next N lines after the first are words to print, and the line after that is a number M, and the next M lines are the ones you want to print (and on and on), then the following would work:</p>
<pre><code>with open(... | 1 | 2016-06-21T22:20:08Z | [
"python",
"file",
"loops"
] |
How do I read an integer from a file, and then read that many lines after the integer in that file (Python)? | 37,955,393 | <p>I'm having some trouble with this problem. I'm a beginner to Python and have been searching this website but can't seem to figure out how to do this specific problem. If I have a file that looks something like this:</p>
<pre><code>3
Alpha
Beta
Gamma
4
Delta
Epsilon
Omega
Zeta
</code></pre>
<p>I want to read that f... | -2 | 2016-06-21T22:08:16Z | 37,979,325 | <p>I don't want to edit my original answer, so here's a new one instead.</p>
<p>Step one is to open and read the file, line by line:</p>
<pre><code>with open('myfile.txt') as input_data:
while True:
line = input_data.readline()
print line
if not line:
break
## this is w... | -1 | 2016-06-22T22:33:06Z | [
"python",
"file",
"loops"
] |
how to run OLS regression with pandas datetime object series being independent value (x) | 37,955,423 | <p>i guess, I am missing something basic. However, here is my question. I have time series data for 25 days, I want to run OLS regression with Y value being the time series and the X value being the datetime index. here is my code</p>
<pre><code>import pandas as pd
from pandas.stats.api import ols
indx = [Timestamp('... | 2 | 2016-06-21T22:11:05Z | 37,955,631 | <p>Add this to your code:</p>
<pre><code>df['jDate'] = df.index.to_julian_date()
ols(x=df.jDate, y=df.abc)
</code></pre>
<p>Complete looks like:</p>
<pre><code>import pandas as pd
from pandas.stats.api import ols
indx = [Timestamp('2015-06-01 00:00:00'), Timestamp('2015-06-02 00:00:00'), Timestamp('2015-06-03 00:00... | 1 | 2016-06-21T22:30:00Z | [
"python",
"pandas",
"statsmodels"
] |
keeping form values after POST as a paramter of python file | 37,955,610 | <p>I have a form, which one submitted goes to a php file and inserts values into DB(MySql).After successfully inserting values into DB,I want to use the values of this parameter form as a python file in another php file when i submitted .</p>
<p>file register.php -> file description.php (button start) -> file exucuter... | 0 | 2016-06-21T22:28:24Z | 37,955,769 | <p>Instead of redirecting to <em>exucuter.php</em> after doing your DB insert, if you </p>
<pre><code>include 'exucuter.php'; // (assuming they are in the same directory)
</code></pre>
<p>in <em>description.php</em> after the DB does its work, you should be able to use the values directly from <code>$_POST</code> in... | 1 | 2016-06-21T22:42:24Z | [
"php",
"python",
"mysql",
"forms"
] |
Pygame Sprites bug? | 37,955,625 | <p>HeyGuys! I just joined this site, so go easy on me with how I go about this question.</p>
<p>So, I recently started playing around with PyGames and ran a few tests with the pygame.sprite.Sprite modules. Here is my code:</p>
<pre><code>#Game
import pygame
pygame.init()
screen_width, screen_height = 800, 600
scre... | 0 | 2016-06-21T22:29:28Z | 37,962,266 | <p>When you call </p>
<pre><code>def load_image(self, url):
self.image = pygame.image.load(url)
self.rect = self.image.get_rect()
</code></pre>
<p>you set the rectangle of the Sprite to the rectangle of the image. However, that rectangle has the position (0,0). This means both the green rectangle and the bloc... | 0 | 2016-06-22T08:14:18Z | [
"python",
"pygame"
] |
convert pandas dataframe column from hex string to int | 37,955,856 | <p>I have a very large dataframe that I would like to avoid iterating through every single row and want to convert the entire column from hex string to int. It doesn't process the string correctly with astype but has no problems with a single entry. Is there a way to tell astype the datatype is base 16?</p>
<pre><code... | 2 | 2016-06-21T22:50:34Z | 37,955,967 | <p>You could use <code>apply</code>.</p>
<pre><code>df.Command0.apply(lambda x: int(x, 16))
>>>
0 456
1 195
Name: Command0, dtype: int64
</code></pre>
<p>And you can do this with <code>pd.read_csv</code> call using the <code>converters</code> parameter:</p>
<pre><code>df = pd.read_csv("path.txt", con... | 2 | 2016-06-21T23:02:54Z | [
"python",
"python-3.x",
"pandas",
"dataframe"
] |
multiple bar plots from pandas dataframe | 37,955,881 | <p>So I have a data frame like</p>
<pre><code>exp_name, index, items, clicks
"foo",0, "apple",200
"foo",0, "banana", 300
"foo",0,"melon",220
"foo",1, "apple", 10
"foo",1,"peach", 20
"bar",0, "apple",400
"bar",0,'banana', 500
"bar",0, "melon",240
"bar",1,"apple",500
</code></pre>
<p>and so on</p>
<p>I want to plot...... | 2 | 2016-06-21T22:54:32Z | 37,956,404 | <p>I copy/paste your data into a txt file called 'test.txt' and rename "index" as "status" to avoid confusion with the DataFrame index. Then I use the <a href="https://stanford.edu/~mwaskom/software/seaborn/tutorial/categorical.html?highlight=estimator" rel="nofollow">Seaborn</a> library to make barplots with the conti... | 3 | 2016-06-21T23:53:40Z | [
"python",
"pandas",
"matplotlib"
] |
Pandas select the second to last column which is also not nan | 37,955,900 | <p>I've cleaned my data as much as I can and read them in Pandas dataframe. So the problem is that different files have different number of columns, but it always the second to the last non-nan column is what I want. So is there anyway to pick them out? Here is an example of the data.</p>
<pre><code> ... f ... | 2 | 2016-06-21T22:56:08Z | 37,955,986 | <h3>One liner</h3>
<pre><code>df.loc[:, :df.columns[(df.columns == df.isnull().all().idxmax()).argmax() - 2]]
... f g
0 ... 39994 29.568
1 ... 39994 29.568
2 ... 39994 29.568
</code></pre>
<h3>Readable</h3>
<pre><code># identify null columns
nullcols = df.isnull().all()
# find the column hea... | 2 | 2016-06-21T23:04:34Z | [
"python",
"pandas",
"select",
null
] |
Pandas select the second to last column which is also not nan | 37,955,900 | <p>I've cleaned my data as much as I can and read them in Pandas dataframe. So the problem is that different files have different number of columns, but it always the second to the last non-nan column is what I want. So is there anyway to pick them out? Here is an example of the data.</p>
<pre><code> ... f ... | 2 | 2016-06-21T22:56:08Z | 37,956,071 | <p>Similar idea to @piRSquared. Essentially, use <code>loc</code> to keep the non-null columns, then use <code>iloc</code> to select the second to last.</p>
<pre><code>df.loc[:, ~df.isnull().all()].iloc[:, -2]
</code></pre>
<p>Sample input:</p>
<pre><code> a b c d e f g h i j
0 0 3 6 9 12 1... | 3 | 2016-06-21T23:15:11Z | [
"python",
"pandas",
"select",
null
] |
Django project not recognizing SCSS files | 37,955,977 | <p>I've been struggling to get Django to recognize my SCSS files (I may be misusing SCSS/SASS/LESS terminology... their relationship confuses me). I'm using <code>django-libsass</code> and <code>compress</code>, both of which seem pretty straight-forward. My page is giving me the error "Resource interpreted as Styles... | 0 | 2016-06-21T23:03:50Z | 37,957,077 | <p>Try adding <code>type="text/x-scss"</code> to the link element along with the compress tag:</p>
<pre><code>{% compress css %}
<link href="{% static 'css/blog.scss' %}" rel="stylesheet" type="text/x-scss">
{% endcompress %}
</code></pre>
<p>And make sure to load the compress tag before you use it:</p>
<p... | 1 | 2016-06-22T01:23:27Z | [
"python",
"django",
"sass",
"less"
] |
Trying to migrate in Django 1.9 -- strange SQL error "django.db.utils.OperationalError: near ")": syntax error" | 37,955,984 | <p>I don't have a clue what's causing this error. It appears to be a bug that there isn't a fix for. Could anyone tell give me a hint as to how I might get around this? It's frustrating me to no end. Thanks.</p>
<pre><code>Operations to perform:
Apply all migrations: admin, contenttypes, optilab, auth, sessions
... | 2 | 2016-06-21T23:04:30Z | 37,979,963 | <p>This appears to be the line that's causing the errror:</p>
<pre><code> INSERT INTO "optilab_lasersubstrate" () SELECT FROM "optilab_lasersubstrate__old";
</code></pre>
<p>You are usually expected to have a list of columns in those parenthesis. Eg <code>INSERT INTO "optilab_lasersubstrate" (col1,col2,etc)</code> h... | 2 | 2016-06-22T23:40:34Z | [
"python",
"django",
"sqlite",
"django-migrations"
] |
how to parse a string to match against dictionary? | 37,956,014 | <p>I have the following code where I try to set "build_info_match" to True only when all the build locations present in "engg_buildinfo" match with "prod_buildinfo",currently I believe I am hitting the error because prod_buildinfo is a string instead of dictionary,how do get the corresponding build location from prod_b... | 0 | 2016-06-21T23:08:42Z | 37,956,493 | <p>From what I understood about your code I come up with this, I think you could work from here, I could add more code but I don't get what you mean by "all the build locations in dict match with buildinfo locations"</p>
<pre><code>import re
prod_buildinfo = """|h6. {color:blue} Meta Build{color}|{color:blue}MSM1234.L... | 0 | 2016-06-22T00:02:40Z | [
"python",
"dictionary"
] |
Index numpy array with pd.Series of boolean | 37,956,088 | <p>I found a piece of code I don't really understand. It basically goes like this:</p>
<pre><code>array = np.ones((5, 4))*np.nan
s1 = pd.Series([1,4,0,4,5], index=[0,1,2,3,4])
I = s1 == 4
print(I)
0 False
1 True
2 False
3 True
4 False
dtype: bool
</code></pre>
<p>I really understand this part, it re... | 3 | 2016-06-21T23:16:47Z | 37,956,285 | <p>Its a mistake. I don't know exactly how numpy is interpreting <code>I</code> in the index. But I'm pretty sure this is what was intended:</p>
<pre><code>array[I.values, 0] = 3
array[I.values, 1] = 7
array[I.values, 2] = 2
array[I.values, 3] = 5
print(array)
[[ nan nan nan nan]
[ 3. 7. 2. 5.]
[ nan n... | 4 | 2016-06-21T23:39:10Z | [
"python",
"numpy",
"pandas"
] |
Index numpy array with pd.Series of boolean | 37,956,088 | <p>I found a piece of code I don't really understand. It basically goes like this:</p>
<pre><code>array = np.ones((5, 4))*np.nan
s1 = pd.Series([1,4,0,4,5], index=[0,1,2,3,4])
I = s1 == 4
print(I)
0 False
1 True
2 False
3 True
4 False
dtype: bool
</code></pre>
<p>I really understand this part, it re... | 3 | 2016-06-21T23:16:47Z | 37,956,305 | <p>The explanation lies in the fact that <code>numpy</code> array and <code>pandas</code> series treat the <em>logic index</em> differently. The former treat <code>True</code> as 1 and <code>False</code> as 0 while latter pick up the value where the logic is <code>True</code> and drop the value where the logic is <code... | 4 | 2016-06-21T23:41:48Z | [
"python",
"numpy",
"pandas"
] |
python: PyPi public modules: How to determine if secure and safe? | 37,956,106 | <p>I am have completed my python 3 application, and it is using multiple public modules from PyPi.</p>
<p>However, before I deploy it to run within my company's enterprise which will be handling credentials of our customers and accessing 3rd party APIs, I need to do due diligence that they are both secure and safe.</p... | 1 | 2016-06-21T23:18:58Z | 37,956,292 | <p>These are 3 separate questions, so:</p>
<ol>
<li><p>You'll have to audit the package (or get someone else to do that) to know if it's secure. No easy way around it.</p></li>
<li><p>All pypi packages have md5 signature attached (link in parentheses after the file). Some of them also attach the pgp signature which sh... | 0 | 2016-06-21T23:40:18Z | [
"python",
"security",
"docker",
"pypi"
] |
Incrementing string in Python | 37,956,212 | <p>I am writing a function to increment a 3-letter (a-z) string. For example:<br>
<strong>Input:</strong> aaa<br>
<strong>Output</strong>: baa</p>
<p><strong>Input:</strong> zba<br>
<strong>Output</strong>: aca</p>
<p>So the order is as following</p>
<pre><code>aaa
baa
...
zaa
aba
bba
cba
...
zba
aca
bca
cca
...
zca... | 0 | 2016-06-21T23:31:12Z | 37,956,252 | <p>just use itertools product</p>
<pre><code>>>> import itertools
>>> from string import ascii_lowercase
>>> strings = itertools.product(*[ascii_lowercase]*3)
>>> "".join(next(strings,"No More Combos..."))
'aaa'
>>> "".join(next(strings,"No More Combos..."))
'aab'
>>&... | 6 | 2016-06-21T23:36:07Z | [
"python"
] |
Incrementing string in Python | 37,956,212 | <p>I am writing a function to increment a 3-letter (a-z) string. For example:<br>
<strong>Input:</strong> aaa<br>
<strong>Output</strong>: baa</p>
<p><strong>Input:</strong> zba<br>
<strong>Output</strong>: aca</p>
<p>So the order is as following</p>
<pre><code>aaa
baa
...
zaa
aba
bba
cba
...
zba
aca
bca
cca
...
zca... | 0 | 2016-06-21T23:31:12Z | 37,956,261 | <p>You can simplify the loop a lot:</p>
<pre><code>def next_code(code):
code = list(code)
for i, let in enumerate(code):
if let != 'z':
code[i] = chr(ord(let) + 1)
break
code[i] = 'a'
return ''.join(code)
</code></pre>
<p>If the goal is to just produce all values on... | 2 | 2016-06-21T23:36:42Z | [
"python"
] |
Can a particular instance of a class declared in a python file be accessed from another file? | 37,956,218 | <p>I have a class which have several functions in it. In file1, I have created an instance of that class.</p>
<pre><code>class requestHandler():
def __init__(self):
......
def processRequest(self,command):
......
if __name__ == "__main__" :
currentHandler = requestHandler()
</code></pre>
<p>Now,... | 2 | 2016-06-21T23:31:57Z | 37,956,256 | <p>You could pass your handler instance to the adapter class</p>
<pre><code>from file2 import adapter
class requestHandler():
def __init__(self):
......
def processRequest(self, command):
......
if __name__ == "__main__" :
currentHandler = requestHandler()
a = adapter()
a.processRequest(c... | 1 | 2016-06-21T23:36:20Z | [
"python"
] |
Can a particular instance of a class declared in a python file be accessed from another file? | 37,956,218 | <p>I have a class which have several functions in it. In file1, I have created an instance of that class.</p>
<pre><code>class requestHandler():
def __init__(self):
......
def processRequest(self,command):
......
if __name__ == "__main__" :
currentHandler = requestHandler()
</code></pre>
<p>Now,... | 2 | 2016-06-21T23:31:57Z | 37,956,413 | <p>To use currentHandler from another script,</p>
<pre><code>currentHandler = requestHandler()
</code></pre>
<p>must not be under the:</p>
<pre><code>if __name__ == "__main__":
</code></pre>
<p>statement. It must be outside the if statement.</p>
<p>Example:</p>
<p>file1</p>
<pre><code>class a():
def f(self):... | 0 | 2016-06-21T23:54:22Z | [
"python"
] |
Can a particular instance of a class declared in a python file be accessed from another file? | 37,956,218 | <p>I have a class which have several functions in it. In file1, I have created an instance of that class.</p>
<pre><code>class requestHandler():
def __init__(self):
......
def processRequest(self,command):
......
if __name__ == "__main__" :
currentHandler = requestHandler()
</code></pre>
<p>Now,... | 2 | 2016-06-21T23:31:57Z | 37,956,586 | <p>Python programs come in two basic flavors: <em>scripts</em> - which are the top level programs you run from the command line, by clicking them, etc... and modules, which are imported. A python program is one <em>script</em> named <code>__main__</code> and any number of imported modules (typically named by the progra... | 2 | 2016-06-22T00:13:08Z | [
"python"
] |
Imported module goes out of scope (unbound local error) | 37,956,270 | <p>I am getting a strange "unbound local" error in a python package that seems to defy all logic. I can't get a MWE to reproduce it, but will try to explain succinctly and hope that someone might be able to offer some explanation of what is going on.</p>
<p>For the sake of this example <code>module</code> is a package... | 1 | 2016-06-21T23:37:58Z | 37,956,492 | <p>Apparently you have a local variable named <code>module</code> somewhere in the function <code>run</code>. For example, the following code will throw <code>UnboundLocalError</code> </p>
<pre><code>import sys
def run():
print sys
sys = None
run()
</code></pre>
<p>Here <code>sys = None</code> introduces ... | 3 | 2016-06-22T00:02:22Z | [
"python",
"scope"
] |
Querying an object in OpenErp 7 | 37,956,302 | <p>I have two objects,'article' and 'mvt', the logic behind the module am trying to create is that an article is defined by a name and a price, but the quantity is calculated through a set of transactions or 'mouvements', each mouvement has a realtion of many2one with an article, a date and a qte, the last field can be... | 0 | 2016-06-21T23:41:40Z | 37,963,104 | <p>We did something very similar and it worked perfectly.</p>
<p>Just beware, after a large number of transactions, the code will become slow as you have to recalculate each time you open the form. You will have to write a "purge" wizard that will summarise transactions older than say three years. It all depends on ... | 1 | 2016-06-22T08:54:45Z | [
"python",
"openerp",
"openerp-7"
] |
reading and doing calculation from .dat file in python | 37,956,344 | <p>I need to read a .dat file in python which has 12 columns in total and millions of lines of rows. I need to divide column 2,3 and 4 with column 1 for my calculation. So before I load that .dat file, do I need to delete all the other unwanted columns? If not, how do I selectively declare the column and ask python to ... | 2 | 2016-06-21T23:47:18Z | 37,956,376 | <p>Try something like:</p>
<pre><code>datContent = [i.strip().split() for i in open("filename.dat").readlines()]
</code></pre>
<p>Then you'll have your data in a list.</p>
<p>If you want to have something more sophisticated you can use <a href="http://pandas.pydata.org/pandas-docs/version/0.15.2/tutorials.html" rel=... | 2 | 2016-06-21T23:50:17Z | [
"python",
"csv"
] |
reading and doing calculation from .dat file in python | 37,956,344 | <p>I need to read a .dat file in python which has 12 columns in total and millions of lines of rows. I need to divide column 2,3 and 4 with column 1 for my calculation. So before I load that .dat file, do I need to delete all the other unwanted columns? If not, how do I selectively declare the column and ask python to ... | 2 | 2016-06-21T23:47:18Z | 37,956,460 | <p>After looking at your <code>flash.dat</code> file, it's clear you need to do a little clean up before you process it. The following code converts it to a CSV file:</p>
<pre><code>import csv
# read flash.dat to a list of lists
datContent = [i.strip().split() for i in open("./flash.dat").readlines()]
# write it as ... | 1 | 2016-06-21T23:59:16Z | [
"python",
"csv"
] |
reading and doing calculation from .dat file in python | 37,956,344 | <p>I need to read a .dat file in python which has 12 columns in total and millions of lines of rows. I need to divide column 2,3 and 4 with column 1 for my calculation. So before I load that .dat file, do I need to delete all the other unwanted columns? If not, how do I selectively declare the column and ask python to ... | 2 | 2016-06-21T23:47:18Z | 37,972,704 | <p>Consider using the general <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_table.html" rel="nofollow"><code>read_table()</code></a> function (of which <code>read_csv()</code> is a special type) where pandas can easily import the specific .dat file specifying the space separator, <code>sep=... | 1 | 2016-06-22T15:41:15Z | [
"python",
"csv"
] |
reading and doing calculation from .dat file in python | 37,956,344 | <p>I need to read a .dat file in python which has 12 columns in total and millions of lines of rows. I need to divide column 2,3 and 4 with column 1 for my calculation. So before I load that .dat file, do I need to delete all the other unwanted columns? If not, how do I selectively declare the column and ask python to ... | 2 | 2016-06-21T23:47:18Z | 37,985,613 | <p>The problem you face here is that the column header names have whitespaces in them. You need to fix/ignore that to make <code>pandas.read_csv</code> behave nicely. This will read the column header names into a list based on the fixed length of the field name strings:</p>
<pre><code>import pandas
with open('flash.d... | 1 | 2016-06-23T08:05:38Z | [
"python",
"csv"
] |
No color when I make python scatter color plot using third variable to define color | 37,956,351 | <p>I try to make colorful scatter plot using third variable to define color. It is simple to use the following code:</p>
<pre><code>plt.scatter(mH, mA, s=1, c=mHc)
plt.colorbar()
plt.show()
</code></pre>
<p>But I do not have many choices to modify the frame of the plot. I am trying the following code to make colorful... | 1 | 2016-06-21T23:48:14Z | 37,956,885 | <p><code>size=0.5</code> is extremely small - probably all you are seeing is the marker outlines. I would suggest you increase the size a bit, and perhaps pass <code>edgecolors="none"</code> to turn off the marker edge stroke:</p>
<pre><code>import numpy as np
from matplotlib import pyplot as plt
n = 10000
x, y = np.... | 3 | 2016-06-22T00:55:07Z | [
"python",
"matplotlib",
"plot",
"colorbar"
] |
MITx: 6.00.1x Introduction to Computer Science and Programming Using Python | 37,956,380 | <p>So I'm very new to Python... The problem is as follows:</p>
<p><strong>Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.</strong></p>
<p>My current code is as follows:</p>
<pre><code>month = 1
minim... | 1 | 2016-06-21T23:50:55Z | 37,956,504 | <p>You are recalculating your balance before calculating your <code>minimumMonthlyPayment</code> rate.</p>
<p>So <code>balance * monthlyPaymentRate</code> comes to a different amount on line 8 and 9 since balance has changed.</p>
<p>If you assign <code>balance * monthlyPaymentRate</code> to a variable before those li... | 1 | 2016-06-22T00:03:15Z | [
"python"
] |
MITx: 6.00.1x Introduction to Computer Science and Programming Using Python | 37,956,380 | <p>So I'm very new to Python... The problem is as follows:</p>
<p><strong>Write a program to calculate the credit card balance after one year if a person only pays the minimum monthly payment required by the credit card company each month.</strong></p>
<p>My current code is as follows:</p>
<pre><code>month = 1
minim... | 1 | 2016-06-21T23:50:55Z | 37,956,535 | <p>Great job! Your code is almost perfect. The only mistake is that line 8 needs to run before line 9. You're changing the balance and then using that changed balance to calculate the minimum monthly payment. You need to calculate the minimum monthly payment for each month before you update the balance.</p>
<p>Hope th... | 0 | 2016-06-22T00:07:11Z | [
"python"
] |
Using a pandas DataFrame to get the count of the 10th most frequent value | 37,956,400 | <p>I have a DataFrame that contains entries of place_ids such as:</p>
<pre><code>place_id
11111
11111
22222
33333
44444
44444
...
</code></pre>
<p>I would like to get the count of the 10th most frequent value.</p>
<p>Here's what I've come up with:</p>
<pre><code>print df.place_id.value_counts().nlargest(10).tail(1)... | 2 | 2016-06-21T23:52:48Z | 37,956,434 | <p>try:</p>
<pre><code>import pandas as pd
import numpy as np
from string import ascii_letters
np.random.seed([3,1415])
s = pd.Series(np.random.choice(list(ascii_letters), (10000,)))
vc = s.value_counts().sort_values()
vc.loc[[vc.index[-10]]]
j 204
dtype: int64
</code></pre>
| 2 | 2016-06-21T23:56:44Z | [
"python",
"numpy",
"pandas",
"dataframe",
"series"
] |
Using a pandas DataFrame to get the count of the 10th most frequent value | 37,956,400 | <p>I have a DataFrame that contains entries of place_ids such as:</p>
<pre><code>place_id
11111
11111
22222
33333
44444
44444
...
</code></pre>
<p>I would like to get the count of the 10th most frequent value.</p>
<p>Here's what I've come up with:</p>
<pre><code>print df.place_id.value_counts().nlargest(10).tail(1)... | 2 | 2016-06-21T23:52:48Z | 37,957,690 | <p>You already have a decent solution I think. Here's an alternative that is marginally faster but for all practical purposes has the same performance:</p>
<pre><code>In [165]: place_ids.value_counts().nlargest(10).tail(1).values[0]
Out[165]: 1057
In [166]: place_ids.value_counts().sort_values().iloc[-10]
Out[166]: 1... | 1 | 2016-06-22T02:48:33Z | [
"python",
"numpy",
"pandas",
"dataframe",
"series"
] |
Cannot Access Variable Outside of Function | 37,956,427 | <p>I keep getting the following error when trying to access a variable from one function inside another function.</p>
<p>NameError: global name 'savemovieurl' is not defined</p>
<p>how can i access the "savemovieurl" from the function "tmdb_posters" inside "dynamic_data_entry" to save it to the database?</p>
<p>i've... | 0 | 2016-06-21T23:56:03Z | 37,956,599 | <p>I think this has already been answered here: <a href="http://stackoverflow.com/q/36186687/4862506">How do I use a variable so that it is inside and outside of a function</a></p>
<p>I know I should comment this however for some reason I can't so I just thought I'd write it as an answer instead. I hope this helps.</p... | 0 | 2016-06-22T00:14:12Z | [
"python"
] |
Write unittest for function with yield | 37,956,435 | <p>I am trying to write a unittest for a function that utilizes a generator. Below is my code:</p>
<pre><code>def extract_data(body):
for i in body:
a = re.sub('<[^<]+?>', '', str(i))
b = re.sub('view\xc2\xa0book\xc2\xa0info', '', str(a))
c = re.sub('key', '', str(b))
d = r... | 0 | 2016-06-21T23:56:48Z | 37,956,654 | <p>Your code, slightly altered to not require unittest:</p>
<pre><code>import re
def extract_data(body):
for i in body:
a = re.sub('<[^<]+?>', '', str(i))
b = re.sub('view\xc2\xa0book\xc2\xa0info', '', str(a))
c = re.sub('key', '', str(b))
d = re.sub('\xc2', ' ', str(c))
... | 1 | 2016-06-22T00:20:43Z | [
"python",
"unit-testing",
"generator"
] |
Write unittest for function with yield | 37,956,435 | <p>I am trying to write a unittest for a function that utilizes a generator. Below is my code:</p>
<pre><code>def extract_data(body):
for i in body:
a = re.sub('<[^<]+?>', '', str(i))
b = re.sub('view\xc2\xa0book\xc2\xa0info', '', str(a))
c = re.sub('key', '', str(b))
d = r... | 0 | 2016-06-21T23:56:48Z | 38,061,756 | <p>I figured out what I needed to do. I needed to make the res into a list. and that was it. A lot simpler than I expected. so this is what it looks like now:</p>
<pre><code>class TestScrapePage(unittest.TestCase):
def test_extract_data(self):
sample_input = ['<tr><h1>keyThis</h1><h2&... | 0 | 2016-06-27T19:28:10Z | [
"python",
"unit-testing",
"generator"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.