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 listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Python: Making one legend that spans two subplots | 38,402,293 | <p>The basic design I'm looking for is that I have two scatterplots side by side to each other, and then I wanted to create one legend underneath both subplots that spans both of them. This is a rough sketch:</p>
<p><a href="http://i.stack.imgur.com/Su69w.png" rel="nofollow"><img src="http://i.stack.imgur.com/Su69w.pn... | 0 | 2016-07-15T17:46:23Z | 38,402,730 | <p>You want to use <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.figlegend" rel="nofollow">figlegend</a> (<a href="http://matplotlib.org/examples/pylab_examples/figlegend_demo.html" rel="nofollow">demo</a>)</p>
<pre><code>figlegend( (line1, line2, line3), ('label1', 'label2', 'label3'), 'upper r... | 1 | 2016-07-15T18:16:38Z | [
"python",
"matplotlib",
"subplot"
] |
Python: Making one legend that spans two subplots | 38,402,293 | <p>The basic design I'm looking for is that I have two scatterplots side by side to each other, and then I wanted to create one legend underneath both subplots that spans both of them. This is a rough sketch:</p>
<p><a href="http://i.stack.imgur.com/Su69w.png" rel="nofollow"><img src="http://i.stack.imgur.com/Su69w.pn... | 0 | 2016-07-15T17:46:23Z | 38,402,856 | <p>Borrowing code from <a href="http://stackoverflow.com/questions/10545330/matplotlib-legend-with-multiple-axes-with-errorbar-object/34173062#34173062">matplotlib - Legend with multiple axes with errorbar object</a> and <a href="http://stackoverflow.com/questions/4700614/how-to-put-the-legend-out-of-the-plot">How to p... | 1 | 2016-07-15T18:26:01Z | [
"python",
"matplotlib",
"subplot"
] |
Python/Pygame Title Rendering | 38,402,310 | <p>I'm trying to render a title for a little project I'm working on. I've replicated the same code which was used to create the options set (merely for ease) yet it isn't working. I was wondering if anyone knows where I'm going wrong? it's probably something really obvious but I'm not experienced when it comes to pytho... | 0 | 2016-07-15T17:47:28Z | 38,644,534 | <p>I do not know what exactly you want to happen. But I think you simple have some typos. The line <code>title = [Title("NOTPONG", (150,20))</code> needs to be <code>title = [Title("NOTPONG", (150,20))]</code> with the closing bracket. And the line <code>title_font = pygame.display.font.Font(None, 42)</code> needs to b... | 0 | 2016-07-28T18:51:46Z | [
"python",
"text",
"fonts",
"pygame"
] |
Reading a multibyte text file in Windows - how does it detect newlines? (Python 2) | 38,402,355 | <p>I thought this was a caveat of a Unicode world -> you cannot <em>correctly</em> process a byte stream as writing without knowing what the encoding is. If you assume an encoding, then you might get valid - but incorrect - characters showing up.</p>
<p>Here's a test - a file with the writing:</p>
<pre><code>hi1
hi2
... | 0 | 2016-07-15T17:50:30Z | 38,402,611 | <p>First things first: open your file as text, indicating the correct encodin,and in explicit text mode.</p>
<p>If you are still using Python 2.7, use <code>codecs.open</code> instead of <code>open</code>. In Python 3.x, just use open:</p>
<pre><code>import codecs
myfile = codecs.open('d:/t/hi2.txt', 'rt', encoding='... | 0 | 2016-07-15T18:08:01Z | [
"python",
"windows",
"unicode"
] |
Reading a multibyte text file in Windows - how does it detect newlines? (Python 2) | 38,402,355 | <p>I thought this was a caveat of a Unicode world -> you cannot <em>correctly</em> process a byte stream as writing without knowing what the encoding is. If you assume an encoding, then you might get valid - but incorrect - characters showing up.</p>
<p>Here's a test - a file with the writing:</p>
<pre><code>hi1
hi2
... | 0 | 2016-07-15T17:50:30Z | 38,405,822 | <p>The result in this case has nothing to do with Windows or the standard I/O implementation of Microsoft's C runtime. You'll see the same result if you test this in Python 2 on a Linux system. It's just how <a href="https://hg.python.org/cpython/file/v2.7.12/Objects/fileobject.c#l1659" rel="nofollow"><code>file.readli... | 1 | 2016-07-15T22:28:00Z | [
"python",
"windows",
"unicode"
] |
tab autocomplete on python script execution in console | 38,402,359 | <p>i'm having this "issue" (for lack of better word), whenever i run my python script with arguments, i can't use the tab completion function of Unix consoles. For example when i want to put a file in the script execution.
Hope this examples illustrate better my issue.</p>
<p>Case 1</p>
<pre><code>>python3 script.... | -2 | 2016-07-15T17:50:58Z | 38,425,485 | <p>Ok, for a work around this. Using python 3.5 i can achieve what i wanted, autocomplete name of files in bash when executing a python script.</p>
<p>so with</p>
<pre><code>> python3 script.py
[tab]
folder/ folder1/ data.dat
> python3 script.py -f d
[tab]
folder/ folder1/ (file data.dat not showing)
</code></... | 0 | 2016-07-17T20:08:06Z | [
"python",
"shell",
"python-3.x",
"unix",
"execution"
] |
displaying values from entry boxes in tkinter | 38,402,473 | <p>I am currently doing gcse computer science and for my current piece of work I have to make a population model. I have made several entry boxes and want to be able to store and then get that information to print on another window and later use it in calculations. Please could somebody help me to get the values to pri... | -1 | 2016-07-15T17:58:51Z | 38,403,468 | <p>First, the <code>command</code> option of a button expects a function, so your code is wrong when you write <code>command=entQuestion7.get()</code>, it should be <code>command=entQuestion7.get</code>. But even this way, nothing will happend because you don't do anything with the value.</p>
<p>Secondly, I think it s... | 0 | 2016-07-15T19:06:18Z | [
"python",
"tkinter"
] |
No output from Python subprocess | 38,402,553 | <p>I'm using Python 3.5.1 and Windows 10. I can't get <code>subprocess</code> to put output to the screen. So let's start with something simple: </p>
<pre><code>import subprocess
process = subprocess.run('echo hi', shell=True, stdout=subprocess.PIPE)
</code></pre>
<p>When I run my python module, I want to it to print... | -2 | 2016-07-15T18:04:07Z | 38,402,662 | <p>It's not printing to the screen because you're redirecting the output to a <code>PIPE</code>. Remove the pipe argument and the output will go to the normal <code>stdout</code></p>
<p>You can use <code>subprocess.call</code> also.</p>
<pre><code>subprocess.call('echo hi', shell=True)
</code></pre>
<p>If you want ... | 2 | 2016-07-15T18:11:21Z | [
"python",
"windows",
"shell",
"python-3.x",
"subprocess"
] |
Grouping the values of all columns by index of a pandas dataframe | 38,402,574 | <p>I want to basically build a distribution of total no. of videos a user has watched. Watch is signified by 1 else 0. Users are index of the data frame. </p>
<p>Assume the data is like this: </p>
<pre><code>A B C
User1 1 1 0
User2 0 1 0
User3 1 0 1
</code></pre>
<p>I want for each use a count ... | 1 | 2016-07-15T18:05:45Z | 38,402,675 | <p>Use the <strong>transpose</strong> method of the DataFrame.</p>
<pre><code>In [38]: d = pd.DataFrame({'A':[1,0,1],'B':[1,1,0],'C':[0,0,1]},index=['User1','User2','User3'])
In [39]: d
Out[39]:
A B C
User1 1 1 0
User2 0 1 0
User3 1 0 1
In [40]: d.transpose()
Out[40]:
User1 User2 User3
A ... | -1 | 2016-07-15T18:12:28Z | [
"python",
"pandas"
] |
Grouping the values of all columns by index of a pandas dataframe | 38,402,574 | <p>I want to basically build a distribution of total no. of videos a user has watched. Watch is signified by 1 else 0. Users are index of the data frame. </p>
<p>Assume the data is like this: </p>
<pre><code>A B C
User1 1 1 0
User2 0 1 0
User3 1 0 1
</code></pre>
<p>I want for each use a count ... | 1 | 2016-07-15T18:05:45Z | 38,402,963 | <p>If you have duplicates in index, you can use <code>groupby</code> with double <code>sum</code>:</p>
<pre><code>print (df)
A B C
User1 1 1 0
User1 1 1 1
User2 0 1 0
User3 1 0 1
print (df.groupby(df.index).sum().sum(1))
User1 5
User2 1
User3 2
dtype: int64
</code></pre>
<p>If there are... | 0 | 2016-07-15T18:31:53Z | [
"python",
"pandas"
] |
requests: 'module' object has no attribute 'get' | 38,402,714 | <p>I installed the <code>requests</code> package last week and it worked fine.. Until this morning. I coded this and I got the <code>AttributeError: 'module' object has no attribute 'get'</code> message:</p>
<pre><code>import requests
r = requests.get('http://www.yellowpages.com/search?search_terms=coffee&geo_loc... | 0 | 2016-07-15T18:15:00Z | 38,402,742 | <p>Is it possible that you named your script <code>requests.py</code> or that you have a similarly named file in the same directory?</p>
| 0 | 2016-07-15T18:17:24Z | [
"python",
"python-3.x",
"python-requests"
] |
logout and login with different twitter account using ( Django + Allauth ) | 38,402,760 | <p>I am using Allauth to login with twitter in my Django app.
I have a problem to logout from existing account to login with different one. </p>
<p>I make logout in function logout in my views.py<br>
and within it i tried to call:</p>
<pre><code>from django.contrib import auth
auth.logout(request)
</code></pre>
<p... | 0 | 2016-07-15T18:19:02Z | 38,402,978 | <p>All auth takes care of it, jut build a url to:
/accounts/logout/</p>
<p>No need to write your own view. If you want to know what it does you could override their view.</p>
| 0 | 2016-07-15T18:32:32Z | [
"python",
"django",
"twitter",
"django-allauth"
] |
list comprehension with multiple conditions (python) | 38,402,777 | <p>The following code works in Python</p>
<pre><code>var=range(20)
var_even = [0 if x%2==0 else x for x in var]
print var,var_even
</code></pre>
<p>However, I thought that the conditions need to be put in the end of a list. If I make the code</p>
<pre><code>var_even = [0 if x%2==0 for x in var]
</code></pre>
<p>The... | 0 | 2016-07-15T18:20:01Z | 38,402,817 | <p><code>0 if x%2==0</code> the syntax is <code>value1 if conditionX else value2</code> , what it does is if conditionX is true, it returns value1, otherwise it returns value2. You cannot use it if you want to get the event numbers from the list, you always return value 0 if it is an even number and you miss the else ... | 1 | 2016-07-15T18:23:18Z | [
"python",
"list"
] |
list comprehension with multiple conditions (python) | 38,402,777 | <p>The following code works in Python</p>
<pre><code>var=range(20)
var_even = [0 if x%2==0 else x for x in var]
print var,var_even
</code></pre>
<p>However, I thought that the conditions need to be put in the end of a list. If I make the code</p>
<pre><code>var_even = [0 if x%2==0 for x in var]
</code></pre>
<p>The... | 0 | 2016-07-15T18:20:01Z | 38,402,873 | <p>There are two distinct but similar-looking syntaxes involved here, <strong>conditional expressions</strong> and <strong>list comprehension filter clauses</strong>.</p>
<p>A conditional expression is of the form <code>x if y else z</code>. This syntax isn't related to list comprehensions. If you want to conditionall... | 3 | 2016-07-15T18:27:03Z | [
"python",
"list"
] |
Get literal prefix of regex pattern | 38,402,822 | <p>Here is the problem:</p>
<p>There is a list of thousands of regular expressions. I need to get regular expression which matches to the given string. <em>Hopefully</em>, these regexes are mutually exclusive, so if several regexes are matching at the same time, I'm ok with returning <em>any</em> of them.</p>
<p>I as... | 0 | 2016-07-15T18:23:30Z | 38,403,706 | <p>I came to the following regular expression: </p>
<pre><code>(?:[^.^$*+?{\\[|(]|(?:\\(?:[^\dAbBdDsSwWZ]|0|[0-7]{3})))*(?![*?|]|{\d+(?:,\d*)?})
</code></pre>
<ul>
<li><p>It's needed to replace backslash+symbol with the symbol in matched string after search: </p>
<p><code>\$</code> â <code>$</code></p></li>
<li><p... | 0 | 2016-07-15T19:23:19Z | [
"python",
"regex"
] |
Validate that a WTForms BooleanField is checked | 38,402,850 | <p>I am creating a form using Flask-WTForms.</p>
<p>I am using a BooleanField so that a user can indicate they agree terms.</p>
<p>I cannot validate the BooleanField upon submission to ensure that it has been checked. I have tried using Required(), DataRequired() and custom validation but in each case I have not rece... | 0 | 2016-07-15T18:25:30Z | 38,403,451 | <p>Works for meâ you do need to use <code>DataRequired()</code> (<code>Required</code> is being deprecated):</p>
<pre><code>from flask import Flask, render_template
from flask_wtf import Form
from wtforms import BooleanField
from wtforms.validators import DataRequired
app = Flask(__name__)
app.secret_key = 'STACKOV... | 2 | 2016-07-15T19:05:35Z | [
"python",
"flask",
"wtforms",
"flask-wtforms"
] |
Best way to get info out of dictionary | 38,402,863 | <p>I am struggling to wrap my head around the best way to get the Title, Artist Name out the following list.</p>
<pre><code>{'status': 'ok', 'results': [{'score': 0.94222, 'id': 'ca222fc1-d1ed-4c30-b21f-eb533cc909aa', 'recordings': [{'artists': [{'id': '84dc4f23-c0b8-4fe1-bbca-a3993ddc8fc2', 'name': 'Primus'}], 'id': ... | -1 | 2016-07-15T18:26:17Z | 38,403,028 | <p>If the dict is bothering you, you may want to convert it to a class.</p>
<pre><code>class Music():
def __init__(self, song):
self.title = song['results'][0]['recordings'][0]['title']
self.artist = song['results'][0]['recordings'][0]['artist'][0]['name']
# and so on and so forth
new_so... | 2 | 2016-07-15T18:35:44Z | [
"python"
] |
Best way to get info out of dictionary | 38,402,863 | <p>I am struggling to wrap my head around the best way to get the Title, Artist Name out the following list.</p>
<pre><code>{'status': 'ok', 'results': [{'score': 0.94222, 'id': 'ca222fc1-d1ed-4c30-b21f-eb533cc909aa', 'recordings': [{'artists': [{'id': '84dc4f23-c0b8-4fe1-bbca-a3993ddc8fc2', 'name': 'Primus'}], 'id': ... | -1 | 2016-07-15T18:26:17Z | 38,403,042 | <p>The data which you getting is mix of dict and list. Since list can only be accessed via index I dont think there could be a better way of doing it unless you preprocess your data to remove that extra nested list.</p>
| 0 | 2016-07-15T18:36:26Z | [
"python"
] |
Creating Grouped bars in Matplotlib | 38,402,890 | <p>I have just started learning python and I am using the Titanic data set to practice </p>
<p>I am not able to create a grouped bar chart and it it giving me an error
'incompatible sizes: argument 'height' must be length 2 or scalar'</p>
<pre><code>import numpy as np
import pandas as pd
import matplotlib.pyplot as p... | -1 | 2016-07-15T18:27:46Z | 38,404,017 | <p>How about replacing your second block of code (the one that returns a <code>ValueError</code>) with this</p>
<pre><code>bar_width = 0.35
tot_people_count = (female_count + male_count) * 1.0
plt.bar(0, female_count, bar_width, color ='b')
plt.bar(1, male_count, bar_width, color ='y',)
plt.bar(0, have_survived/tot_... | 0 | 2016-07-15T19:44:58Z | [
"python",
"numpy",
"pandas",
"matplotlib",
"bar-chart"
] |
How to make dynamic updates to the database using a list in python | 38,402,895 | <pre><code>if year in Year:
#print 'executing'
for rows in range(1,sheet.nrows):
records = []
FIP = str(sheet.cell(rows, 1).value)
for cols in range(9,sheet.ncols):
records.append(str(sheet.cell(rows,cols).value))
cur.execute("UPDATE " + str(table_name) + " SET " + (str(variables[0... | 0 | 2016-07-15T18:28:10Z | 38,406,886 | <p>You will find it easier to use parameter-substitution. See <a href="https://www.python.org/dev/peps/pep-0249/#paramstyle" rel="nofollow">params</a>, and note that <strong>execute</strong> takes a sequence argument. Then that line starts to look something like, </p>
<pre><code>cur.execute(sql, records)
</code></pr... | 0 | 2016-07-16T01:31:19Z | [
"python",
"sql-server"
] |
Split rows according to text in two columns (Python, Pandas) | 38,402,906 | <p>This is my dataframe (with many more letters and a length of ~35.5k) and stuff where the â are other relevant strings). All the variables are strings and ['C1','C2'] is the MultiIndex.</p>
<pre><code>tmp
C1 C2 C3 C4 C5 Start End C8
A 1 - - - 12 14 -
A 2 ... | 1 | 2016-07-15T18:28:53Z | 38,403,123 | <p>You can create new <code>df</code> from <code>s1</code> and <code>s2</code> and then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.join.html" rel="nofollow"><code>join</code></a>. Also better is use parameter <code>expand=True</code> in <a href="http://pandas.pydata.org/pandas-docs/... | 3 | 2016-07-15T18:42:24Z | [
"python",
"string",
"pandas",
"split",
"multi-index"
] |
Split rows according to text in two columns (Python, Pandas) | 38,402,906 | <p>This is my dataframe (with many more letters and a length of ~35.5k) and stuff where the â are other relevant strings). All the variables are strings and ['C1','C2'] is the MultiIndex.</p>
<pre><code>tmp
C1 C2 C3 C4 C5 Start End C8
A 1 - - - 12 14 -
A 2 ... | 1 | 2016-07-15T18:28:53Z | 38,403,220 | <p>I concat the expanded <code>'Start'</code> and <code>'End'</code> columns to ensure they match up even if they don't have the same number of entries.</p>
<pre><code>s = tmp.Start.str.split(',', expand=True).stack().rename('Start')
e = tmp.End.str.split(',', expand=True).stack().rename('End')
se = pd.concat([s, e], ... | 3 | 2016-07-15T18:49:01Z | [
"python",
"string",
"pandas",
"split",
"multi-index"
] |
Python define class functions in seperate py file | 38,402,932 | <p>I am working on a project that deals with data analysis. In order to simplify the process of finding and modifying functions, I have decided to put functions of a similar purposes in different py files. The issue comes in when functions in one py file require functions from another to work. I think I can solve the i... | -1 | 2016-07-15T18:30:11Z | 38,403,034 | <p>You don't need classes, you simply need to re-think the responsibility of your functions. In general, any case where you have <code>A</code> depends on <code>B</code> and <code>B</code> depends on <code>A</code> you're confused.</p>
<p>What you typically want to have is:</p>
<ul>
<li><code>C</code> depends on <cod... | 1 | 2016-07-15T18:36:12Z | [
"python",
"class",
"prototype",
"forward-declaration"
] |
Python define class functions in seperate py file | 38,402,932 | <p>I am working on a project that deals with data analysis. In order to simplify the process of finding and modifying functions, I have decided to put functions of a similar purposes in different py files. The issue comes in when functions in one py file require functions from another to work. I think I can solve the i... | -1 | 2016-07-15T18:30:11Z | 38,403,094 | <ol>
<li><p>To avoid confusion, in <code>a.py</code> and <code>b.py</code>, rename your implementation functions <code>a1_impl</code>, <code>a2_impl</code>, ... (or some other consistent naming convention).</p></li>
<li><p>Update the code:</p>
<pre><code>from b import *
from a import *
class test(object):
a1 = a1... | 0 | 2016-07-15T18:40:29Z | [
"python",
"class",
"prototype",
"forward-declaration"
] |
Python define class functions in seperate py file | 38,402,932 | <p>I am working on a project that deals with data analysis. In order to simplify the process of finding and modifying functions, I have decided to put functions of a similar purposes in different py files. The issue comes in when functions in one py file require functions from another to work. I think I can solve the i... | -1 | 2016-07-15T18:30:11Z | 38,403,107 | <p>Use mix-in classes:</p>
<pre><code># In a.py
class A(object):
def a1(self):
self.var=3
def a2(self):
self.b1(4)
# In b.py
class B(object):
def b1(self, x):
self.var=x
def b2(self):
self.a1()
# In testclass.py
class Test(A, B):
def __init__(self):
self... | 0 | 2016-07-15T18:41:19Z | [
"python",
"class",
"prototype",
"forward-declaration"
] |
Dictionary Comprehension to generate values of built-in type | 38,402,938 | <p>I would like to do a dictionary comprehension to get a list of keys with the built-in type of <code>str</code> as values. </p>
<pre><code>headers = ['Header1', 'Header2', 'Header3']
print dict([(x,str) for x in headers])
</code></pre>
<p>output:</p>
<pre><code>{'Header2': <type 'str'>, 'Header3': <type '... | 1 | 2016-07-15T18:30:29Z | 38,402,994 | <p>You <strong>do</strong> have a dictionary with the built-in <code>str</code> in it. </p>
<p>The <code><type 'str'></code> is due to the <code>print</code> call which will use the value obtained from calling an objects' <code>__str__</code> when it prints it. That value for <code>str</code> is <code><type '... | 5 | 2016-07-15T18:33:33Z | [
"python",
"python-2.7",
"dictionary",
"dictionary-comprehension"
] |
Django/Python: Import once, use everywhere | 38,402,941 | <p>I have the following structure for my <code>views</code> directory.</p>
<pre><code>views
|--__init__.py
|--a_management.py
|--b_management.py
|--c_management.py
|--d_management.py
|--e_management.py
</code></pre>
<p>and <code>__init__.py</code> starts with the following:</p>
<pre><code>from a_management import *
... | 5 | 2016-07-15T18:30:32Z | 38,403,360 | <p>If each <code>management</code> module needs access to <code>sys</code>, then they all must import it. No way around that. (And really, if they all need it, then they all <em>should</em> import it. It's not a bad thing.)</p>
<p>You could save a bit of typing by having <code>__init__</code> import <code>sys</code... | 3 | 2016-07-15T18:59:11Z | [
"python",
"django",
"python-import"
] |
Django/Python: Import once, use everywhere | 38,402,941 | <p>I have the following structure for my <code>views</code> directory.</p>
<pre><code>views
|--__init__.py
|--a_management.py
|--b_management.py
|--c_management.py
|--d_management.py
|--e_management.py
</code></pre>
<p>and <code>__init__.py</code> starts with the following:</p>
<pre><code>from a_management import *
... | 5 | 2016-07-15T18:30:32Z | 38,403,714 | <p>What about using a shared script to do all the system imports?</p>
<p>BTW, I agree that <code>import *</code> is not the greatest of idea. It makes sense in my use of <strong>importer</strong>, but I am not so sure in your general setup. Also, you need to careful about circular imports.</p>
<p>So, my answer is s... | 2 | 2016-07-15T19:23:58Z | [
"python",
"django",
"python-import"
] |
How to write data to Redshift that is a result of a dataframe created in Python? | 38,402,995 | <p>I have a dataframe in Python. Can I write this data to Redshift as a new table?
I have successfully created a db connection to Redshift and am able to execute simple sql queries.
Now I need to write a dataframe to it. </p>
| 1 | 2016-07-15T18:33:34Z | 38,443,665 | <p>For the purpose of this conversation Postgres = RedShift
You have two options:</p>
<p><strong>Option 1:</strong></p>
<p>From Pandas:
<a href="http://pandas.pydata.org/pandas-docs/stable/io.html#io-sql" rel="nofollow">http://pandas.pydata.org/pandas-docs/stable/io.html#io-sql</a></p>
<p>The pandas.io.sql module pr... | 0 | 2016-07-18T18:28:11Z | [
"python",
"pandas",
"dataframe",
"amazon-redshift",
"psycopg2"
] |
How to write data to Redshift that is a result of a dataframe created in Python? | 38,402,995 | <p>I have a dataframe in Python. Can I write this data to Redshift as a new table?
I have successfully created a db connection to Redshift and am able to execute simple sql queries.
Now I need to write a dataframe to it. </p>
| 1 | 2016-07-15T18:33:34Z | 39,709,820 | <p>You can use <code>to_sql</code> to push data to a Redshift database. I've been able to do this using a connection to my database through a SQLAlchemy engine. Just be sure to set <code>index = False</code> in your <code>to_sql</code> call. The table will be created if it doesn't exist, and you can specify if you w... | 2 | 2016-09-26T18:24:44Z | [
"python",
"pandas",
"dataframe",
"amazon-redshift",
"psycopg2"
] |
Python: Adding hour vector to date vector elementwise | 38,403,141 | <p>I have an array of dates as:</p>
<pre><code>>>> dates
array([datetime.datetime(2013, 1, 1, 0, 0),
datetime.datetime(2013, 1, 2, 0, 0),
datetime.datetime(2013, 2, 1, 0, 0))], dtype=object)
</code></pre>
<p>I have corresponding array of hours of same size as dates:</p>
<pre><code>numpy.asarra... | 2 | 2016-07-15T18:43:41Z | 38,403,197 | <p>All you need is creating <code>timedelta</code>s from your hours as a numpy array tehm add it with your dates:</p>
<pre><code>>>> import datetime
>>> import numpy as np
>>> dates = np.array([datetime.datetime(2013, 1, 1, 0, 0),
... datetime.datetime(2013, 1, 2, 0, 0),
... da... | 1 | 2016-07-15T18:47:54Z | [
"python",
"datetime",
"numpy"
] |
Getting nameerror in python | 38,403,142 | <p>I have the following function, I want to concat the 2 strings, What wrong am I doing here?</p>
<pre><code>commands = ["abcd","123"]
def configure_dev(self, steps):
func_name = self.id + ':configure dev'
global conf_cmd
for key in commands:
conf_cmd += key + '\n'
print(conf_cmd)
</code></pr... | 1 | 2016-07-15T18:43:43Z | 38,403,193 | <p>All you need to do is to add:
<code>conf_cmd = ''</code></p>
<p>just after <code>commands = ["abcd","123"]</code></p>
<p>Why?
<code>global conf_cmd</code> Does not create new string, it just means you can access the global variable. </p>
| 1 | 2016-07-15T18:47:38Z | [
"python"
] |
Getting nameerror in python | 38,403,142 | <p>I have the following function, I want to concat the 2 strings, What wrong am I doing here?</p>
<pre><code>commands = ["abcd","123"]
def configure_dev(self, steps):
func_name = self.id + ':configure dev'
global conf_cmd
for key in commands:
conf_cmd += key + '\n'
print(conf_cmd)
</code></pr... | 1 | 2016-07-15T18:43:43Z | 38,403,202 | <p>I added your code with your critical issue resolved.</p>
<pre><code>commands = ["abcd","123"]
def configure_dev(self, steps):
func_name = self.id + ':configure dev'
global conf_cmd = '' // <-- ''
for key in commands:
conf_cmd+=key+'\n'
print(conf_cmd)
</code></pre>
| 1 | 2016-07-15T18:48:02Z | [
"python"
] |
Need Python regex for all characters between double quotes after 'returned' | 38,403,159 | <p>I have an error message response...</p>
<pre><code><HttpError 404 when requesting https://www.googleapis.com/bigquery/v2/projects/di-dtbqquery-us-poc-1/queries?alt=json returned "Not found: Table di-dtbqquery-us-poc-1:lab_auxiliary.antonioTes">`
</code></pre>
<p>I only need the text between the double quotes... | 0 | 2016-07-15T18:44:56Z | 38,403,198 | <p>Try something like this:</p>
<pre><code>.*returned "(?P<error_message>.*)"
</code></pre>
| 2 | 2016-07-15T18:47:57Z | [
"python",
"regex"
] |
Prints a 2D list of the possible rolls of two dice in python | 38,403,168 | <p>I am trying to print a 2D list of the possible rolls of two dice in python 3.0+, using Eclipse
I have two questions. First, why my prof gave the function that take no arguments, what should I write for the main program?
Second, when it runs to r.append(result) , it said AttributeError: 'int' object has no attribute ... | 1 | 2016-07-15T18:45:30Z | 38,403,316 | <p>I am not going to do your homework, but to answer your questions:</p>
<p>1) Probably because your Professor wanted to make the assignment more challenging</p>
<p>2) Because when you are trying to append <code>r</code>, <code>r</code> is an int</p>
<pre><code>for r in range(DICE1): # r are the integers in the ran... | 1 | 2016-07-15T18:55:42Z | [
"python"
] |
How to segment blood vessels python opencv | 38,403,205 | <p>I am trying to segment the blood vessels in retinal images using Python and OpenCV. Here is the original image:</p>
<p><a href="http://i.stack.imgur.com/aB4Iz.jpg" rel="nofollow"><img src="http://i.stack.imgur.com/aB4Iz.jpg" alt="enter image description here"></a></p>
<p>Ideally I want all the blood vessels to be ... | 6 | 2016-07-15T18:48:13Z | 38,414,873 | <p>I worked on retina vessel detection for a bit few years ago, and there are different ways to do it:</p>
<ul>
<li>If you don't need a top result but something fast, you can use oriented openings, <a href="https://www.researchgate.net/publication/3327391_Segmentation_of_vessel-like_patterns_using_mathematical_morphol... | 0 | 2016-07-16T19:33:16Z | [
"python",
"image",
"opencv",
"computer-vision",
"edge-detection"
] |
How to multiply every other list item by 2 in python | 38,403,219 | <p>I'm making a program that validates a credit card, by multiplying every other number in the card number by 2; after i'll add the digits multiplied by 2 to the ones not multiplied by 2. All of the double digit numbers are added by the sum of their digits, so 14 becomes 1+4. I have a photo below that explains it all. ... | -1 | 2016-07-15T18:48:57Z | 38,403,386 | <p>To perform that sum:</p>
<pre><code>>>> s = '4417123456789113'
>>> sum(int(c) for c in ''.join(str(int(x)*(2-i%2)) for i, x in enumerate(s)))
70
</code></pre>
<h3>How it works</h3>
<p>The code consists of two parts. The first part creates a string with every other number doubled:</p>
<pre><cod... | 2 | 2016-07-15T19:00:54Z | [
"python"
] |
How to multiply every other list item by 2 in python | 38,403,219 | <p>I'm making a program that validates a credit card, by multiplying every other number in the card number by 2; after i'll add the digits multiplied by 2 to the ones not multiplied by 2. All of the double digit numbers are added by the sum of their digits, so 14 becomes 1+4. I have a photo below that explains it all. ... | -1 | 2016-07-15T18:48:57Z | 38,403,416 | <p>You need to increment the <code>count</code> inside the <code>while()</code> loop. Also, append the user input to your <code>card_li</code> list after you have the <code>if..</code> check. Your <strong>init</strong> method should look like:</p>
<pre><code>def __init__(self):
count = 1
self.card_li = []
... | 0 | 2016-07-15T19:03:04Z | [
"python"
] |
Can't get my program to animate multiple patches in python matplotlib | 38,403,232 | <p>I am attempting to animate two different particles in matplotlib (python). I just figured out a way to animate one particle in matplotlib, but I am havign difficulties trying to get the program to work with multiple particles. Does anyone know what is wrong and how to fix it?</p>
<pre><code>import numpy as np
from ... | 0 | 2016-07-15T18:49:57Z | 38,421,142 | <pre><code>import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
fig = plt.figure()
fig.set_dpi(100)
fig.set_size_inches(5, 4.5)
ax = plt.axes(xlim=(0, 100), ylim=(0, 100))
enemy = plt.Circle((10, -10), 0.75, fc='r')
agent = plt.Circle((10, -10), 0.75, fc='b')
def init():
enem... | 1 | 2016-07-17T12:24:58Z | [
"python",
"animation",
"matplotlib",
"plot",
"simulation"
] |
Django RegexValidator fails on empty string | 38,403,238 | <p>I have added a custom validation for my username field,</p>
<p>my regex is, <code>^[a-zA-Z0-9_]{1,15}$</code> which I need to validate a-z, 0-9 and _ (underscores) of length 1-15.</p>
<pre><code>def validate_username(value):
valid_username = r'^[a-zA-Z0-9_]{1,15}$'
validator = RegexValidator(regex=valid_u... | 0 | 2016-07-15T18:50:25Z | 38,403,317 | <p>The <code>validator</code> is never called in your <code>save</code> method when the string is empty:</p>
<pre><code>if self.username: # an empty string will not pass this condition
self.username = validate_username(self.username)
</code></pre>
| 2 | 2016-07-15T18:55:43Z | [
"python",
"regex",
"django"
] |
Django Model Graph (pydot) Error | 38,403,350 | <p>I have recently started working on a big Django project with existing complicated model. I needed to visualize that model, so I decided to use django-extensions (namely <strong>pygraphviz</strong>). But unfortunately, failed to install <strong>pygraphviz</strong> on windows using pip, so I installed <strong>pydot</s... | 1 | 2016-07-15T18:58:30Z | 38,412,639 | <p>You must use older <code>pydot</code>. Version 1.1.0 works for me. Install with:</p>
<pre><code>pip install pydot==1.1.0
</code></pre>
| 0 | 2016-07-16T15:32:16Z | [
"python",
"django",
"graph",
"model",
"pydot"
] |
Django Model Graph (pydot) Error | 38,403,350 | <p>I have recently started working on a big Django project with existing complicated model. I needed to visualize that model, so I decided to use django-extensions (namely <strong>pygraphviz</strong>). But unfortunately, failed to install <strong>pygraphviz</strong> on windows using pip, so I installed <strong>pydot</s... | 1 | 2016-07-15T18:58:30Z | 39,171,212 | <p>pydot==1.1.0 doesn't work for me with Python 3.5. as pydot 1.1.0 is not compatible with <strong>Python 3.5</strong></p>
<p>Using <strong>pydotplus</strong> worked for me.</p>
<pre><code>pip install pydotplus
</code></pre>
| 1 | 2016-08-26T16:54:31Z | [
"python",
"django",
"graph",
"model",
"pydot"
] |
OpenGL (Python) - applying an STMap (UVmap) to an image? | 38,403,443 | <p>i have the following code that loads and displays (using PyQt) an image on the screen:</p>
<pre><code>gVShader = """
attribute vec4 position;
attribute vec2 texture_coordinates;
varying vec2 v_texture_coordinates;
void main() {
v_texture_coor... | 2 | 2016-07-15T19:05:08Z | 38,473,827 | <p>Since I do not have all resources I cannot run you code here.</p>
<p>From the shader point of view, you can modify <code>texture1</code> coordinates by using <code>texture2</code> coordinates.
There are many ways to do that, for example you could just translate them by adding UVMap values to it. Here, <code>texture... | 2 | 2016-07-20T06:29:12Z | [
"python",
"opengl"
] |
pygame crash right after taking an action | 38,403,479 | <p>Im new at Python, so the problem at my code is probably a silly one.
Right after the image of the player is moving, the window of the pygame is crashing without an error message at the IDLE.</p>
<p>im using Python 2.7.
Here's the code: </p>
<pre><code>import pygame,sys
from pygame.locals import *
pygame.init()
di... | 0 | 2016-07-15T19:06:37Z | 38,403,994 | <p>I just skimmed over your program, if I'm not wrong (hopefully I'm not) you keep adding 10 to cax, the result is that your player reaches the position which will set flag to false after just 26 iterations in your while loop.
This will happen quite fast.</p>
| 0 | 2016-07-15T19:43:19Z | [
"python",
"pygame"
] |
pygame crash right after taking an action | 38,403,479 | <p>Im new at Python, so the problem at my code is probably a silly one.
Right after the image of the player is moving, the window of the pygame is crashing without an error message at the IDLE.</p>
<p>im using Python 2.7.
Here's the code: </p>
<pre><code>import pygame,sys
from pygame.locals import *
pygame.init()
di... | 0 | 2016-07-15T19:06:37Z | 38,404,217 | <p>I look through your program and the issue is that you set <code>flag = False</code> when <code>if cax == 410</code>. That is why your program quits, because the condition becomes True after just a couple of seconds. But there are many things you should consider, so I made some changes (not in the program but in name... | 0 | 2016-07-15T19:59:14Z | [
"python",
"pygame"
] |
ipcluster on Sun Grid Engine has only ranks 0 | 38,403,534 | <p>I set up an IPython parallel <code>ipcluster</code> to use the Sun Grid Engine and things seem to work fine:</p>
<p><code>ipcluster start -n 100 --profile=sge</code></p>
<pre><code>2016-07-15 14:47:09.749 [IPClusterStart] Starting ipcluster with [daemon=False]
2016-07-15 14:47:09.751 [IPClusterStart] Creating pid ... | 0 | 2016-07-15T19:11:10Z | 38,433,954 | <p>Found the solution/bug myself:</p>
<p>in <code>ipcluster_config.py</code>, I forgot to rename some cases of <code>Slurm</code>-><code>SGE</code>, so it should be</p>
<pre class="lang-py prettyprint-override"><code>c.IPClusterEngines.engine_launcher_class = 'SGEEngineSetLauncher'
c.IPClusterStart.controller_launche... | 0 | 2016-07-18T10:07:06Z | [
"python",
"ipython",
"sungridengine",
"ipython-parallel"
] |
Find duplicates, add to variable and remove | 38,403,761 | <p>I have a script that writes sales values to separate lines in a file and the ultimate goal is to save the data into a database. The problem I'm running into is that there are duplicate entries for the same sales person, date, product, price and quantity.</p>
<p>My code is written like this to the file:</p>
<pre><c... | 1 | 2016-07-15T19:27:05Z | 38,403,919 | <p>Assuming your files is called records.txt</p>
<p>To Split the file into a separate file for each salesperson:</p>
<p><code>awk '{print > $1}' records.txt</code></p>
<p>Then to count specific items per salesperson:</p>
<p><code>cat Sara | grep 'Hammer' | awk '{print $NF,sum}' | awk '{s+=$1} END {print s}'</code><... | 0 | 2016-07-15T19:38:11Z | [
"python",
"django",
"counter"
] |
Find duplicates, add to variable and remove | 38,403,761 | <p>I have a script that writes sales values to separate lines in a file and the ultimate goal is to save the data into a database. The problem I'm running into is that there are duplicate entries for the same sales person, date, product, price and quantity.</p>
<p>My code is written like this to the file:</p>
<pre><c... | 1 | 2016-07-15T19:27:05Z | 38,404,040 | <p>sample.csv</p>
<pre><code>John 07-15-2016 Tool Belt $100 2
Sara 07-15-2016 Hammer $100 3
John 07-15-2016 Tool Belt $100 2
John 07-15-2016 Tool Belt $100 2
Sara 07-15-2016 Hammer $100 3
</code></pre>
<p>test.py</p>
<pre><code>with open("sample.csv") as inputs:
mydict = dict()
for line in inputs:
el... | 0 | 2016-07-15T19:46:23Z | [
"python",
"django",
"counter"
] |
How to pass Variable from Python to VBA Sub | 38,403,790 | <p>I am trying to call a VBA sub from my Python code to convert all excel files in a specified folder from the xls to xlsm format.</p>
<p>I can use the following code when I am not using a variable in the VBA and it works well.</p>
<p><strong>Python Code:</strong></p>
<pre><code>import os
import win32com.client
xl=... | 1 | 2016-07-15T19:29:23Z | 38,403,831 | <p>Go to Macro Security under the developer tag and choose the Enable all macros option </p>
| 0 | 2016-07-15T19:32:41Z | [
"python",
"excel",
"vba",
"excel-vba"
] |
How to pass Variable from Python to VBA Sub | 38,403,790 | <p>I am trying to call a VBA sub from my Python code to convert all excel files in a specified folder from the xls to xlsm format.</p>
<p>I can use the following code when I am not using a variable in the VBA and it works well.</p>
<p><strong>Python Code:</strong></p>
<pre><code>import os
import win32com.client
xl=... | 1 | 2016-07-15T19:29:23Z | 38,405,493 | <p>Per Tim Williams suggestion I read the last section of rondebruin.nl/win/s9/win001.htm and formulated the python code</p>
<pre><code> import os
import win32com.client
Datev = """16.06 """
xl=win32com.client.Dispatch("Excel.Application")
xl.Workbooks.Open(Filename="C:\Users\Name\Documents\PERSONA... | 0 | 2016-07-15T21:51:39Z | [
"python",
"excel",
"vba",
"excel-vba"
] |
Python metaclass conflict/Type error | 38,403,795 | <p>I'm debugging a python script (python isn't my go to language), and this is the first time I'm working with metaclass's in python. I'm getting a metaclass conflict error when I run the code as it is below.</p>
<pre><code>TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a de... | 0 | 2016-07-15T19:29:53Z | 38,404,006 | <p>The problem is that when selecting a metaclass, python picks the most inherited version. However, you have two conflicting metaclasses in play (<code>ABCMeta</code> and whatever <code>MSoftware</code> has).</p>
<p>I think that the <a href="https://docs.python.org/3.5/reference/datamodel.html#determining-the-approp... | 2 | 2016-07-15T19:44:11Z | [
"python",
"python-2.7"
] |
Python metaclass conflict/Type error | 38,403,795 | <p>I'm debugging a python script (python isn't my go to language), and this is the first time I'm working with metaclass's in python. I'm getting a metaclass conflict error when I run the code as it is below.</p>
<pre><code>TypeError: Error when calling the metaclass bases
metaclass conflict: the metaclass of a de... | 0 | 2016-07-15T19:29:53Z | 38,407,284 | <p>The issue has to do with your imports, and confusion between identically named classes and modules. The <code>MSoftware</code> you're importing in <code>MySQLMSoftware.py</code> is the module implemented in <code>MSoftware.py</code>, not the class of the same name within that module. To get the latter (without chang... | 1 | 2016-07-16T03:00:32Z | [
"python",
"python-2.7"
] |
Query in pandas for closest object (in time) which meets a set of conditions | 38,403,939 | <p>I am using Pandas to manage a set of files which have several properties:</p>
<pre><code>import pandas as pd
data = {'Objtype' : ['bias', 'bias', 'flat', 'flat', 'StdStar', 'flat', 'Arc', 'Target1', 'Arc', 'Flat', 'Flat', 'Flat', 'bias', 'bias'],
'UT' : pd.date_range("11:00", "12:05", freq="5min... | 2 | 2016-07-15T19:39:18Z | 38,405,651 | <p>Let's build a function</p>
<pre><code>def get_closest(df, idx, bool_cond, to_this):
others = df.loc[bool_cond, to_this]
target = df.loc[idx, to_this]
return df.ix[(others - target).abs().idxmin()]
</code></pre>
<p>First, assume when you are looking for somethihg closest to something else that we have a... | 2 | 2016-07-15T22:08:53Z | [
"python",
"datetime",
"numpy",
"pandas"
] |
Sklearn - How to predict probability for all target labels | 38,403,951 | <p>I have a data set with a target variable that can have 7 different labels. Each sample in my training set has only one label for the target variable. </p>
<p>For each sample, I want to calculate the probability for each of the target labels. So my prediction would consist of 7 probabilities for each row.</p>
<p>On... | 0 | 2016-07-15T19:40:19Z | 38,409,496 | <p>You can do that by simply removing the <code>OneVsRestClassifer</code> and using <a href="http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html#sklearn.tree.DecisionTreeClassifier.predict_proba" rel="nofollow"><code>predict_proba</code></a> method of the <a href="http://scikit-lea... | 1 | 2016-07-16T09:05:00Z | [
"python",
"scikit-learn",
"multilabel-classification"
] |
Sklearn - How to predict probability for all target labels | 38,403,951 | <p>I have a data set with a target variable that can have 7 different labels. Each sample in my training set has only one label for the target variable. </p>
<p>For each sample, I want to calculate the probability for each of the target labels. So my prediction would consist of 7 probabilities for each row.</p>
<p>On... | 0 | 2016-07-15T19:40:19Z | 38,413,714 | <p>You can try using <a href="http://scikit.ml" rel="nofollow">scikit-multilearn</a> - an extension of sklearn that handles multilabel classification. If your labels are not overly correlated you can train one classifier per label and get all predictions - try (after <em>pip install scikit-multilearn</em>):</p>
<pre><... | 1 | 2016-07-16T17:23:44Z | [
"python",
"scikit-learn",
"multilabel-classification"
] |
How to use the return value of the first task in the second task's group for loop? | 38,403,999 | <p>I have two celery tasks:</p>
<pre><code>@app.task
def task1(a, b, c, d):
# do some stuff and find the return value
return r
@app.task
def task2(a, b, c, d, e, f, g):
# do some other stuff
</code></pre>
<p>I want to first execute task1 and then execute a list of task2 in parallel:</p>
<pre><code>c = ch... | -1 | 2016-07-15T19:43:34Z | 38,405,656 | <p>You may specify a base for your first task and have it call the second task with the retVal of the first. You can do this in the on_success method of your base.</p>
<pre><code>import Task from Celery
def setVal():
return 1, 2, 3
class FollowUp(Task):
def on_success(self, retval, task_id, *args, **kwargs):... | 0 | 2016-07-15T22:09:27Z | [
"python",
"celery",
"chain"
] |
Pygit2: Why does merge leave branch in an unclean state? | 38,404,020 | <p>I'm currently running Pygit 0.24.1 (along with libgit 0.24.1), working on a repository where I have two branches (say <code>prod</code> and <code>dev</code>).</p>
<p>Every change is first commited to the <code>dev</code> branch and pushed to the remote repository. To do that, I have this piece of code:</p>
<pre><c... | 4 | 2016-07-15T19:45:11Z | 38,442,759 | <p>I would explain the observed problem as follows:</p>
<pre><code>head_commit = repo.head
# This resets the index and the working tree to the old state
# and records that we are in a state corresponding to the commit
# pointed to by refs/heads/prod
repo.checkout('refs/heads/prod')
prod_branch_tip = repo.lookup_refe... | 3 | 2016-07-18T17:32:29Z | [
"python",
"git",
"python-2.7",
"libgit2",
"pygit2"
] |
Filling NumPy array with object instances? | 38,404,079 | <p>I am trying to add object instances of <code>astropy</code> <code>Angles</code> to a <code>NumPy</code> array , and am getting an error:</p>
<p><code>ValueError: setting an array element with a sequence.</code></p>
<p>the <code>Angle</code> objects look something like this:</p>
<p><code><Angle 1.2557346257567 ... | 0 | 2016-07-15T19:49:39Z | 38,404,362 | <p>I don't have <code>astrop</code> package and don't know the details of the <code>Angle</code> object. But I can make some Python and numpy observations.</p>
<p><code><Angle 1.2557346257567 deg></code> is the string representation of this object, produced by its <code>__repr__</code> method.</p>
<p>The TypeE... | 2 | 2016-07-15T20:10:43Z | [
"python",
"object",
"numpy",
"sequence",
"astropy"
] |
Filling NumPy array with object instances? | 38,404,079 | <p>I am trying to add object instances of <code>astropy</code> <code>Angles</code> to a <code>NumPy</code> array , and am getting an error:</p>
<p><code>ValueError: setting an array element with a sequence.</code></p>
<p>the <code>Angle</code> objects look something like this:</p>
<p><code><Angle 1.2557346257567 ... | 0 | 2016-07-15T19:49:39Z | 38,404,372 | <p>You can set the <code>dtype</code> of the array to <code>object</code>, a trivial example being</p>
<pre><code>import numpy as np
from astropy.coordinates import Angle
a, b, c = Angle('1.2562500714928306d'), Angle('1.2562500714928306d'), Angle('1.2562500714928306d')
s = np.array([a, b, c], dtype=object)
</code></pr... | 0 | 2016-07-15T20:11:36Z | [
"python",
"object",
"numpy",
"sequence",
"astropy"
] |
Filling NumPy array with object instances? | 38,404,079 | <p>I am trying to add object instances of <code>astropy</code> <code>Angles</code> to a <code>NumPy</code> array , and am getting an error:</p>
<p><code>ValueError: setting an array element with a sequence.</code></p>
<p>the <code>Angle</code> objects look something like this:</p>
<p><code><Angle 1.2557346257567 ... | 0 | 2016-07-15T19:49:39Z | 38,406,593 | <p>Don't create a list or array of <code>Angle</code> objects.<br>
Instead, view <code>Angle</code> (and similar astropy classes) as a container object that adds a unit, and initialize it with a list or array.</p>
<p>For example:</p>
<pre><code>>>> from astropy.coordinates import Angle
>>> from astr... | 4 | 2016-07-16T00:28:31Z | [
"python",
"object",
"numpy",
"sequence",
"astropy"
] |
Python Sphinx/rest substitution for long names defining substitution rule in same source file | 38,404,147 | <p>Post <a href="http://stackoverflow.com/questions/10034303/python-sphinx-referencing-long-names">Python Sphinx referencing long names</a> provided one answer that was very close to what I was looking for with regards to substitution directives for long class names.</p>
<pre><code>def exampleFunction():
'''Here i... | 1 | 2016-07-15T19:54:50Z | 38,404,422 | <p>You can do that with the variable <code>rst_epilog</code> in your <code>conf.py</code> file. This is taken straight from <a href="http://www.sphinx-doc.org/en/stable/config.html#confval-rst_epilog" rel="nofollow">rst_epilog</a>:</p>
<blockquote>
<p>rst_epilog</p>
<p>A string of reStructuredText that will be ... | 0 | 2016-07-15T20:15:38Z | [
"python",
"python-sphinx",
"substitution"
] |
Is None really a built-in? | 38,404,151 | <p>I am trying to use Python's (2.7) <code>eval</code> in a (relatively) safe manner. Hence, I defined:</p>
<pre><code>def safer_eval(string):
"""Safer version of eval() as globals and builtins are inaccessible"""
return eval(string, {'__builtins__': {}})
</code></pre>
<p>As expected, the following does not w... | 2 | 2016-07-15T19:55:09Z | 38,404,267 | <p>In Python 2.7, this is a perfectly valid statement.</p>
<pre><code>True = False
>>> print True
False
</code></pre>
<p>Try to do it with <code>None</code> though, and..</p>
<p><code>SyntaxError: cannot assign to None</code></p>
<p>Can kind of make your head spin. I'm not sure, but I suspect that <code>Tr... | 0 | 2016-07-15T20:02:40Z | [
"python",
"built-in",
"nonetype"
] |
Is None really a built-in? | 38,404,151 | <p>I am trying to use Python's (2.7) <code>eval</code> in a (relatively) safe manner. Hence, I defined:</p>
<pre><code>def safer_eval(string):
"""Safer version of eval() as globals and builtins are inaccessible"""
return eval(string, {'__builtins__': {}})
</code></pre>
<p>As expected, the following does not w... | 2 | 2016-07-15T19:55:09Z | 38,404,298 | <p><code>None</code> is a <em>constant</em> in Python, see the <a href="https://docs.python.org/2/reference/lexical_analysis.html#keywords" rel="nofollow"><em>Keywords</em> documentation</a>:</p>
<blockquote>
<p>Changed in version 2.4: <code>None</code> became a constant and is now recognized by the compiler as a na... | 9 | 2016-07-15T20:05:12Z | [
"python",
"built-in",
"nonetype"
] |
Summing Groups of Columns within a Pandas Dataframe | 38,404,247 | <p>I have a pandas dataframe with 600 columns (df1), and I want to sum the values of each column in groups of 6. In other words, I want to create a new dataframe (df2) that has 100 columns, each column being the sum of 6 columns from the input dataframe. For example, Each row the first column in df2 will be the sum of ... | 1 | 2016-07-15T20:00:56Z | 38,404,341 | <p>You can <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.groupby.html" rel="nofollow"><code>groupby</code></a> by columns (<code>axis=1</code>) with groups created by <code>df.columns //6</code> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.core.groupby.Grou... | 1 | 2016-07-15T20:08:49Z | [
"python",
"pandas",
"dataframe",
"sum"
] |
Python - Multiprocessing Pool Class: Can the Thread Function contain arguments? | 38,404,320 | <p>I want to know if it is possible to pass arguments into the threading pool funktion?</p>
<pre><code>from multiprocessing.dummy import Pool as ThreadPool
def mainFunc():
myArray = ["A", "B", "C"]
pool = ThreadPool(8)
pool.map(threadFunc, myArray) # how is it possible to give >>threadFunc<&... | 0 | 2016-07-15T20:06:37Z | 38,404,357 | <ol>
<li><p>The official python docs says</p>
<blockquote>
<p>A parallel equivalent of the map() built-in function (it supports only one iterable argument though). It blocks until the result is ready.</p>
</blockquote>
<p>Therefore it is impossible to add another argument, but you can always add text1 as the last e... | 2 | 2016-07-15T20:09:59Z | [
"python",
"multithreading",
"multiprocessing",
"pool"
] |
Python - Multiprocessing Pool Class: Can the Thread Function contain arguments? | 38,404,320 | <p>I want to know if it is possible to pass arguments into the threading pool funktion?</p>
<pre><code>from multiprocessing.dummy import Pool as ThreadPool
def mainFunc():
myArray = ["A", "B", "C"]
pool = ThreadPool(8)
pool.map(threadFunc, myArray) # how is it possible to give >>threadFunc<&... | 0 | 2016-07-15T20:06:37Z | 38,410,625 | <p>You can pass as many arguments as you want in a tuple or a list:</p>
<pre><code>from multiprocessing.dummy import Pool as ThreadPool
def mainFunc():
myArray = ["A", "B", "C"]
text1 = "Hello "
pool = ThreadPool(8)
# combine text1 with each element in myArray
args_generator = ((text1, x) for x... | 0 | 2016-07-16T11:16:01Z | [
"python",
"multithreading",
"multiprocessing",
"pool"
] |
Efficiently compute historical aggregates | 38,404,359 | <p>I have a dataframe containing historical records, for example sales.</p>
<pre><code>import pandas as pd
first_salesman = pd.Series([1, 2, 3], index=[pd.to_datetime('2015-01-01'), pd.to_datetime('2015-01-02'), pd.to_datetime('2015-01-03')])
second_salesman = pd.Series([2, 0, 5], index=[pd.to_datetime('2015-01-01'),... | 2 | 2016-07-15T20:10:11Z | 38,406,260 | <p>After some tinkering, I found the solution. In Pandas >= 0.18, you can use df.expanding(). See <a href="http://pandas.pydata.org/pandas-docs/stable/computation.html" rel="nofollow">documentation</a>.</p>
<p>A clean solution to this scenario is this one-liner:</p>
<pre><code>df.set_index(['Salesman_id', 'Date']).ex... | 0 | 2016-07-15T23:26:53Z | [
"python",
"pandas"
] |
2 Sample KS test - something seems wrong | 38,404,398 | <p>I am attempting to run a Kolmogorov-Smirnoff test using the ks_2samp function from scipy to determine if histograms of data are from the same distribution. The returned p-value doesn't seem quite right sometimes though...</p>
<p>For example with this histogram: </p>
<p><img src="http://i.stack.imgur.com/2j2ug.jpg"... | 1 | 2016-07-15T20:13:07Z | 38,405,469 | <p><code>ks_2samp</code> applies the Kolmogorov-Smirnov test to two samples and tests the null hypothesis that both come from the same distribution.</p>
<p>Therefore <code>ks_2samp</code> also takes the two samples (here <code>list1</code> and <code>list2</code>) as input.</p>
<pre><code>ks_2samp(list1, list2)
</code... | 3 | 2016-07-15T21:49:34Z | [
"python",
"scipy",
"statistics",
"kolmogorov-smirnov"
] |
Writing Output of Python Program to .txt File | 38,404,505 | <p>I've written a program that reads a CSV file and outputs the contents as insert statements. I then wrote an execute program that <em>should</em> take the output of the CSV parser program and write it to a .txt file but instead of writing the entire output it only writes the first statement. </p>
<p>Here is the code... | -2 | 2016-07-15T20:22:01Z | 38,404,565 | <p>Not sure if this would work for you but you can use the >/>> operator to have stdout be re-routed to a file.</p>
<p><strong>Edit: The difference between > and >> is that >> appends to the end of the file while > truncates the file</strong></p>
<pre><code>$python program.py >> output.txt
</code></pre>
<p>To ... | 0 | 2016-07-15T20:29:03Z | [
"python",
"file",
"python-3.x",
"csv",
"parsing"
] |
Writing Output of Python Program to .txt File | 38,404,505 | <p>I've written a program that reads a CSV file and outputs the contents as insert statements. I then wrote an execute program that <em>should</em> take the output of the CSV parser program and write it to a .txt file but instead of writing the entire output it only writes the first statement. </p>
<p>Here is the code... | -2 | 2016-07-15T20:22:01Z | 38,404,748 | <p>You are making things more complicated than they need to be. Just nest your open statements using <strong>with</strong>. One program. And it prints to the screen and writes to a file.</p>
<pre><code>import csv, os
path = 'C:/Users/user/Desktop/test/'
for file in os.listdir(path):
if file.endswith('.csv'):
... | 0 | 2016-07-15T20:43:25Z | [
"python",
"file",
"python-3.x",
"csv",
"parsing"
] |
Python : Most efficient way to get list of combinations? | 38,404,580 | <p>I have a dictionary : </p>
<pre><code>diff_params = {0: [a, b],
1: [c, d]}
</code></pre>
<p>Each key is a setting_name, and each value is a specific setting. I would like to be able to make a list like:</p>
<pre><code>[[a, c],
[a, d],
[b, c],
[b, d]]
</code></pre>
<p>I can't figure out how t... | -2 | 2016-07-15T20:30:10Z | 38,404,665 | <p>It seems that you are more specifically looking for <a href="https://docs.python.org/3/library/itertools.html#itertools.product" rel="nofollow"><code>itertools.product()</code></a> which can be used like this with <a href="https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists" rel="nofollow">u... | 3 | 2016-07-15T20:36:57Z | [
"python",
"combinations",
"permutation",
"itertools"
] |
Move popup window | 38,404,585 | <p>The popup Image window blocks the stop button and other buttons in windows application. How do I move the window in Squish? I tried to move the window using the following script. Squish is not recognizing the popup window. </p>
<pre><code>win = waitForObject(":_Image0")
mousePress(win.x, win.y - 10, MouseButton.Le... | 0 | 2016-07-15T20:30:59Z | 38,437,248 | <p>You could try using the <a href="http://doc.froglogic.com/squish/6.0/rgs-windowsobjectapi.html#win-mouseDrag-function" rel="nofollow"><code>mouseDrag()</code></a> function, e.g.</p>
<pre><code>mouseDrag(win, 100, 0)
</code></pre>
<p>In the upcoming Squish 6.1 release, there's also a <a href="http://doc.froglogic.c... | 0 | 2016-07-18T12:54:09Z | [
"python",
"squish"
] |
Why is a part of my Python code interpreted diffently when I add a seemingly unrelated part? | 38,404,605 | <p>Some background: I'm implementing a GUI to interact with equipment via GPIB. The issue arises in this method:</p>
<pre><code>from tkinter import *
from tkinter import ttk
import visa #PyVisa Package. pyvisa.readthedocs.io
from time import sleep
import numpy as np #NumPy Package. Scipy.org
def oneDSweep():
Voltage ... | 0 | 2016-07-15T20:32:36Z | 38,404,695 | <p>Python is telling you exactly what is wrong with your code -- a <code>ValueError</code>. It even gives you the exact line number and the value that is causing the problem.</p>
<pre><code>'#3006 00.003'
</code></pre>
<p>That is the value of <code>SNOW</code> that is being printed out. Then you do this</p>
<pre><... | 2 | 2016-07-15T20:39:36Z | [
"python",
"interpreter",
"visa",
"gpib"
] |
Why is a part of my Python code interpreted diffently when I add a seemingly unrelated part? | 38,404,605 | <p>Some background: I'm implementing a GUI to interact with equipment via GPIB. The issue arises in this method:</p>
<pre><code>from tkinter import *
from tkinter import ttk
import visa #PyVisa Package. pyvisa.readthedocs.io
from time import sleep
import numpy as np #NumPy Package. Scipy.org
def oneDSweep():
Voltage ... | 0 | 2016-07-15T20:32:36Z | 38,405,028 | <blockquote>
<p>I am convinced that Python's interpreter is at fault here. Earlier, I was cleaning up my code and discovered that one particular set of quotes, when changed from ' to ", produced this same error, despite no other quote pair exhibiting this behavior, even within the same line.</p>
</blockquote>
<p>Pyt... | 2 | 2016-07-15T21:07:08Z | [
"python",
"interpreter",
"visa",
"gpib"
] |
how to import module only once in python behave step files | 38,404,617 | <p>I am very new to Python and Behave. In my step file, <code>test_steps.py</code>, I have imported the following: </p>
<pre><code>from behave import given, when, then, step
from behave_http.steps import *
from datetime import datetime
import time
import pdb
import xmltodict
import requests
</code></pre>
<p>If I crea... | 0 | 2016-07-15T20:33:19Z | 38,405,434 | <p>It's generally useful to know all the imports for a given file; however, you can do something like the following:</p>
<p>config.py</p>
<pre><code>from behave import given, when, then, step
from behave_http.steps import *
from datetime import datetime
import time
import pdb
import xmltodict
import requests
</code><... | 0 | 2016-07-15T21:46:41Z | [
"python",
"import",
"python-behave"
] |
Reading YAML config file in python and using variables | 38,404,633 | <p>Say I have a yaml config file such as:</p>
<pre><code>test1:
minVolt: -1
maxVolt: 1
test2:
curr: 5
volt: 5
</code></pre>
<p>I can read the file into python using:</p>
<pre><code>import yaml
with open("config.yaml", "r") as f:
config = yaml.load(f)
</code></pre>
<p>Then I can access the varia... | -1 | 2016-07-15T20:34:45Z | 38,409,774 | <p>You can do this:</p>
<pre><code>class Test1Class:
def __init__(self, raw):
self.minVolt = raw['minVolt']
self.maxVolt = raw['maxVolt']
class Test2Class:
def __init__(self, raw):
self.curr = raw['curr']
self.volt = raw['volt']
class Config:
def __init__(self, raw):
... | 0 | 2016-07-16T09:40:03Z | [
"python",
"yaml",
"config"
] |
Wrong posts sequence at home page [Django app] | 38,404,646 | <p>At my home-page I've got exhibited all posts on my blog, but they're sorted incorrectly, from the oldest post to newest(it has to be reversed).
I use querysets to sort posts order by published date in my views.py</p>
<pre><code>def home(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).or... | 0 | 2016-07-15T20:35:43Z | 38,404,729 | <p>You want to add a <code>-</code> to the string argument in <a href="https://docs.djangoproject.com/en/1.9/ref/models/querysets/#django.db.models.query.QuerySet.order_by" rel="nofollow">order_by</a> this will cause your queryset to be in descending order.</p>
<pre><code>def home(request):
posts = Post.objects.fil... | 0 | 2016-07-15T20:42:22Z | [
"python",
"django",
"django-queryset"
] |
How to convert Panda's columns into an index and a header when index column has duplicates | 38,404,669 | <p>Iâd like to convert a dataframe, df, similar to this one:</p>
<pre><code>PIDM | COURSE | GRADE
1 | MAT1 | B
1 | PHY2 | C
2 | MAT1 | A
2 | MAT2 | B
2 | PHE2 | A
</code></... | 0 | 2016-07-15T20:37:23Z | 38,404,709 | <p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.pivot_table.html" rel="nofollow"><code>pivot_table</code></a> with aggregate function <code>join</code>:</p>
<pre><code>df2 = df.pivot_table(index='PIDM', columns='COURSE', values = 'GRADE', aggfunc=', '.join)
print (df2)
COURSE MAT1 ... | 1 | 2016-07-15T20:40:28Z | [
"python",
"pandas",
"pivot"
] |
Obtaining widget values in tkinter | 38,404,686 | <p>How do I refer to the widget values in the following code.Here I have added widgets by calling methods in the app class for different frames.Next,I want to access the values in all the Widgets(which the user enters) of all the frames at the same time.But I am not able to figure out how should I refer to them and acc... | 0 | 2016-07-15T20:38:39Z | 38,409,232 | <p>The widgets in which the user can write have a <code>get</code> method that returns their content. But in order to do this, you need to store your widget in a class variable for example.</p>
<p><strong>Edit</strong>: I had misunderstood the problem and I hadn't realized that the <code>add_widget</code> function wou... | 1 | 2016-07-16T08:16:18Z | [
"python",
"tkinter"
] |
How to call functions in python files that are not in the working directory? | 38,404,707 | <p>Say now my working folder is <code>.</code> and my supporting python files are in <code>./supporting_files/</code>, I want to call a function <code>func</code> in the <code>a.py</code> file under <code>./supporting_files/</code>, what should I do? I tried calling <code>from supporting_files.a import func</code> and ... | 2 | 2016-07-15T20:40:26Z | 38,404,790 | <p>Add an <code>__init__.py</code> file (it can be empty) to the <code>supporting_files</code> directory, and python will treat it as a package available for imports. More details are available in the <a href="https://docs.python.org/3/tutorial/modules.html#packages" rel="nofollow">Python documentation</a>.</p>
| 1 | 2016-07-15T20:47:37Z | [
"python"
] |
How to call functions in python files that are not in the working directory? | 38,404,707 | <p>Say now my working folder is <code>.</code> and my supporting python files are in <code>./supporting_files/</code>, I want to call a function <code>func</code> in the <code>a.py</code> file under <code>./supporting_files/</code>, what should I do? I tried calling <code>from supporting_files.a import func</code> and ... | 2 | 2016-07-15T20:40:26Z | 38,404,858 | <p>There are two ways you can do that I'm aware of.</p>
<h1>Wrong way</h1>
<pre><code>import sys
sys.path.append('./supporting_files')
from a import func
func()
</code></pre>
<h1>Right way</h1>
<pre><code>$ touch supporting_files/__init__.py
</code></pre>
<p>Then</p>
<pre><code>import supporting_files.a as a
... | 3 | 2016-07-15T20:54:09Z | [
"python"
] |
multiprocessing module and distinct psycopg2 connections | 38,404,773 | <p>I am very puzzled as to the behavior of some multiprocessing code that is using <em>psycopg2</em> to make queries in parallel to a postgres db.</p>
<p>Essentially, I am making the same query (with different params) to various partitions of a larger table. I am using multiprocessing.Pool to fork off a separate query... | 0 | 2016-07-15T20:46:06Z | 38,407,361 | <p>I think I've figured this out. The answer lies in the fact that multiprocessing in Python is shared-nothing so the entire memory space is copied, functions and all. Hence for each process, even though the pid is different, the memory spaces are copies of each other and the address of the connection within the memory... | 1 | 2016-07-16T03:17:05Z | [
"python",
"postgresql",
"psycopg2"
] |
Numpy using smaller 2D array to map with bigger array with more elements | 38,404,793 | <p>I have a smaller array as:</p>
<pre><code>A = np.array([2011, 2014, 2015, 2016, 2017])
Aval = np.array([14, 10, 35, 40, 45])
</code></pre>
<p>I have another array:</p>
<pre><code>A2 = np.array([2013, 2014, 2015, 2014, 2015, 2016, 2016, 2016, 2017])
</code></pre>
<p>I want to create A2val such that:</p>
<pre><co... | 1 | 2016-07-15T20:48:19Z | 38,404,864 | <p>You can construct a dictionary from <code>A</code> and <code>Aval</code> and then loop through <code>A2</code> and find out the corresponding values:</p>
<pre><code>dic = dict(zip(A, Aval))
[dic.get(a) for a in A2 if dic.get(a) != None]
# [10, 35, 10, 35, 40, 40, 40, 45]
</code></pre>
| 1 | 2016-07-15T20:54:56Z | [
"python",
"numpy"
] |
Numpy using smaller 2D array to map with bigger array with more elements | 38,404,793 | <p>I have a smaller array as:</p>
<pre><code>A = np.array([2011, 2014, 2015, 2016, 2017])
Aval = np.array([14, 10, 35, 40, 45])
</code></pre>
<p>I have another array:</p>
<pre><code>A2 = np.array([2013, 2014, 2015, 2014, 2015, 2016, 2016, 2016, 2017])
</code></pre>
<p>I want to create A2val such that:</p>
<pre><co... | 1 | 2016-07-15T20:48:19Z | 38,404,995 | <p>Here is one way:</p>
<pre><code>>>> Aval[np.searchsorted(A, A2[np.nonzero(np.in1d(A2, A))[0]])]
array([10, 35, 10, 35, 40, 40, 40, 45])
</code></pre>
<p>Note that for getting the expected indices in default order the second array that you pass to <code>searchsorted()</code> should be contain the common it... | 4 | 2016-07-15T21:04:34Z | [
"python",
"numpy"
] |
cx_Freeze doesn't print to console | 38,404,800 | <p>I have an application that prints a few things to the console upon running. But as a standalone the executable doesn't print anything to the console?</p>
<p>The setup.py script looks like this:</p>
<pre><code>import sys
from cx_Freeze import setup, Executable
setup(
name = "My App",
version = "1.0",
o... | 0 | 2016-07-15T20:48:44Z | 38,412,650 | <p>If you use the "Win32GUI" base, then Windows does not make available stdout and stderr. You will need to redirect those yourself to some other location (such as a file). If you use the "Console" base then stdout and stderr are available and print() will work as expected -- but you will see a console created for you ... | 1 | 2016-07-16T15:33:11Z | [
"python",
"python-3.x",
"cx-freeze"
] |
Safest way to remove argument order and provide default values at the same time in Python | 38,404,819 | <p>I am trying to write Python 2.7 cod that is easier to scale by removing argument order while providing default values in the case that requirements change. Here is my code:</p>
<pre><code># Class:
class Mailer(object):
def __init__(self, **args):
self.subject=args.get('subject', None)
self.maili... | 0 | 2016-07-15T20:50:34Z | 38,404,927 | <p>Try this way of initialize your class:</p>
<pre><code>class Mailer(object):
def __init__(self, **args):
for k in args:
self.__dict__[k] = args[k]
</code></pre>
| 0 | 2016-07-15T20:59:26Z | [
"python",
"python-2.7",
"parameter-passing",
"default-value",
"kwargs"
] |
Safest way to remove argument order and provide default values at the same time in Python | 38,404,819 | <p>I am trying to write Python 2.7 cod that is easier to scale by removing argument order while providing default values in the case that requirements change. Here is my code:</p>
<pre><code># Class:
class Mailer(object):
def __init__(self, **args):
self.subject=args.get('subject', None)
self.maili... | 0 | 2016-07-15T20:50:34Z | 38,404,967 | <p>The problem with the way you're doing it is that there is no documentation about what arguments the class accepts, so <code>help(Mailer)</code> is useless. What you should do is provide default argument values in the <code>__init__()</code> method where possible. </p>
<p>To set the arguments as attributes on the in... | 0 | 2016-07-15T21:02:06Z | [
"python",
"python-2.7",
"parameter-passing",
"default-value",
"kwargs"
] |
Python: ' ' is not defined | 38,404,825 | <p>Here is my code:</p>
<pre><code># This program makes the robot calculate the average amount of light in a simulated room
from myro import *
init("simulator")
from random import*
def pressC():
""" Wait for "c" to be entered from the keyboard in the Python shell """
entry = " "
while(entry != "c"):
... | 0 | 2016-07-15T20:51:32Z | 38,405,406 | <p>If you want to return multiple items from <code>scan()</code>, don't use three separate <code>return</code> statements. Instead, do this:</p>
<pre><code>return leftLightSeries, centerLightSeries, rightLightSeries
</code></pre>
<p>Also, when you call the function, you have to assign variable(s) to the returned val... | 0 | 2016-07-15T21:43:14Z | [
"python",
"nameerror"
] |
Avoid writing carriage return when writing line feed with Python | 38,404,827 | <p>If taken into consideration that <code>carriage return = \r</code> and <code>line feed = \n</code></p>
<pre><code>Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> '{:02x}'.format(ord('\n... | 0 | 2016-07-15T20:51:47Z | 38,420,824 | <p>You can do this by passing <code>''</code> to the <code>newline</code> parameter when opening the text file.</p>
<pre><code>f = open('test.txt', 'w', newline='')
f.write('Only LF\n')
f.write('CR + LF\r\n')
f.write('Only CR\r')
f.write('Nothing')
f.close()
</code></pre>
<p>As described in the <a href="https://docs.... | 2 | 2016-07-17T11:44:00Z | [
"python",
"carriage-return",
"linefeed"
] |
Slider with max value greater than 2147483647 in wxPython Phoenix? | 38,404,850 | <p>Basically, the <code>wx.Slider</code> widget from wxPython Phoenix cannot go further than <code>2147483647</code>. </p>
<p>Indeed, </p>
<pre><code>slider = wx.Slider( parent = parent,\
value = 10,\
minValue = 0,\
maxValue = 2147483647 )
print slide... | 0 | 2016-07-15T20:53:24Z | 38,404,999 | <p>I assume it's a 32 bit machine? <br>
2147483647 (or 2^31-1 (since we're counting from 0)) is the biggest integer a 32 bit machine can handle</p>
| 0 | 2016-07-15T21:04:48Z | [
"python",
"slider",
"wxpython",
"limit",
"value"
] |
Slider with max value greater than 2147483647 in wxPython Phoenix? | 38,404,850 | <p>Basically, the <code>wx.Slider</code> widget from wxPython Phoenix cannot go further than <code>2147483647</code>. </p>
<p>Indeed, </p>
<pre><code>slider = wx.Slider( parent = parent,\
value = 10,\
minValue = 0,\
maxValue = 2147483647 )
print slide... | 0 | 2016-07-15T20:53:24Z | 38,409,032 | <p>Have you considered just dividing your values by an appropriate divisor.</p>
<p>Edit:<br>
There are times when you simply have to be pragmatic. You cannot possibly display or use a slider with a length of 2 billion. Whether it is automatically generated or not, it is simpler to make the slider utilise values betwee... | 1 | 2016-07-16T07:48:21Z | [
"python",
"slider",
"wxpython",
"limit",
"value"
] |
Implement classes Square and Triangle as subclasses of class Polygon | 38,404,881 | <p>It will overload the constructor method init so it only takes one argument(side length) and will override method area that computes the area. I came up with this program, but it keeps saying "undefined name Polygon".</p>
<pre><code>class Square(Polygon):
'square class'
def __init__(self, s):
'const... | -1 | 2016-07-15T20:55:53Z | 38,405,105 | <p>If you want to inherit from <code>Polygon</code>, you have to define it before you define the other classes that inherit from it.</p>
<pre><code>class Polygon:
def __init__(self):
pass
def area(self):
raise NotImplemented
class Square(Polygon):
'square class'
def __init__(self, s):... | 0 | 2016-07-15T21:13:32Z | [
"python"
] |
Google's Python Course wordcount.py | 38,404,890 | <p>I am taking Google's Python Course, which uses Python 2.7. I am running 3.5.2. </p>
<p>The script functions. This was one of my exercises. </p>
<pre><code>#!/usr/bin/python -tt
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Pyt... | -1 | 2016-07-15T20:56:24Z | 38,405,538 | <ol>
<li><p>If <code>word</code> is not already in the dictionary, we create a new entry in the dictionary for it, and set the value to the number <code>1</code>, since we've so far just found 1 occurrence of the word. Otherwise, we retrieve the old value from the dictionary, use <code>+ 1</code> to add 1 to that value... | 0 | 2016-07-15T21:55:47Z | [
"python"
] |
All list items change to appended item, in Python | 38,404,939 | <p>I am using Python 2.7, using only standard modules.</p>
<p>I have a huge data file that contains a bunch of information about car events. I am trying to copy the data about an individual car event type (e.g. Acceleration) and write it to separate file. My current approach stores the data in a table --I used lists w... | 0 | 2016-07-15T21:00:03Z | 38,431,544 | <p>List objects are passed by reference in Python. The reason the previously appended elements are mutating to the current row is because they all point to the same list, single_event.</p>
<p>A simple </p>
<pre><code>single_event = list(range(3))
</code></pre>
<p>after each append operation should solve your issue.<... | 1 | 2016-07-18T08:06:37Z | [
"python",
"list",
"file",
"object",
"datatable"
] |
Selecting only rows where one date is less than another with Pandas Dataframe | 38,405,015 | <p>I have a pandas dataframe with this data:</p>
<pre><code>Id Converteddate Createddate
0015000000toohpAAA 2015-07-24 00:00:00 2014-07-08 19:36:13
0015000000tqEpKAAU 2015-03-17 00:00:00 2014-07-16 00:28:06
00138000015me01AAA 2015-10-22 00:00:00 2015-10-22 22:04:55
00138000015me56AAA 2015-10... | 1 | 2016-07-15T21:06:03Z | 38,405,148 | <p>You can use for converting to <code>datetime</code> function <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html" rel="nofollow"><code>to_datetime</code></a> and then use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_timedelta.html" rel="nofollow"><code>t... | 1 | 2016-07-15T21:16:42Z | [
"python",
"python-2.7",
"datetime",
"pandas",
"dataframe"
] |
How to convert a scipy row matrix into a numpy array | 38,405,047 | <p>Consider the following example:</p>
<pre><code>import numpy as np
import scipy.sparse
A = scipy.sparse.csr_matrix((2,2))
b = A.sum(axis=0)
</code></pre>
<p>The matrix <code>b</code> now has the form</p>
<pre><code>matrix([[ 0., 0.]])
</code></pre>
<p>However, I'd like it to become an array like this:</p>
<pre... | 1 | 2016-07-15T21:08:03Z | 38,405,450 | <p>There are different options here. For example, you could start by converting matrix <code>b</code> to a 2D array. Then you'll need to transform it into a 1D array. This can be easily accomplished through NumPy's <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.squeeze.html" rel="nofollow"><code>squ... | 1 | 2016-07-15T21:48:03Z | [
"python",
"numpy",
"scipy"
] |
How to convert a scipy row matrix into a numpy array | 38,405,047 | <p>Consider the following example:</p>
<pre><code>import numpy as np
import scipy.sparse
A = scipy.sparse.csr_matrix((2,2))
b = A.sum(axis=0)
</code></pre>
<p>The matrix <code>b</code> now has the form</p>
<pre><code>matrix([[ 0., 0.]])
</code></pre>
<p>However, I'd like it to become an array like this:</p>
<pre... | 1 | 2016-07-15T21:08:03Z | 38,405,999 | <p><code>b.A1</code> will do the job.</p>
<pre><code>In [83]: A
Out[83]:
<2x2 sparse matrix of type '<class 'numpy.float64'>'
with 0 stored elements in Compressed Sparse Row format>
In [84]: A.A
Out[84]:
array([[ 0., 0.],
[ 0., 0.]])
In [85]: b=A.sum(axis=0)
In [86]: b
Out[86]: matrix([[ ... | 2 | 2016-07-15T22:47:18Z | [
"python",
"numpy",
"scipy"
] |
Python finding Prime Numbers between any two numbers | 38,405,065 | <p>I'm trying to find prime numbers between any two random numbers.</p>
<p>Firstly, I have written the code like:</p>
<pre><code>m,n = map(int, raw_input().split())
for i in range(m, n+1):
for j in range(2, i):
if i%j == 0:
break
else:
print i,
</code></pre>
<p>Now for test case s... | 1 | 2016-07-15T21:09:15Z | 38,405,172 | <p>Your inner loop used to loop up until <code>i-1</code> or <code>i/2</code>. This inner loop was short when <code>i</code> was small, and longer when <code>i</code> got larger.</p>
<p>Now, your inner loop goes up to <code>sqrt_num</code>, which is a constant computed from <code>n</code>. Difference in behavior.</p... | 2 | 2016-07-15T21:18:53Z | [
"python",
"primes",
"sieve-of-eratosthenes"
] |
Python finding Prime Numbers between any two numbers | 38,405,065 | <p>I'm trying to find prime numbers between any two random numbers.</p>
<p>Firstly, I have written the code like:</p>
<pre><code>m,n = map(int, raw_input().split())
for i in range(m, n+1):
for j in range(2, i):
if i%j == 0:
break
else:
print i,
</code></pre>
<p>Now for test case s... | 1 | 2016-07-15T21:09:15Z | 38,405,582 | <p>Also, I hope the position of your else is intentional, because that matters in Python: different results when directly under the if</p>
| -3 | 2016-07-15T22:02:06Z | [
"python",
"primes",
"sieve-of-eratosthenes"
] |
How are python module paths translated to filesystem paths? | 38,405,109 | <p>This may seem like a simple question, but I haven't found an answer that explains the behavior I'm seeing. Hard to provide a simple repro case but I basically have a package structure like this:</p>
<p><code>a.b.c</code>
<code>a.b.utils</code></p>
<p>I have one project that has files in <code>a.b.c.</code> (let's ... | 0 | 2016-07-15T21:13:57Z | 38,405,572 | <p>Ok, the problem was simply that the cwd is prepended to the PYTHONPATH. <code>sys.path.pop(1)</code> (0 is the tests dir, prepended by pytest) resolved the behavior.</p>
| 0 | 2016-07-15T22:00:59Z | [
"python",
"py.test",
"python-module"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.