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 |
|---|---|---|---|---|---|---|---|---|---|
python add an attribute to a method using decorators | 39,537,757 | <p>I'm trying to add an attribute to my method using decorators to determine if it has been called. I can't figure out why I got this error : TypeError: bet() missing 1 required positional argument: 'betsize'. </p>
<p>file game.py</p>
<pre><code>class Game(object):
def __init__(self):
..
@AddCalled
... | 0 | 2016-09-16T18:15:25Z | 39,537,941 | <p>Your decorator doesn't properly pass <code>self</code> to the wrapped function.</p>
<p>Normally, <code>self</code> is added by the descriptor mechanism of function objects, which converts them on the fly into method objects with the <code>self</code> rolled in. But you replaced your method with an AddDecorator obj... | 2 | 2016-09-16T18:26:54Z | [
"python",
"qt",
"class",
"decorator"
] |
python add an attribute to a method using decorators | 39,537,757 | <p>I'm trying to add an attribute to my method using decorators to determine if it has been called. I can't figure out why I got this error : TypeError: bet() missing 1 required positional argument: 'betsize'. </p>
<p>file game.py</p>
<pre><code>class Game(object):
def __init__(self):
..
@AddCalled
... | 0 | 2016-09-16T18:15:25Z | 39,538,000 | <p>When you write:</p>
<pre><code>@AddCalled
def bet(self, betsize):
print(betsize)
</code></pre>
<p>This is equivalent to:</p>
<pre><code>def bet(self, betsize):
print(betsize)
bet = AddCalled(bet)
</code></pre>
<p>So, the argument passed to <code>AddCalled</code> is the <code>bet</code> function.</p>
| -1 | 2016-09-16T18:29:43Z | [
"python",
"qt",
"class",
"decorator"
] |
Orthogonality issue in scipy's legendre polynomials | 39,537,794 | <p>I recently stumbled upon a curious issue concerning the <code>scipy.special.legendre()</code> (<a href="http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.legendre.html" rel="nofollow">scipy documentation</a>). The legendre polynomials should be pairwise orthogonal. However, when I calculate them over... | 2 | 2016-09-16T18:19:03Z | 39,541,581 | <p>As others have commented, you're going to get some error, since you're performing an in-exact integral.</p>
<p>But you can reduce the error by doing the integral as best you can. In your case, you can still improve your sampling points to make the integral more exact. When sampling, use the "midpoint" of the interv... | 0 | 2016-09-17T00:02:52Z | [
"python",
"scipy",
"polynomials",
"orthogonal"
] |
A more pythonic way of doing the following? | 39,537,837 | <p>A more pythonic way of doing the following? In this example, I'm trying to build comments (a dict) to be key-value pairs where the key is the unmodified-version, and the value is the return value from a function where the key was passed as an arg.</p>
<pre><code>def func(word):
return word[-1:-6:-1].upper()
su... | 0 | 2016-09-16T18:20:56Z | 39,537,912 | <p>Use a <a href="https://www.python.org/dev/peps/pep-0274/" rel="nofollow">dict comprehension</a> instead of building your dictionary in a <code>for</code> loop:</p>
<pre><code>comments = {key: func(key) for key in subs['ALLOWED']}
</code></pre>
| 4 | 2016-09-16T18:25:00Z | [
"python",
"python-3.x"
] |
A more pythonic way of doing the following? | 39,537,837 | <p>A more pythonic way of doing the following? In this example, I'm trying to build comments (a dict) to be key-value pairs where the key is the unmodified-version, and the value is the return value from a function where the key was passed as an arg.</p>
<pre><code>def func(word):
return word[-1:-6:-1].upper()
su... | 0 | 2016-09-16T18:20:56Z | 39,537,920 | <p>Remove the loop and replace it inside the function with a dictionary comprehension. Then, you can simply return it. </p>
<p>Also, you can reverse the string <code>word</code> with <code>[::-1]</code>, not the complex <code>[-1:-6:-1]</code> slice you're using:</p>
<pre><code>def func(words):
return {word: word... | 0 | 2016-09-16T18:25:32Z | [
"python",
"python-3.x"
] |
Python random.random - chance of rolling 0 | 39,537,843 | <p>As described in the <a href="https://docs.python.org/3.4/library/random.html#random.random" rel="nofollow">documentation</a>, random.random will "return the next random floating point number in the range [0.0, 1.0)"</p>
<p>So what is the chance of it returning a 0?</p>
| 3 | 2016-09-16T18:21:09Z | 39,537,894 | <p>As per the documentation, it </p>
<blockquote>
<p>It produces 53-bit precision </p>
</blockquote>
<p>And the Mersenne Twister it is based on has a huge state space, many times large than this. It also routinely passes statistical tests of bit independence (in programs designed to spot patterns in RNG output). Th... | 8 | 2016-09-16T18:24:02Z | [
"python",
"random"
] |
Python 3 + NTLM + Sharepoint | 39,537,888 | <p>I am attempting to create a tool for interfacing with Sharepoint to start transitioning a number of old processes away from using Sharepoint as a relational database and move that data into an actual database and automate several manual tasks among other things.</p>
<p>The environment I am working with is a Sharepo... | 0 | 2016-09-16T18:23:43Z | 39,622,563 | <p>Shareplum ended up working great, with some exceptions due to the way it imported some data. Here's some rough code I ended up using to test it and later expand, censored, but enough to get someone started if they stumble across this:</p>
<pre><code>from <<DATABASE LIBRARY>> import KEY,ORACLESQL
from re... | 0 | 2016-09-21T17:06:25Z | [
"python",
"sharepoint",
"sharepoint-2013",
"ntlm"
] |
Start infinite python script in new thread within Flask | 39,537,892 | <p>I'd like to start my never ending Python script from within Flask request:</p>
<pre><code>def start_process():
exec(open("./process/main.py").read(), globals())
print("Started")
return
</code></pre>
<p>and with the request:</p>
<pre><code>@app.route("/start")
def start():
from threading import T... | 0 | 2016-09-16T18:23:51Z | 39,563,991 | <p>I've not successfully started long-running thread from within Flask, but gone the other way, starting Flask in thread and providing it a way to communicate with other threads.</p>
<p>The trick is to something along the lines of</p>
<pre><code>def webserver(coordinator):
app.config['COORDINATOR'] = coordinator
... | 0 | 2016-09-19T00:51:19Z | [
"python",
"multithreading",
"flask",
"process",
"daemon"
] |
Update/Append to dictionary | 39,537,896 | <p>Let's say I have a dictionary like so:</p>
<pre><code>x = {'age': 23,
'channel': ['a'],
'name': 'Test',
'source': {'data': [1, 2]}}
</code></pre>
<p>and a similar one like:</p>
<pre><code>y = {'age': 23,
'channel': ['c'],
'name': 'Test',
'source': {'data': [3, 4], 'no': 'xyz'}}
</cod... | -1 | 2016-09-16T18:24:09Z | 39,538,072 | <p>You can access the value associated to the key and make the changes.
Lets take the dict example you have taken in your question:</p>
<pre><code>x = {'name': 'Test', 'age': 23, 'channel': ['a'], 'source': {'data': [1,2]}}
x['channel']=['a']
</code></pre>
<p>The value is of type list[].
you can append or add value... | 0 | 2016-09-16T18:34:40Z | [
"python",
"dictionary"
] |
Update/Append to dictionary | 39,537,896 | <p>Let's say I have a dictionary like so:</p>
<pre><code>x = {'age': 23,
'channel': ['a'],
'name': 'Test',
'source': {'data': [1, 2]}}
</code></pre>
<p>and a similar one like:</p>
<pre><code>y = {'age': 23,
'channel': ['c'],
'name': 'Test',
'source': {'data': [3, 4], 'no': 'xyz'}}
</cod... | -1 | 2016-09-16T18:24:09Z | 39,538,357 | <p>Your requirement seems a bit vague, but you can do what you want with a recursive function like the following. (To the point I understood your requirements, you can't append <em>sets</em> to <em>dicts</em> right ? or the likes of these cases)</p>
<pre><code>x = {'age': 23,
'channel': ['a'],
'name': 'Test'... | 2 | 2016-09-16T18:51:45Z | [
"python",
"dictionary"
] |
How do I download the entire pypi Python Package Index | 39,537,938 | <p>I'm trying to find a way to download the entire PyPi index - and only the index - no code files. I'm wanting to analyze license types to be able to rule out libraries that have too restrictive license types. I've looked online and through the user's guide, but if the answer is there, it eludes me.</p>
| 1 | 2016-09-16T18:26:44Z | 39,538,181 | <p>Well, you can use <a href="https://pypi.python.org/simple" rel="nofollow">PyPi's Simple Index</a> to get a simple list of packages without overhead. And then send a GET request to</p>
<pre><code>https://pypi.python.org/pypi/<package-name>/json
</code></pre>
<p>This will return a JSON response containing all ... | 1 | 2016-09-16T18:40:50Z | [
"python",
"pypi"
] |
How can I execute Python code in a virtualenv from Matlab | 39,538,010 | <p>I am creating a Matlab toolbox for research and I need to execute Matlab code but also Python code. </p>
<p>I want to allow the user to execute Python code from Matlab. The problem is that if I do it right away, I would have to install everything on the Python's environment and I want to avoid this using virtualenv... | 3 | 2016-09-16T18:30:22Z | 39,538,066 | <p>You can either modify the <code>PATH</code> environment variable in MATLAB prior to calling python from MATLAB</p>
<pre class="lang-matlab prettyprint-override"><code>% Modify the system PATH so it finds the python executable in your venv first
setenv('PATH', ['/path/to/my/venv/bin', pathsep, getenv('PATH')])
% Ca... | 5 | 2016-09-16T18:34:22Z | [
"python",
"matlab",
"virtualenv"
] |
ipython runs older version of script first before running new version | 39,538,051 | <p>I edited <em>oldscript.py</em> and then saved it in the same directory as <em>newscript.py</em>. After this, when I do <em>%run newscript.py</em> in ipython it seems to run <em>oldscript.py</em> before running <em>newscript.py</em>. I know this because it gives an output from <em>oldscript.py</em> before giving the ... | 0 | 2016-09-16T18:33:22Z | 39,538,325 | <p>I'm pretty sure I just figured it out. I removed <em>oldscript.py</em> from the directory and it worked! Who knew Python could be so particular?! Okay, probably a lot of you, but give me a break I'm a noob ;)</p>
| 0 | 2016-09-16T18:49:57Z | [
"python",
"ipython"
] |
How best to use pandas.DataFrame.pivot? | 39,538,109 | <p>I am trying to translate a dataframe from rows of key, value to a table with keys as the columns and values as cells. For example:</p>
<p>Input dataframe with key, value:</p>
<pre><code>>>>df = pd.DataFrame([['TIME', 'VAL1', 'VAL2', 'VAL3',
'TIME', 'VAL1', 'VAL2', 'VAL3'],
... | 4 | 2016-09-16T18:37:07Z | 39,538,298 | <p>You need an "ID" variable that indicates which rows go together. In your desired output, you are implicitly assuming that every block of 4 rows should become a single row, but pandas won't assume that, because in general pivoting should be able to group together nonconsecutive rows. Each set of rows that you want ... | 3 | 2016-09-16T18:47:59Z | [
"python",
"pandas"
] |
How best to use pandas.DataFrame.pivot? | 39,538,109 | <p>I am trying to translate a dataframe from rows of key, value to a table with keys as the columns and values as cells. For example:</p>
<p>Input dataframe with key, value:</p>
<pre><code>>>>df = pd.DataFrame([['TIME', 'VAL1', 'VAL2', 'VAL3',
'TIME', 'VAL1', 'VAL2', 'VAL3'],
... | 4 | 2016-09-16T18:37:07Z | 39,538,524 | <p>Another way to do this:</p>
<pre><code>In [65]: df
Out[65]:
0 1
0 TIME 00:00:01
1 VAL1 1
2 VAL2 2
3 VAL3 3
4 TIME 00:00:02
5 VAL1 1
6 VAL2 2
7 VAL3 3
In [66]: newdf = pd.concat([df[df[0] == x].reset_index()[1] for x in df[0].unique()], axis=1... | 1 | 2016-09-16T19:03:40Z | [
"python",
"pandas"
] |
How best to use pandas.DataFrame.pivot? | 39,538,109 | <p>I am trying to translate a dataframe from rows of key, value to a table with keys as the columns and values as cells. For example:</p>
<p>Input dataframe with key, value:</p>
<pre><code>>>>df = pd.DataFrame([['TIME', 'VAL1', 'VAL2', 'VAL3',
'TIME', 'VAL1', 'VAL2', 'VAL3'],
... | 4 | 2016-09-16T18:37:07Z | 39,538,604 | <p>You can use a defaultdict that would work fine in the DataFrame constructor:</p>
<pre><code>import collections
keys = ['TIME', 'VAL1', 'VAL2', 'VAL3', 'TIME', 'VAL1', 'VAL2', 'VAL3']
values = ["00:00:01",1,2,3,"00:00:02", 1,2,3]
d = collections.defaultdict(list)
for k, v in zip(keys, values):
d[k].append(v)
'... | 0 | 2016-09-16T19:08:58Z | [
"python",
"pandas"
] |
Load CSV to search for match in array/dictionary/list | 39,538,166 | <p>Very new to Python and I'm now learning by trying to write a program to process data from first few lines from multiple text files. so far so good - getting the data in and reformatting it for output.</p>
<p>Now I'd like to change the format of one output field based on what row it sits in in the csv file. The file... | 0 | 2016-09-16T18:40:14Z | 39,538,405 | <p>I think that you should try with two-dimensional dictionary</p>
<pre><code>new_dic = {}
new_dic[0] = {BIT, BITSIZE, BITM, BS11, BIT, BS4, BIT1, BIT_STM}
new_dic[1] = {CAL, ID27, CALP, HCALI, IECY, CLLO, RD2, RAD3QI, ID4}
</code></pre>
<p>Then you can search for the element and print it.</p>
| 0 | 2016-09-16T18:55:43Z | [
"python",
"list",
"python-2.7",
"csv",
"dictionary"
] |
Load CSV to search for match in array/dictionary/list | 39,538,166 | <p>Very new to Python and I'm now learning by trying to write a program to process data from first few lines from multiple text files. so far so good - getting the data in and reformatting it for output.</p>
<p>Now I'd like to change the format of one output field based on what row it sits in in the csv file. The file... | 0 | 2016-09-16T18:40:14Z | 39,538,760 | <p>you can use "index" to search for an item in a list. if there that item in the list it will return the location of the first occurrence of it.</p>
<pre><code>my_list = ['a','b','c','d','e','c'] # defines the list
copy_at = my_list.index('b') # checks if 'b' is in the list
copy_at # prints the location in the list w... | 0 | 2016-09-16T19:21:10Z | [
"python",
"list",
"python-2.7",
"csv",
"dictionary"
] |
How to debug Pygame application with Visual Studio during runtime | 39,538,259 | <p>I've been making a small game for a homework assignment using Pygame with Livewires. I've been trying to debug it, but to no success; I can't get a look at the variables I want to look at before the main loop is executed. Though I can press F10 to skip over the main loop, that just stops the Autos and Watches window... | 0 | 2016-09-16T18:45:59Z | 39,582,747 | <p>Thanks to Jack Zhai's suggestion, I figured it out. </p>
<ol>
<li><p>When the breakpoint is hit, unpause the debugger (shortcut: F5)</p></li>
<li><p>Play to the point in the game you want to debug.</p></li>
<li><p>Repause the debugger using Break All (shortcut: Ctrl-Alt-Break)</p></li>
<li><p>Press F10 a few times;... | 0 | 2016-09-19T21:57:17Z | [
"python",
"visual-studio",
"debugging",
"pygame",
"livewires"
] |
Given an acyclic directed graph, return a collection of collections of nodes "at the same level"? | 39,538,363 | <p>Firstly I am not sure what such an algorithm is called, which is the primary problem - so first part of the question is what is this algorithm called?</p>
<p>Basically I have a <code>DiGraph()</code> into which I insert the nodes <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</code> and the edges <code>([1,3],[2,3],[3,5],[4... | 4 | 2016-09-16T18:52:21Z | 39,538,477 | <p>Why would bfs not solve it? A bfs algorithm is breadth traversal algorithm, i.e. it traverses the tree level wise. This also means, all nodes at same level are traversed at once, which is your desired output.
As pointed out in comment, this will however, assume a starting point in the graph.</p>
| 0 | 2016-09-16T19:00:19Z | [
"python",
"algorithm",
"graph",
"graph-theory",
"networkx"
] |
Given an acyclic directed graph, return a collection of collections of nodes "at the same level"? | 39,538,363 | <p>Firstly I am not sure what such an algorithm is called, which is the primary problem - so first part of the question is what is this algorithm called?</p>
<p>Basically I have a <code>DiGraph()</code> into which I insert the nodes <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</code> and the edges <code>([1,3],[2,3],[3,5],[4... | 4 | 2016-09-16T18:52:21Z | 39,538,705 | <p>Your question states that you would like the output, for this graph, to be <code>[[1, 2, 4, 6], [3], [5], [7], [8, 9, 10]]</code>. IIUC, the pattern is as follows:</p>
<ul>
<li><p><code>[1, 2, 4, 6]</code> are the nodes that have no in edges.</p></li>
<li><p><code>[3]</code> are the nodes that have no in edges, ass... | 4 | 2016-09-16T19:16:40Z | [
"python",
"algorithm",
"graph",
"graph-theory",
"networkx"
] |
Given an acyclic directed graph, return a collection of collections of nodes "at the same level"? | 39,538,363 | <p>Firstly I am not sure what such an algorithm is called, which is the primary problem - so first part of the question is what is this algorithm called?</p>
<p>Basically I have a <code>DiGraph()</code> into which I insert the nodes <code>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]</code> and the edges <code>([1,3],[2,3],[3,5],[4... | 4 | 2016-09-16T18:52:21Z | 39,542,360 | <p>A topological sort will achieve this, as Ami states. The following is a Boost Graph Library implementation, with no context, but the pseudocode can be extracted. The <code>toporder</code> object just provides the iterator to a topological ordering. I can extract the general algorithm if desired. </p>
<pre><code>tem... | 2 | 2016-09-17T02:35:59Z | [
"python",
"algorithm",
"graph",
"graph-theory",
"networkx"
] |
Scraping table information | 39,538,366 | <p>I would like to extract the odds information from the website <a href="http://www.footballlocks.com/nfl_odds.shtml" rel="nofollow">http://www.footballlocks.com/nfl_odds.shtml</a> using Python.</p>
<p>I have been trying to do it with BeautifulSoup.</p>
<p>The optimal result would be to obtain the odds information i... | 1 | 2016-09-16T18:53:02Z | 39,552,858 | <p>It is not the nicest html to parse as there are no classes we can use but this will put all the rows into a list of dicts:</p>
<pre><code>from bs4 import BeautifulSoup
import requests
url = "http://www.footballlocks.com/nfl_odds.shtml"
soup = BeautifulSoup(requests.get(url).content)
# Use the text of one of the... | 1 | 2016-09-18T00:00:57Z | [
"python",
"html",
"web-scraping"
] |
How to display images in html? | 39,538,368 | <p>I have a working app using the imgur API with python.</p>
<pre><code>from imgurpython import ImgurClient
client_id = '5b786edf274c63c'
client_secret = 'e44e529f76cb43769d7dc15eb47d45fc3836ff2f'
client = ImgurClient(client_id, client_secret)
items = client.subreddit_gallery('rarepuppers')
for item in items:
p... | -1 | 2016-09-16T18:53:09Z | 39,539,035 | <p>OK, I haven't tested this, but it should work. The HTML is really basic (but you never mentioned anything about formatting) so give this a shot:</p>
<pre><code>from imgurpython import ImgurClient
client_id = '5b786edf274c63c'
client_secret = 'e44e529f76cb43769d7dc15eb47d45fc3836ff2f'
client = ImgurClient(client_... | 0 | 2016-09-16T19:41:14Z | [
"python",
"html",
"api",
"imgur"
] |
read bash array from property file into a script | 39,538,371 | <ol>
<li><p>I've a property file abc.prop that contains the following.</p>
<pre><code>x=(A B)
y=(C D)
</code></pre></li>
<li><p>I've a python script abc.py which is able to load the property file abc.prop.
But I'm not able to iterate and convert both the arrays from abc.prop as follows,</p>
<pre><code>x_array=['A','B... | 0 | 2016-09-16T18:53:16Z | 39,539,479 | <p>I'm not aware of any special bash to python data structure converters. And I doubt there are any. The only thing I may suggest is a little bit cleaner and dynamic way of doing this.</p>
<pre><code>data = {}
with open('abc.prop', 'r') as f:
for line in f:
parts = line.split('=')
key = parts[0].st... | 1 | 2016-09-16T20:16:20Z | [
"python"
] |
Dynamic entries in a settings module | 39,538,409 | <p>I'm writing a package that imports audio files, processes them, plots them etc., for research purposes.
At each stage of the pipeline, settings are pulled from a settings module as shown below. </p>
<p>I want to be able to update a global setting like <code>MODEL_NAME</code> and have it update in any dicts containi... | 0 | 2016-09-16T18:55:54Z | 39,540,660 | <p>You want to configure generic and specific settings structured in dictionaries for functions that perform waves analysis.</p>
<p>Start by defining a settings class, like :</p>
<pre><code>class Settings :
data_directory = 'path/to/waves'
def __init__(self, model):
self.parameters= {
"key1... | 1 | 2016-09-16T21:59:01Z | [
"python",
"dictionary",
"configuration",
"python-module"
] |
My search in MySQL it's not working (Python) | 39,538,456 | <p>I'm trying to get information from a database I have. But everytime I search it says there is nothing that follows the query. This is what I have.</p>
<pre><code>import datetime
import MySQLdb
db = MySQLdb.connect(user='root', passwd='', host='localhost', db = 'data') or die ('Error while connecting')
cursor = db.... | 2 | 2016-09-16T18:58:59Z | 39,538,538 | <p>Your <code>db.commit()</code> might be throwing it off. However, lots of factors could play a part in this. You might also consider printing out your SQL query to see what is being put so like this:</p>
<p>Try setting up your code like this, it should lead you in the right direction:</p>
<pre><code>import MySQLdb ... | 1 | 2016-09-16T19:04:32Z | [
"python",
"mysql",
"datetime"
] |
How to access preexisting table with Sqlalchemy | 39,538,531 | <p>I'm working with scrapy. I want to get access to a sqlalchemy session for a table with a table named 'contacts' according to the docs (<a href="http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#getting-a-session" rel="nofollow">http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#getting-a-session... | 1 | 2016-09-16T19:04:08Z | 39,543,773 | <p>You can connect to pre-existing tables via reflection. Unfortunately your question lacks some of the code setup, so below is a general pseudocode example (assuming your table name is <code>contacts</code>)</p>
<pre><code>from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
# Look up th... | 1 | 2016-09-17T06:54:11Z | [
"python",
"sqlalchemy"
] |
Python using lxml to write an xml file with system performance data | 39,538,576 | <p>I am using the python modules <code>lxml</code> and <code>psutil</code> to record some system metrics to be placed in an XML file and copied to a remote server for parsing by php and displayed to a user. </p>
<p>However, lxml is giving me some trouble on pushing some variables, objects and such to the various parts... | 0 | 2016-09-16T19:07:19Z | 39,538,627 | <p>The <code>text</code> field is expected to be unicode or str, not any other type (<code>boot_time</code> is <code>float</code>, and <code>len()</code> is int).
So just convert to string the non-string compliant elements:</p>
<pre><code># First system/hostname, so we know what machine this is
etree.SubElement(child1... | 2 | 2016-09-16T19:11:08Z | [
"python",
"lxml",
"psutil"
] |
Generate data with normally distributed noise and mean function | 39,538,610 | <p>I created a numpy array with n values from 0 to 2pi. Now, I want to generate n test data points deviating from sin(x) normally distributed. </p>
<p>So i figured I need to do something like this: <code>t = sin(x) + noise</code>. Where the noise must be something like this: <code>noise = np.random.randn(mean, std)</c... | 1 | 2016-09-16T19:09:46Z | 39,538,803 | <p>The arguments to <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.randn.html" rel="nofollow"><code>numpy.random.randn</code></a> are not the mean and standard deviation. For that, you want <a href="http://docs.scipy.org/doc/numpy/reference/generated/numpy.random.normal.html" rel="nofollow">... | 2 | 2016-09-16T19:24:16Z | [
"python",
"numpy",
"scipy",
"normal-distribution"
] |
Generate data with normally distributed noise and mean function | 39,538,610 | <p>I created a numpy array with n values from 0 to 2pi. Now, I want to generate n test data points deviating from sin(x) normally distributed. </p>
<p>So i figured I need to do something like this: <code>t = sin(x) + noise</code>. Where the noise must be something like this: <code>noise = np.random.randn(mean, std)</c... | 1 | 2016-09-16T19:09:46Z | 39,539,184 | <p>If you add the noise to the <code>y</code> coordinate, some of the test data points may have values outside the normal range of the sine function, that is, not from -1 to 1, but from -(1+noise) to +(1+noise). I suggest to add the noise to the <code>x</code> coordinate: </p>
<pre><code>t = np.sin(x + np.random.unifo... | 1 | 2016-09-16T19:53:04Z | [
"python",
"numpy",
"scipy",
"normal-distribution"
] |
Get color of individual pixels of images in pygame | 39,538,642 | <p>How can I get the colour values of pixels of an image that is blitted onto a pygame surface? Using Surface.get_at() only returns the color of the surface layer, not the image that has been blitted over it.</p>
| 1 | 2016-09-16T19:11:53Z | 39,550,937 | <p>The method <code>surface.get_at</code> is fine.
Here is an example showing the difference when blitting an image without alpha channel.</p>
<pre><code>import sys, pygame
pygame.init()
size = width, height = 320, 240
screen = pygame.display.set_mode(size)
image = pygame.image.load("./img.bmp")
image_rect = image.ge... | 3 | 2016-09-17T19:34:14Z | [
"python",
"image",
"image-processing",
"pygame"
] |
correct way to inherit method with 1 correction | 39,538,665 | <p>I experimented a little bit OOP in python, while doing homework on data structures and I have some troubles with understanding how to correct inherit some method with corrections. </p>
<p>So, I have:</p>
<pre><code>class BinarySearchTree(object):
# snipped
def _insert(self, key, val):
prevNode = No... | 1 | 2016-09-16T19:13:35Z | 39,538,742 | <p>Assuming that <code>prevNode</code> is also a <code>BTree</code> or <code>RBTree</code>, you could add another method, say 'updateSize`, and include the line </p>
<pre><code>prevNode.updateSize()
</code></pre>
<p>In <code>BTree</code>, this would do nothing. But if you make <code>RBTree</code> a subclass of <code... | 1 | 2016-09-16T19:19:33Z | [
"python",
"python-2.7",
"inheritance"
] |
correct way to inherit method with 1 correction | 39,538,665 | <p>I experimented a little bit OOP in python, while doing homework on data structures and I have some troubles with understanding how to correct inherit some method with corrections. </p>
<p>So, I have:</p>
<pre><code>class BinarySearchTree(object):
# snipped
def _insert(self, key, val):
prevNode = No... | 1 | 2016-09-16T19:13:35Z | 39,538,944 | <p>Here's a suggestion using the Visitor design pattern.</p>
<p>In this pattern, you're writing a visitor method than knows specifically what needs to be done with each node visited.</p>
<p>We'll change the base class to add a visitor capability;</p>
<pre><code>class BinarySearchTree(object):
# snipped
def _insert(s... | 1 | 2016-09-16T19:34:54Z | [
"python",
"python-2.7",
"inheritance"
] |
correct way to inherit method with 1 correction | 39,538,665 | <p>I experimented a little bit OOP in python, while doing homework on data structures and I have some troubles with understanding how to correct inherit some method with corrections. </p>
<p>So, I have:</p>
<pre><code>class BinarySearchTree(object):
# snipped
def _insert(self, key, val):
prevNode = No... | 1 | 2016-09-16T19:13:35Z | 39,539,060 | <p>It's not exactly elegant, but you could do something like this:</p>
<pre><code>class BinarySearchTree(object):
def _insert(self, key, val, update=False):
prevNode = None
currentNode = self.root
while currentNode:
prevNode = currentNode
if update:
pre... | 2 | 2016-09-16T19:43:28Z | [
"python",
"python-2.7",
"inheritance"
] |
Relative Python Modules | 39,538,721 | <p>I am having a lot of trouble understanding the python module import system.</p>
<p>I am trying to create a simple folder structure as follows.</p>
<pre><code>SomeModule
__init__.py
AnotherModule
AnotherModule.py
__init__.py
Utils
Utils.py
__init__.py
</code></pre>
... | 1 | 2016-09-16T19:18:16Z | 39,538,866 | <p>To shorten up the actual function name that you'll have to call in your code, you can always do:</p>
<pre><code>from SomeModule.AnotherModule.Utils import *
</code></pre>
<p>While this still won't allow you to get away with a shorter import statement at the top of your script, you'll be able to access all of the f... | 0 | 2016-09-16T19:29:22Z | [
"python",
"python-2.7"
] |
Relative Python Modules | 39,538,721 | <p>I am having a lot of trouble understanding the python module import system.</p>
<p>I am trying to create a simple folder structure as follows.</p>
<pre><code>SomeModule
__init__.py
AnotherModule
AnotherModule.py
__init__.py
Utils
Utils.py
__init__.py
</code></pre>
... | 1 | 2016-09-16T19:18:16Z | 39,539,157 | <p>put</p>
<pre><code>import sys
import SomeModule.AnotherModule
sys.modules['AnotherModule'] = SomeModule.AnotherModule
</code></pre>
<p>in SomeModules <code>__init__.py</code></p>
| 0 | 2016-09-16T19:51:06Z | [
"python",
"python-2.7"
] |
Is file automatically closed if read in same line as opening? | 39,538,802 | <p>If I do (in Python):</p>
<pre><code>text = open("filename").read()
</code></pre>
<p>is the file automatically closed?</p>
| 4 | 2016-09-16T19:24:14Z | 39,538,833 | <p>The garbage collector would be activated at some point, but you cannot be certain of when unless you force it.</p>
<p>The best way to ensure that the file is closed when you go out of scope just do this:</p>
<pre><code>with open("filename") as f: text = f.read()
</code></pre>
<p>also one-liner but safer.</p>
| 6 | 2016-09-16T19:26:47Z | [
"python",
"file",
"io"
] |
Is file automatically closed if read in same line as opening? | 39,538,802 | <p>If I do (in Python):</p>
<pre><code>text = open("filename").read()
</code></pre>
<p>is the file automatically closed?</p>
| 4 | 2016-09-16T19:24:14Z | 39,538,837 | <p>In CPython (the reference Python implementation) the file will be automatically closed. CPython destroys objects as soon as they have no references, which happens at the end of the statement at the very latest.</p>
<p>In other Python implementations this may not happen right away since they may rely on the memory m... | 3 | 2016-09-16T19:27:15Z | [
"python",
"file",
"io"
] |
Is file automatically closed if read in same line as opening? | 39,538,802 | <p>If I do (in Python):</p>
<pre><code>text = open("filename").read()
</code></pre>
<p>is the file automatically closed?</p>
| 4 | 2016-09-16T19:24:14Z | 39,538,839 | <p>Since you have no reference on the open file handle,
CPython will close it automatically either during garbage collection or at program exit. The problem here is that you don't have any guarantees about when that will occur, which is why the <code>with open(...)</code> construct is preferred. </p>
| 2 | 2016-09-16T19:27:21Z | [
"python",
"file",
"io"
] |
Django - Why are variables declared in Model Classes Static | 39,538,841 | <p>I have been reading and working with Django for a bit now. One of the things that I am still confused with is why the model classes that we create in Django are made up of static variables and not member variables. For instance</p>
<pre><code>class Album(models.Model):
artist = models.CharField(max_length=128, ... | 1 | 2016-09-16T19:27:32Z | 39,540,205 | <p>Django uses a <a href="https://docs.python.org/3/reference/datamodel.html#customizing-class-creation" rel="nofollow">metaclass</a> to create the model class. Just as a class's <code>__init__()</code> method creates a new instance, the metaclass's <code>__new__()</code> method creates the class itself. All variables,... | 1 | 2016-09-16T21:17:42Z | [
"python",
"django"
] |
Parsing text fields into excel columns | 39,538,943 | <p>I've attempted to parse out data that's over 20,000 records. Each record has 4 fields that's prefixed with 2 alphanumeric values. Below is an example with 2 records. I currently have a bloated solution that uses Java based on the link here: <a href="http://stackoverflow.com/questions/25491424/parsing-html-data-using... | 1 | 2016-09-16T19:34:54Z | 39,540,858 | <p>This one is kinda crappy but it works. here you go:</p>
<pre><code>#!/bin/bash
i=0
while IFS= read -r line;do
echo $line | egrep -q '^[0-9]+'
if test $? -eq 0; then
id1=$(echo $line | cut -d' ' -f1)
id2=$(echo $line | cut -d' ' -f2)
((i++))
fi
echo $line | egrep -q 'Category'
if test $? -eq 0; then
cat=$(ec... | 0 | 2016-09-16T22:18:44Z | [
"python",
"excel",
"parsing",
"text",
"vbscript"
] |
What files are required for Py_Initialize to run? | 39,539,089 | <p>I am working on a simple piece of code that runs a Python function from a C/C++ application. In order to do this I set the PYTHONPATH and run initialize as follows:</p>
<pre class="lang-c++ prettyprint-override"><code>Py_SetPythonHome("../Python27");
Py_InitializeEx(0);
</code></pre>
<p>Then I import my module and... | 3 | 2016-09-16T19:45:42Z | 39,541,474 | <p>At the beginning I wanted to say that there's no module required (at least no <em>non-builtin</em> one) for <code>Py_InitializeEx</code>, so the only requirement was <em>python27.dll</em> (btw: <em>python27.lib</em> is <strong>not</strong> required, unless your colleagues want to link something against it - but that... | 0 | 2016-09-16T23:45:30Z | [
"python",
"c++",
"ctypes",
"embedding"
] |
Beginning Python: For Loop- what do to afterwards | 39,539,090 | <p>Found this exercise in a textbook online and am attempting to battle my way through it. I believe they intended it to be answered with a while loop, but I'm using a for loop instead which could be my problem.</p>
<p>"Write a program that prompts the user to enter an integer and returns two integers <em>pwr</em> and... | 2 | 2016-09-16T19:45:51Z | 39,539,279 | <p>You want to check if there is an integer <code>root</code> such that <code>root ** pwr == user_input</code>. With a little math we can re-write the above statement as <code>root = user_input ** (1. / pwr)</code>. You've got a pretty small number of <code>pwr</code> values to choose from, so you can simply loop over ... | 3 | 2016-09-16T20:00:37Z | [
"python",
"if-statement",
"for-loop"
] |
Beginning Python: For Loop- what do to afterwards | 39,539,090 | <p>Found this exercise in a textbook online and am attempting to battle my way through it. I believe they intended it to be answered with a while loop, but I'm using a for loop instead which could be my problem.</p>
<p>"Write a program that prompts the user to enter an integer and returns two integers <em>pwr</em> and... | 2 | 2016-09-16T19:45:51Z | 39,539,343 | <p>How about this?</p>
<pre><code>userNum = int(input("Choose a number: "))
for i in range(1,6):
for j in range(userNum):
if j ** i == userNum:
pwr = i
root = j
if pwr:
print('pwr = {}, root = {}'.format(pwr, root))
print("No such integers exist.")
</code></pre>
| -1 | 2016-09-16T20:06:55Z | [
"python",
"if-statement",
"for-loop"
] |
Beginning Python: For Loop- what do to afterwards | 39,539,090 | <p>Found this exercise in a textbook online and am attempting to battle my way through it. I believe they intended it to be answered with a while loop, but I'm using a for loop instead which could be my problem.</p>
<p>"Write a program that prompts the user to enter an integer and returns two integers <em>pwr</em> and... | 2 | 2016-09-16T19:45:51Z | 39,539,677 | <p>Here's my solution using @BiRico's <code>for..else</code> strategy and an inner <code>while</code> loop to make it more efficient. Of course, because there is no bounds on <code>root</code> and we're only looking for one solution, it only finds the trivial case (<code>root = number, pwr = 1</code>).</p>
<pre><code>... | 0 | 2016-09-16T20:31:31Z | [
"python",
"if-statement",
"for-loop"
] |
Django Password Resest Via Email | 39,539,102 | <p>I'm trying to implement password reset by sending an email to the user with a link which will redirect him/her to a new password form. </p>
<p>I took by example <a href="http://stackoverflow.com/questions/18928144/django-user-registration-password-reset-via-email">this question</a> and <a href="http://ruddra.com/20... | 1 | 2016-09-16T19:46:43Z | 39,539,379 | <p>Iâd suggest to borrow the general logic from Django and adapt it to your specific conditions:</p>
<ul>
<li><a href="https://github.com/django/django/blob/master/django/contrib/auth/tokens.py" rel="nofollow"><strong><code>PasswordResetTokenGenerator</code> code</strong></a> â pretty well-documented, very useful<... | 1 | 2016-09-16T20:09:52Z | [
"python",
"django",
"django-forms"
] |
Django Password Resest Via Email | 39,539,102 | <p>I'm trying to implement password reset by sending an email to the user with a link which will redirect him/her to a new password form. </p>
<p>I took by example <a href="http://stackoverflow.com/questions/18928144/django-user-registration-password-reset-via-email">this question</a> and <a href="http://ruddra.com/20... | 1 | 2016-09-16T19:46:43Z | 39,539,861 | <p>The problem is not to generate unique link, you need to store somewhere info about user id or email, and generated token. Otherwise you will not know which user should use which token. After user resets his password you can delete his record (his token). </p>
<p>You can write the most simple model even in sqlite, w... | 1 | 2016-09-16T20:47:30Z | [
"python",
"django",
"django-forms"
] |
Django Password Resest Via Email | 39,539,102 | <p>I'm trying to implement password reset by sending an email to the user with a link which will redirect him/her to a new password form. </p>
<p>I took by example <a href="http://stackoverflow.com/questions/18928144/django-user-registration-password-reset-via-email">this question</a> and <a href="http://ruddra.com/20... | 1 | 2016-09-16T19:46:43Z | 39,540,032 | <p><strong>Don't reinvent the wheel.</strong> You should use <a href="https://github.com/pennersr/django-allauth" rel="nofollow">django-allauth</a> for this kind of stuff. The library is well maintained and under active development.</p>
| 0 | 2016-09-16T21:02:32Z | [
"python",
"django",
"django-forms"
] |
Separating/accessing a triple tuple list like [[[x,y],z],p]? | 39,539,142 | <p>I am trying to access variables stored in a triple tuple list in python and I am not sure how to do it. I would like to be able to go through the list in a for loop and get x,y,x, & p from each tuple. How would I do that? </p>
<pre><code>MovesList = [ [[[1,2],3],1] , [[[2,5],3],1] , [[[1,3],0],2] ]
</code></p... | 0 | 2016-09-16T19:49:48Z | 39,539,182 | <p>You can unpack tuples as you iterate over them:</p>
<p>Python 2:</p>
<pre><code>>>> for ((x,y),z),p in MovesList:
... print x, y, z, p
</code></pre>
<p>Python 3:</p>
<pre><code>>>> for ((x,y),z),p in MovesList:
... print(x,y,z,p)
</code></pre>
<p>Both of which result in:</p>
<pre><cod... | 3 | 2016-09-16T19:52:54Z | [
"python"
] |
Separating/accessing a triple tuple list like [[[x,y],z],p]? | 39,539,142 | <p>I am trying to access variables stored in a triple tuple list in python and I am not sure how to do it. I would like to be able to go through the list in a for loop and get x,y,x, & p from each tuple. How would I do that? </p>
<pre><code>MovesList = [ [[[1,2],3],1] , [[[2,5],3],1] , [[[1,3],0],2] ]
</code></p... | 0 | 2016-09-16T19:49:48Z | 39,539,275 | <p>same unpacking with list comprehension</p>
<pre><code>In [202]: [[x,y,z,p] for ([[x,y],z],p) in MovesList]
Out[202]: [[1, 2, 3, 1], [2, 5, 3, 1], [1, 3, 0, 2]]
</code></pre>
| 0 | 2016-09-16T20:00:20Z | [
"python"
] |
Separating/accessing a triple tuple list like [[[x,y],z],p]? | 39,539,142 | <p>I am trying to access variables stored in a triple tuple list in python and I am not sure how to do it. I would like to be able to go through the list in a for loop and get x,y,x, & p from each tuple. How would I do that? </p>
<pre><code>MovesList = [ [[[1,2],3],1] , [[[2,5],3],1] , [[[1,3],0],2] ]
</code></p... | 0 | 2016-09-16T19:49:48Z | 39,819,791 | <p>I also found you can unpack a list of tuples that doesn't have a finite space by putting it through a while loop like so:</p>
<pre><code>Mylist = list()
MyOtherList = list()
//list is packed my tuples of four {(a,b,c,d),(a,b,c,d),(a,b,c,d),...}
While MyList[0] != Null:
var w = MyList[0][0]
var x = MyList[... | 0 | 2016-10-02T17:41:34Z | [
"python"
] |
pd.rolling_max and min with groupby or similar | 39,539,151 | <p>Using the following code I am able to capture the rolling high and low of my data in the <code>H1_high</code>and <code>H1_low</code> columns. </p>
<pre><code>data["H1_high"] = pd.rolling_max(data.High, window=60, min_periods=1)
data["H1_low"] = pd.rolling_min(data.Low, window=60, min_periods=1)
</code></pre>
<p>... | 2 | 2016-09-16T19:50:29Z | 39,539,484 | <p>use <code>datetime.time</code> and filter your index</p>
<pre><code>import datetime
high_low_xt = lambda df: pd.concat([df.High.cummax(), df.Low.cummin()], axis=1)
tidx = pd.date_range('2016-09-14', '2016-09-16', freq='T')
start = datetime.time(9, 30)
end = datetime.time(10, 30)
eod = datetime.time(18, 14)
bidx ... | 0 | 2016-09-16T20:16:38Z | [
"python",
"pandas"
] |
How to create an rray of composites strings | 39,539,230 | <p>Hi everyone: I have a collection of 50 strings that represent comments in a text file where each line represents a separate comment with different sentences . </p>
<p>Each string is a user review of a product, and each string or review has several several sentences. </p>
<p>How could I to create an array with thes... | 1 | 2016-09-16T19:56:22Z | 39,540,860 | <p>One of my first projects was similar to this. I believe your asking for help in getting the text file lines as an array.</p>
<p>To open the file for reading: </p>
<p><code>file = open("/path/to/file", "r")</code></p>
<p>I would then split on spaces so: </p>
<pre><code>for line in file:
print line.split(' ... | 0 | 2016-09-16T22:19:11Z | [
"python",
"arrays",
"string"
] |
Python for loop over two lists for all the pairs | 39,539,287 | <p>I have a dataframe with date, id - I need to pull out each date and id combination and create a new dataframe.</p>
<pre><code> date id
2016-05-13 abc
2016-05-13 pqr
2016-05-14 abc
2016-05-14 pqr
ids = list(sorted(set(df['id'])))
Out: ['abc','pqr']
dates = list(sorted(set(df[df.i... | 2 | 2016-09-16T20:01:11Z | 39,539,342 | <p>to get all the pairs <code>ids</code> vs. <code>dates</code>, you could use <code>itertools</code> as</p>
<pre><code>import itertools
for iid, ddate in itertools.product(ids, dates):
df2 = df[(df.date == ddate) & (df.id == iid)]
</code></pre>
| -2 | 2016-09-16T20:06:42Z | [
"python",
"pandas",
"for-loop",
"iteration"
] |
Python for loop over two lists for all the pairs | 39,539,287 | <p>I have a dataframe with date, id - I need to pull out each date and id combination and create a new dataframe.</p>
<pre><code> date id
2016-05-13 abc
2016-05-13 pqr
2016-05-14 abc
2016-05-14 pqr
ids = list(sorted(set(df['id'])))
Out: ['abc','pqr']
dates = list(sorted(set(df[df.i... | 2 | 2016-09-16T20:01:11Z | 39,540,243 | <p>Create a new dataframe with each <code>id</code> in columns and each <code>date</code> in rows. You can fill it in later.</p>
<pre><code>pd.DataFrame([], set(df.date), set(df.id))
</code></pre>
<p><a href="http://i.stack.imgur.com/ig5Xe.png" rel="nofollow"><img src="http://i.stack.imgur.com/ig5Xe.png" alt="enter ... | 0 | 2016-09-16T21:20:32Z | [
"python",
"pandas",
"for-loop",
"iteration"
] |
Specialized @property decorators in python | 39,539,292 | <p>I have a few classes each of which has a number of attributes. What all of the attributes have in common is that they should be numeric properties. This seems to be an ideal place to use python's decorators, but I can't seem to wrap my mind around what the correct implementation would be. Here is a simple example:</... | 4 | 2016-09-16T20:01:31Z | 39,539,523 | <p>A <code>@property</code> is just a special case of Python's <a href="https://docs.python.org/3/howto/descriptor.html" rel="nofollow">descriptor protocol</a>, so you can certainly build your own custom versions. For your case:</p>
<pre><code>class NumericProperty:
"""A property that must be numeric.
Args:
... | 2 | 2016-09-16T20:19:03Z | [
"python",
"python-3.x",
"decorator",
"python-decorators"
] |
Specialized @property decorators in python | 39,539,292 | <p>I have a few classes each of which has a number of attributes. What all of the attributes have in common is that they should be numeric properties. This seems to be an ideal place to use python's decorators, but I can't seem to wrap my mind around what the correct implementation would be. Here is a simple example:</... | 4 | 2016-09-16T20:01:31Z | 39,539,588 | <p>You may just create a function that does it for you . As simple as it can get, no need to create a custom descriptor:</p>
<pre><code>def numprop(name, privname):
@property
def _numprop(self):
return getattr(self, privname)
@_numprop.setter
def _numprop(self, value):
if not isinstanc... | 0 | 2016-09-16T20:23:48Z | [
"python",
"python-3.x",
"decorator",
"python-decorators"
] |
Specialized @property decorators in python | 39,539,292 | <p>I have a few classes each of which has a number of attributes. What all of the attributes have in common is that they should be numeric properties. This seems to be an ideal place to use python's decorators, but I can't seem to wrap my mind around what the correct implementation would be. Here is a simple example:</... | 4 | 2016-09-16T20:01:31Z | 39,539,771 | <h2>Option 1: inherit from <code>property</code></h2>
<p><code>property</code> is a descriptor. See <a href="https://docs.python.org/3/howto/descriptor.html" rel="nofollow">Descriptor HowTo on python.org</a>.</p>
<p>So, can inherit from <code>property</code> and override the relevant methods.</p>
<p>For example, to ... | 1 | 2016-09-16T20:39:52Z | [
"python",
"python-3.x",
"decorator",
"python-decorators"
] |
Use variables as keywords for functions with pre-defined keywords (Python) | 39,539,316 | <p>I'm trying to create a simple function that allows a user to input basic information that will change the values of a datetime object, and I'd like to find a way to make it as clean as possible by using a variable as a keyword. This can easily be done a different way, but I figured it'd be useful to know how to rep... | 0 | 2016-09-16T20:04:10Z | 39,539,444 | <p>Python allows you to store data in a dictionary and finally unpack them as keyword arguments to different functions.</p>
<p>For the thing that you want to do, best way to accomplish this is to use kwargs.</p>
<pre><code>replacement_info = {'day': 2, 'month': 9, ...}
new_time = start_time.replace(**replacement_inf... | 0 | 2016-09-16T20:14:16Z | [
"python",
"datetime"
] |
Use variables as keywords for functions with pre-defined keywords (Python) | 39,539,316 | <p>I'm trying to create a simple function that allows a user to input basic information that will change the values of a datetime object, and I'd like to find a way to make it as clean as possible by using a variable as a keyword. This can easily be done a different way, but I figured it'd be useful to know how to rep... | 0 | 2016-09-16T20:04:10Z | 39,539,449 | <p>You cannot replace keyword arguments on a function you did not write. When calling a function like:</p>
<pre><code>f(a=b)
</code></pre>
<p>The value of <code>a</code> is not sent as an argument to <code>f</code>. Instead, the value of <code>b</code> is sent and that value is set to the argument <code>a</code> in <... | 1 | 2016-09-16T20:14:27Z | [
"python",
"datetime"
] |
Use variables as keywords for functions with pre-defined keywords (Python) | 39,539,316 | <p>I'm trying to create a simple function that allows a user to input basic information that will change the values of a datetime object, and I'd like to find a way to make it as clean as possible by using a variable as a keyword. This can easily be done a different way, but I figured it'd be useful to know how to rep... | 0 | 2016-09-16T20:04:10Z | 39,539,465 | <p>Change your last line to something like this:</p>
<pre><code>year = start_time.year
month = start_time.month
day = start_time.day
hour = start_time.hour
minute = start_time.minute
second = start_time.second
microsecond = start_time.microsecond
exec(time_type + '='+str(new_time))
print(start_time.replace(year, month... | 0 | 2016-09-16T20:15:42Z | [
"python",
"datetime"
] |
python socket server and java android socket - freezes app | 39,539,356 | <p>I'm making a python server running on my computer and java socket client running on my phone. the minute the java tries to connect, the app freezes. Not saying anything in the logcat. I have no idea why...</p>
<p>python 3.5.1:</p>
<pre><code>PORT = 8888
import socket
sock = socket.socket()
sock.bind(("0.0.0.0", ... | 0 | 2016-09-16T20:08:23Z | 39,539,885 | <p>This line is wrong:</p>
<pre><code>client = sock.connect()
</code></pre>
<p>Servers don't call <code>connect()</code>. Servers call <code>listen()</code> and <code>accept()</code>. Only clients call <code>connect()</code>.</p>
<p>Since your server calls <code>bind()</code> and <code>listen()</code>, but not <code... | 0 | 2016-09-16T20:49:42Z | [
"java",
"android",
"python",
"sockets"
] |
Python Split data into multiple files with a rule | 39,539,358 | <p>I need some idea to solve my problem in python to split a file.</p>
<p>I more than 1.000.000 rows in a file with 2 columns: "accountid" and a "property". One "accountid" can have multiple properties, but each property is one row. Looks something like this:
<a href="http://i.stack.imgur.com/d2aVJ.png" rel="nofollow"... | 0 | 2016-09-16T20:08:32Z | 39,561,775 | <p>Here is one solution that comes to my mind:</p>
<p>First you have to determine how many partitions you will need, based on two parameters X and Y. X is determined by the accountid with the maximum number of properties. Let's assume accountid=7 has the maximum number of properties equal to 270 properties. That means... | 0 | 2016-09-18T19:29:25Z | [
"python",
"split"
] |
Tkinter intvar causing process to live on | 39,539,462 | <p>I realize there are many <a href="http://stackoverflow.com/questions/110923/close-a-tkinter-window">examples</a> of how to properly close a Tkinter GUI by calling the root.destroy() function. They work with my setup except I've determined that including a variable of type tkinter.intvar causes the gui process to liv... | 0 | 2016-09-16T20:15:30Z | 39,540,567 | <p><code>nexusvar</code> isn't a child of <code>root</code>, so when you destroy <code>root</code> it doesn't know to destroy <code>nexusvar</code> as well - the two things are separate. You can set an <code>IntVar</code> to have <code>root</code> as a parent by supplying <code>root</code> to the constructor. <code>nex... | 1 | 2016-09-16T21:50:04Z | [
"python",
"tkinter",
"process"
] |
How to sharex and sharey axis in for loop | 39,539,476 | <p>I'm trying to share the x-axis and y-axis of my sumplots, I've tried using the sharey and sharex several different ways but haven't gotten the correct result.</p>
<pre><code>ax0 = plt.subplot(4,1,1)
for i in range(4):
plt.subplot(4,1,i+1,sharex = ax0)
plt.plot(wavelength[i],flux)
plt.xlim([-1000,1000])
... | 0 | 2016-09-16T20:16:15Z | 39,539,785 | <p>If I understood you correctly, want to have four stacked plots, sharing the x-axis and the y-axis. This you can do with <a href="http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.subplots" rel="nofollow">plt.subplots</a> and the keywords <code>sharex=True</code> and <code>sharey=True</code>. See example ... | 0 | 2016-09-16T20:40:41Z | [
"python",
"matplotlib"
] |
Control robot by using keyboard | 39,539,561 | <p>I am new to Python and raspberry pi, I have created a wheeled robot and codes for forwards, backward, turn left and turn right! However every time I want to execute a differant script I have to open a new code and run it(eg open the file for forwards, then open the file for left etc etc.) </p>
<p>How do I use the t... | 0 | 2016-09-16T20:21:51Z | 39,551,299 | <p>You only need one file for this. Make a new file.</p>
<p>You will need a infinite loop, I will suggest using a <code>while(true)</code> loop. You then need</p>
<pre><code>if(/*key was UP ARROW*/){
/*CODE TO MAKE MOVE FORWARD HERE*/
}else if(/*KEY WAS DOWN ARROW*/{
/*CODE TO MAKE MOVE DOWN HERE*/
} etc...
</code></... | 0 | 2016-09-17T20:17:09Z | [
"python",
"keyboard",
"raspberry-pi",
"control",
"keyboard-events"
] |
Are for-loop name list expressions legal? | 39,539,606 | <p>In CPython 2.7.10 and 3.4.3, and PyPy 2.6.0 (Python 2.7.9), it is apparently legal to use expressions (or some subset of them) for the name list in a for-loop. Here's a typical for-loop:</p>
<pre><code>>>> for a in [1]: pass
...
>>> a
1
</code></pre>
<p>But you can also use attributes from object... | 3 | 2016-09-16T20:25:32Z | 39,539,675 | <p>As <a href="https://docs.python.org/3/reference/compound_stmts.html#the-for-statement" rel="nofollow">documented</a>, the "variable" in the <code>for</code> syntax can be any <code>target_list</code>, which, as <a href="https://docs.python.org/3/reference/simple_stmts.html#grammar-token-target_list" rel="nofollow">a... | 1 | 2016-09-16T20:31:22Z | [
"python",
"language-lawyer"
] |
Are for-loop name list expressions legal? | 39,539,606 | <p>In CPython 2.7.10 and 3.4.3, and PyPy 2.6.0 (Python 2.7.9), it is apparently legal to use expressions (or some subset of them) for the name list in a for-loop. Here's a typical for-loop:</p>
<pre><code>>>> for a in [1]: pass
...
>>> a
1
</code></pre>
<p>But you can also use attributes from object... | 3 | 2016-09-16T20:25:32Z | 39,539,697 | <blockquote>
<p>Are these even supposed to work? </p>
</blockquote>
<p>Yes</p>
<blockquote>
<p>Is this an oversight? </p>
</blockquote>
<p>No</p>
<blockquote>
<p>Is this an implementation detail of CPython that PyPy happens to also
implement?</p>
</blockquote>
<p>No</p>
<hr>
<p>If you can assign to it, y... | 5 | 2016-09-16T20:32:57Z | [
"python",
"language-lawyer"
] |
google-app-engine fails to run Cron job and gives an ImportError: No module named gcloud | 39,539,611 | <p>app-engine fails to import gcloud
used gcloud app deploy app.yaml \cron.yaml to deploy on google app engine</p>
<p>opened on browser and get:</p>
<pre><code>Traceback (most recent call last):
File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
... | 0 | 2016-09-16T20:25:49Z | 39,715,633 | <p>All 3rd party packages need to be installed in the same directory as your app. Run this from the root directory of your application to install it.</p>
<pre><code>pip install gcloud -t .
</code></pre>
| 0 | 2016-09-27T03:46:28Z | [
"python",
"google-app-engine",
"cron",
"gcloud-python",
"google-cloud-python"
] |
Scipy/numpy: two dense, one sparse dot product | 39,539,640 | <p>Let's say we have a matrix <code>A</code> of size <code>NxN</code>, and <code>A</code> is sparse and <code>N</code> is very large. So we naturally want to store is as as scipy sparse matrix.</p>
<p>We also have a dense numpy array <code>q</code> of size <code>NxK</code>, where <code>K</code> is relatively smaller.<... | 0 | 2016-09-16T20:28:06Z | 39,540,895 | <p>So you have</p>
<pre><code>(k,N) * (N,N) * (N,k) => (k,k)
</code></pre>
<p>One of those dot product results in a dense array; that times another dense is also dense. With a multiplication like this you quickly loose the sparsity.</p>
<p>If <code>q</code> has a lot of 0s, and you want to preserve the sparse ma... | 0 | 2016-09-16T22:23:24Z | [
"python",
"arrays",
"numpy",
"matrix",
"scipy"
] |
Python Web-scraping Solution | 39,539,646 | <p>So, I'm new to python and am trying to develop an exercise in which I scrape the page numbers from a list on this url, which is a list of various published papers. </p>
<p>When I go into the HTML element for the page I want to scrape, I inspect the element and find this HTML code to match up:</p>
<pre><code><di... | 1 | 2016-09-16T20:28:31Z | 39,539,709 | <p>If I understand you correctly, you want the pages inside all divs with class="src"</p>
<p>If so, then you need to do:</p>
<pre><code>import requests
import re
from bs4 import BeautifulSoup
url = "http://www.jstor.org/action/doAdvancedSearch?c4=AND&c5=AND&q2=&pt=&q1=nuclear&f3=all&f1=all&am... | 1 | 2016-09-16T20:33:48Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Python Web-scraping Solution | 39,539,646 | <p>So, I'm new to python and am trying to develop an exercise in which I scrape the page numbers from a list on this url, which is a list of various published papers. </p>
<p>When I go into the HTML element for the page I want to scrape, I inspect the element and find this HTML code to match up:</p>
<pre><code><di... | 1 | 2016-09-16T20:28:31Z | 39,539,820 | <p>An alternative to Tales Pádua's <a href="http://stackoverflow.com/a/39539709/189134">answer</a> is this:</p>
<pre><code>from bs4 import BeautifulSoup
html = """<div class="src">
Foreign Affairs, Vol. 79, No. 4 (Jul. - Aug., 2000), pp. 53-63
</div>
<div class="src">
Other Book, Vol. 1, No... | 2 | 2016-09-16T20:44:00Z | [
"python",
"web-scraping",
"beautifulsoup"
] |
Random numbers- only length-1 arrays can be converted to Python scalars | 39,539,672 | <pre><code>from math import sin, cos, pi
import numpy as np
N=10
a=np.random.randint(0, 360+1, N)
print (a)
theta=a*pi/180
print(theta)
x=[cos(theta)]
print(x)
y=[sin(theta)]
print(y)
</code></pre>
<hr>
<pre><code>TypeError Traceback (most recent call last)
<ipython-input-47-632b... | -2 | 2016-09-16T20:31:03Z | 39,539,723 | <p>Try using <code>np.cos(theta)</code> instead of <code>cos(theta)</code>. Same goes for <code>sin</code>.</p>
<p>Only NumPy functions can be applied both to scalars and arrays. The regular <code>cos()</code> and <code>sin()</code> instead expect only scalar arguments, and fail in the example, as you try to apply the... | 1 | 2016-09-16T20:35:16Z | [
"python",
"arrays",
"numpy",
"random",
"polar-coordinates"
] |
Get image width from HTML code | 39,539,733 | <p>I can get the <code>width</code> attribute of an image using <code>BeautifulSoup</code> as follows:</p>
<pre><code>img = soup.find("img")
width = img["width"]
</code></pre>
<p>The problem is that <code>width</code> can be set in <code>CSS</code> file or not set at all.</p>
<p>I would like to extract the value wit... | 1 | 2016-09-16T20:36:23Z | 39,539,776 | <p>The quick answer is: you can't - the resultant size of an image is based on evaluation of CSS, and indeed JS. You'd need to do all that work in order to find your answer.</p>
<p>Another approach might be to use a real browser to do that work for you, and then ask it what the width is. See <a href="http://phantomjs.... | 2 | 2016-09-16T20:40:11Z | [
"python",
"selenium",
"web-scraping",
"beautifulsoup",
"phantomjs"
] |
Get image width from HTML code | 39,539,733 | <p>I can get the <code>width</code> attribute of an image using <code>BeautifulSoup</code> as follows:</p>
<pre><code>img = soup.find("img")
width = img["width"]
</code></pre>
<p>The problem is that <code>width</code> can be set in <code>CSS</code> file or not set at all.</p>
<p>I would like to extract the value wit... | 1 | 2016-09-16T20:36:23Z | 39,558,983 | <p>You can partially download image, only enough to get width/height through setting
Range in requests headers and use somehow variant of getimageinfo.py</p>
<p>Example usage:</p>
<pre><code>def check_is_small_pic(url, pic_size):
is_small = False
r_check = requests.get(url, headers={"Range": "50"})
image... | 2 | 2016-09-18T14:51:58Z | [
"python",
"selenium",
"web-scraping",
"beautifulsoup",
"phantomjs"
] |
defining a function without using ":" | 39,539,803 | <p>I have been asked to define a function which is called <code>avg</code>. <code>avg</code> should calculate the average of two lists with the same amount of numbers - take all the numbers from both lists and calculate their average.<br>
However, it is not allowed to use <code>:</code> nor more than one line (except <... | 1 | 2016-09-16T20:42:34Z | 39,539,964 | <p>If someone asked you a pointless question, I would just give him a pointless answer. He deserves it.</p>
<pre><code>import numpy # You said it doesn't count as a line
# Take the : from dict's docstring.
exec("avg = lambda lst1, lst2{} numpy.mean(lst1+lst2)".format(dict.__doc__[213]))
>>> avg([1,2,3], [1... | 7 | 2016-09-16T20:56:54Z | [
"python"
] |
defining a function without using ":" | 39,539,803 | <p>I have been asked to define a function which is called <code>avg</code>. <code>avg</code> should calculate the average of two lists with the same amount of numbers - take all the numbers from both lists and calculate their average.<br>
However, it is not allowed to use <code>:</code> nor more than one line (except <... | 1 | 2016-09-16T20:42:34Z | 39,540,361 | <p>You could use exec like in Bharel's answer but use the <code>chr(58)</code>:</p>
<pre><code>exec("avg = lambda lst1, lst2 " + chr(58) + " sum(lst1 + lst2, 0.) / (len(lst1) + len(lst2))")
print(avg([1,2,3], [4,5,6]))
</code></pre>
<p>Or if you really want to use numpy.mean:</p>
<pre><code>exec("avg = lambda lst1... | 1 | 2016-09-16T21:31:12Z | [
"python"
] |
defining a function without using ":" | 39,539,803 | <p>I have been asked to define a function which is called <code>avg</code>. <code>avg</code> should calculate the average of two lists with the same amount of numbers - take all the numbers from both lists and calculate their average.<br>
However, it is not allowed to use <code>:</code> nor more than one line (except <... | 1 | 2016-09-16T20:42:34Z | 39,540,519 | <p>Speaking of ridiculous, I suggest:</p>
<pre><code>>>> exec(''.join(map(chr, [100, 101, 102, 32, 97, 118, 103, 40, 108, 115, 116, 49, 44, 32, 108, 115, 116, 50, 41, 58, 32, 114, 101,116, 117, 114, 110, 32, 48, 46, 53, 32, 42, 32, 115, 117, 109, 40, 108, 115, 116, 49, 32, 43, 32, 108, 115, 116, 50, 41, 32, 4... | 3 | 2016-09-16T21:46:28Z | [
"python"
] |
Read CSV and replace a column based on keyword list | 39,539,868 | <p>I'm new to Python and would appreciate some help on how to approach this problem. Here's what I'm trying to do:</p>
<ol>
<li>Read a CSV file with a list of transactions. Each row has 6 columns.</li>
<li><p>For each row, compare the <code>DESCRIPTION</code> column to a list of keywords to see if any word matches on... | 2 | 2016-09-16T20:47:52Z | 39,540,147 | <p>i find that the <strong>pandas</strong> library works great for this type of stuff. i'm sure that the find_cat def could be sped up a bit, but wanted to get the idea of the search & substitution applied to a column communicated.</p>
<pre><code>import pandas as pd
def find_cat(desc, cat_dict):
cat_list = ... | 0 | 2016-09-16T21:12:43Z | [
"python",
"csv"
] |
Are user defined functions callable? | 39,539,914 | <p>I am not a very experience programmer. Please can you tell me why this code gives me the error message:</p>
<p>error: quad: first argument is not callable</p>
<p>code:</p>
<pre><code>from matplotlib import pyplot as plt
import numpy as np
import scipy.integrate as integrate
def parabola(x, a):
return a+x**2
... | 0 | 2016-09-16T20:52:04Z | 39,539,948 | <p>There are two problems in your code:</p>
<p>1) you call the function <code>parabola()</code>. Instead, pass it as an argument to <code>integrate</code>.</p>
<p>2) <code>parabola()</code> is a two argument function. <code>integrate</code> expects a single-argument function.</p>
<p>To solve the second problem, you ... | 3 | 2016-09-16T20:55:27Z | [
"python",
"numpy"
] |
Are user defined functions callable? | 39,539,914 | <p>I am not a very experience programmer. Please can you tell me why this code gives me the error message:</p>
<p>error: quad: first argument is not callable</p>
<p>code:</p>
<pre><code>from matplotlib import pyplot as plt
import numpy as np
import scipy.integrate as integrate
def parabola(x, a):
return a+x**2
... | 0 | 2016-09-16T20:52:04Z | 39,540,508 | <p>Try:</p>
<pre><code>int1=integrate.quad(parabola, -5, 5, args=(2,))
</code></pre>
<p>The <code>quad</code> signature is:</p>
<pre><code>quad(func, a, b, args=(), ...)
</code></pre>
<p>the function, lower range, upper range, args_to_pass through, etc.</p>
| 1 | 2016-09-16T21:44:37Z | [
"python",
"numpy"
] |
What's the difference between True and False in python grammar? | 39,540,014 | <p>I'm reading <a href="https://docs.python.org/3/reference/grammar.html" rel="nofollow">the python language specification</a> and found there's a <code>None</code>,
<code>True</code>, and <code>False</code> token. I can understand the difference between <code>None</code> and
<code>False</code> since <code>None</code> ... | 0 | 2016-09-16T21:01:20Z | 39,540,098 | <p>This is a formalization of the fact that <code>True</code> and <code>False</code> are special names in python3: you can't assign to them. </p>
<p>The reason that they aren't BOOLEAN is simply that boolean isn't a <a href="https://docs.python.org/3/library/token.html" rel="nofollow">valid token</a> for the parser. ... | 2 | 2016-09-16T21:08:51Z | [
"python"
] |
What's the difference between True and False in python grammar? | 39,540,014 | <p>I'm reading <a href="https://docs.python.org/3/reference/grammar.html" rel="nofollow">the python language specification</a> and found there's a <code>None</code>,
<code>True</code>, and <code>False</code> token. I can understand the difference between <code>None</code> and
<code>False</code> since <code>None</code> ... | 0 | 2016-09-16T21:01:20Z | 39,540,115 | <pre><code>atom: ('(' [yield_expr|testlist_comp] ')' |
'[' [testlist_comp] ']' |
'{' [dictorsetmaker] '}' |
NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')
</code></pre>
<p><code>NAME</code>, <code>NUMBER</code>, and <code>STRING</code> are tokens representing three classes of tokens.... | 3 | 2016-09-16T21:10:09Z | [
"python"
] |
What's the difference between True and False in python grammar? | 39,540,014 | <p>I'm reading <a href="https://docs.python.org/3/reference/grammar.html" rel="nofollow">the python language specification</a> and found there's a <code>None</code>,
<code>True</code>, and <code>False</code> token. I can understand the difference between <code>None</code> and
<code>False</code> since <code>None</code> ... | 0 | 2016-09-16T21:01:20Z | 39,540,127 | <p>Presumably from the reference to which you linked you are referring to the grammatical production</p>
<pre><code>atom: ('(' [yield_expr|testlist_comp] ')' |
'[' [testlist_comp] ']' |
'{' [dictorsetmaker] '}' |
NAME | NUMBER | STRING+ | '...' | 'None' | 'True' | 'False')
</code></pre>
<p>This s... | 1 | 2016-09-16T21:10:54Z | [
"python"
] |
How to add a subject to an email being sent with gmail? | 39,540,043 | <p>I am trying to send an email using GMAIL with a subject and a message. I have succeeded in sending an email using GMAIL without the implementation of <code>subject</code> and have also been able to receieve the email. However whenever I try to add a subject the program simply does not work.</p>
<pre><code>import sm... | 0 | 2016-09-16T21:03:32Z | 39,540,105 | <p>The call to <code>smtplib.SMTP.sendmail()</code> does not take a <code>subject</code> parameter. See <a href="https://docs.python.org/2/library/smtplib.html#smtplib.SMTP.sendmail" rel="nofollow">the doc</a> for instructions on how to call it.</p>
<p>Subject lines, along with all other headers, are included as part ... | 3 | 2016-09-16T21:09:36Z | [
"python",
"python-2.7",
"email",
"gmail",
"subject"
] |
How to add a subject to an email being sent with gmail? | 39,540,043 | <p>I am trying to send an email using GMAIL with a subject and a message. I have succeeded in sending an email using GMAIL without the implementation of <code>subject</code> and have also been able to receieve the email. However whenever I try to add a subject the program simply does not work.</p>
<pre><code>import sm... | 0 | 2016-09-16T21:03:32Z | 39,546,304 | <p>Or just use a package like <a href="https://github.com/kootenpv/yagmail" rel="nofollow">yagmail</a>. Disclaimer: I'm the maintainer.</p>
<pre><code>import yagmail
yag = yagmail.SMTP("email.gmail.com", "password")
yag.send("email1.gmail.com", "subject", "contents")
</code></pre>
<p>Install with <code>pip install ya... | 0 | 2016-09-17T11:28:02Z | [
"python",
"python-2.7",
"email",
"gmail",
"subject"
] |
MySQLdb Executemany error | 39,540,086 | <p>I'm having issues with executemany returning the following error</p>
<pre><code>(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IBM'',''1998-01-02 09:30:00'',''104.5'',''104.5'',''104.5'',''104.5'',''67000'')' at line 2")... | 0 | 2016-09-16T21:08:01Z | 39,540,295 | <p>What you do in the for loop is wrong.
You are formatting query as string with <code>sql_statement = sql%record</code>, this is not the correct way.
You are constructing a query, this is what you are using MySQLdb for.</p>
<p>What you need to do is the following:</p>
<pre><code># remove quotes from the query
sql =... | 0 | 2016-09-16T21:25:10Z | [
"python",
"mysql-python"
] |
MySQLdb Executemany error | 39,540,086 | <p>I'm having issues with executemany returning the following error</p>
<pre><code>(1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IBM'',''1998-01-02 09:30:00'',''104.5'',''104.5'',''104.5'',''104.5'',''67000'')' at line 2")... | 0 | 2016-09-16T21:08:01Z | 39,540,446 | <p>The problem is in <code>sql</code> query, you added quotes to <code>%s</code> (remove them): </p>
<pre><code>sql = """INSERT ... VALUES(%s, %s, %s, %s, %s, %s, %s)
</code></pre>
| 0 | 2016-09-16T21:39:04Z | [
"python",
"mysql-python"
] |
checking non-ambiguity of strides in numpy array | 39,540,102 | <p>For a numpy array <code>X</code>, the location of its element <code>X[k[0], ..., k[d-1]]</code> is offset from the location of <code>X[0,..., 0]</code> by <code>k[0]*s[0] + ... + k[d-1]*s[d-1]</code>, where <code>(s[0],...,s[d-1])</code> is the tuple representing <code>X.strides</code>.</p>
<p>As far as I understan... | 2 | 2016-09-16T21:09:09Z | 39,540,641 | <p>edit: It took me a bit to figure what you are asking about. With striding tricks it's possible to index the same element in a databuffer in different ways, and broadcasting actually does this under the covers. Normally we don't worry about it because it is either hidden or intentional.</p>
<p>Recreating in the str... | 2 | 2016-09-16T21:57:17Z | [
"python",
"numpy"
] |
checking non-ambiguity of strides in numpy array | 39,540,102 | <p>For a numpy array <code>X</code>, the location of its element <code>X[k[0], ..., k[d-1]]</code> is offset from the location of <code>X[0,..., 0]</code> by <code>k[0]*s[0] + ... + k[d-1]*s[d-1]</code>, where <code>(s[0],...,s[d-1])</code> is the tuple representing <code>X.strides</code>.</p>
<p>As far as I understan... | 2 | 2016-09-16T21:09:09Z | 39,752,690 | <p>It turns out this test is already implemented in numpy, see <a href="https://github.com/numpy/numpy/blob/master/numpy/core/src/private/mem_overlap.c#L842" rel="nofollow">mem_overlap.c:842</a>.</p>
<p>The test is exposed as <code>numpy.core.multiarray_tests.internal_overlap(x)</code>. </p>
<p>Example:</p>
<pre><co... | 2 | 2016-09-28T16:12:48Z | [
"python",
"numpy"
] |
What does dis.findlabels() do? | 39,540,128 | <p>I was playing around with the <code>dis</code> library to gather information about a function (like what other functions it called). The documentation for <a href="https://docs.python.org/2/library/dis.html#dis.findlabels" rel="nofollow"><code>dis.findlabels</code></a> sounds like it would return other function cal... | 0 | 2016-09-16T21:10:57Z | 39,540,245 | <p>The jump targets are annotated by <code>>></code> in disassembly output.</p>
<p>For example, in:</p>
<pre><code>def f(i):
if i == 1:
return 1
elif i == 2:
return 2
</code></pre>
<p><code>dis.dis(f)</code> shows:</p>
<pre><code> 2 0 LOAD_FAST 0 (i)
... | 1 | 2016-09-16T21:20:45Z | [
"python"
] |
What does dis.findlabels() do? | 39,540,128 | <p>I was playing around with the <code>dis</code> library to gather information about a function (like what other functions it called). The documentation for <a href="https://docs.python.org/2/library/dis.html#dis.findlabels" rel="nofollow"><code>dis.findlabels</code></a> sounds like it would return other function cal... | 0 | 2016-09-16T21:10:57Z | 39,540,261 | <p>For example, this function has one jump:</p>
<pre><code>def f(x):
if x > 0: # This will jump to "return 2" if not x > 0
return 1
else:
return 2
</code></pre>
<p>See it here:</p>
<pre><code>>>> dis.disco(f.__code__)
2 0 LOAD_FAST 0 (x)
... | 2 | 2016-09-16T21:22:21Z | [
"python"
] |
Selenium Python StaleElementReferenceException | 39,540,160 | <p>I'm trying to download all the pdf on a webpage using Selenium Python with Chrome as browser but every time the session ends with this message:</p>
<pre><code>StaleElementReferenceException: stale element reference: element is not attached to the page document
(Session info: chrome=52.0.2743.116)
(Driver info: ... | 1 | 2016-09-16T21:14:10Z | 39,540,710 | <p>You get stale element when you search for an element and before doing any action on it the page has changed/reloaded.</p>
<p>Make sure the page is fully loaded before doing any actions in the page.</p>
<p>So you need to add first a condition to wait for the page to be loaded an maybe check all requests are done.</... | 0 | 2016-09-16T22:02:46Z | [
"python",
"google-chrome",
"selenium"
] |
Selenium Python StaleElementReferenceException | 39,540,160 | <p>I'm trying to download all the pdf on a webpage using Selenium Python with Chrome as browser but every time the session ends with this message:</p>
<pre><code>StaleElementReferenceException: stale element reference: element is not attached to the page document
(Session info: chrome=52.0.2743.116)
(Driver info: ... | 1 | 2016-09-16T21:14:10Z | 39,542,565 | <p>As soon as you call <code>self.driver.get()</code> in your loop, all the other elements in the list of elements will become stale. Try collecting the <code>href</code> attributes from the elements first, and then visiting them:</p>
<pre><code>def download_pdf(self):
current = self.driver.current_url
lista_l... | 0 | 2016-09-17T03:28:26Z | [
"python",
"google-chrome",
"selenium"
] |
How can I create unique non-repeating pair combinations from a list | 39,540,161 | <p>I am new to computer programming. </p>
<p>I want to create successive 2-person teams from an even numbered list of players (32 max) but with no repeats until all possible teams have been formed. </p>
<p>For example for 6 players (a thru f) I can generate with itertools.combinations 15 distinct teams. Then I can ... | -3 | 2016-09-16T21:14:26Z | 39,540,410 | <p>If all you need is <em>some</em> complete round-robin pairing, then look up solutions with "round-robin tournament schedule". You can likely just use the long-known solution illustrated well on <a href="https://en.wikipedia.org/wiki/Round-robin_tournament" rel="nofollow">Wikipedia</a>.</p>
<p>List the players in t... | 0 | 2016-09-16T21:35:25Z | [
"python",
"itertools"
] |
How can I create unique non-repeating pair combinations from a list | 39,540,161 | <p>I am new to computer programming. </p>
<p>I want to create successive 2-person teams from an even numbered list of players (32 max) but with no repeats until all possible teams have been formed. </p>
<p>For example for 6 players (a thru f) I can generate with itertools.combinations 15 distinct teams. Then I can ... | -3 | 2016-09-16T21:14:26Z | 39,622,880 | <p>Here's a typical scenario of what I'm trying to accomplish:
Roster of about 26 players
Week 1: 18 of 26 show up. I form 9 teams
Week 2: 22 of 26 show up. I form 11 teams but no repeats from Week 1
Week 3: 10 of 26 show up. I form 5 teams but no repeats from Week 1 or Week 2, etc.</p>
<p>The following works, albeit ... | 0 | 2016-09-21T17:23:00Z | [
"python",
"itertools"
] |
django runserver can't find django | 39,540,328 | <p>I'm creating a Django application and I've compiled my own Python then used buildout to manage my dependencies.</p>
<p>I'm at the point where I want to run manage.py runserver but I can get an ImportError for django</p>
<p>Digging a little deeper it appears that actually it can find django - if I just run manage.p... | 0 | 2016-09-16T21:27:34Z | 39,553,888 | <p>So, I think I figured it out. I found a file called django-admin.py in my buildout's bin directory, which eventually led me to add a django section to my buildout.cfg (see <a href="https://pypi.python.org/pypi/djangorecipe" rel="nofollow">https://pypi.python.org/pypi/djangorecipe</a> for details).</p>
<p>This creat... | 0 | 2016-09-18T03:48:21Z | [
"python",
"django",
"buildout"
] |
python absolute import of submodule fails | 39,540,417 | <p>I have seen other posts but did not find answer that worked!</p>
<p>File structure</p>
<pre><code>my_package/
__init__.py -- empty
test/
__init__.py -- empty
test1.py
</code></pre>
<p>Fail</p>
<pre><code>from my_package import test
test.test1
</code></pre>
<p>gives </p>
... | 1 | 2016-09-16T21:35:53Z | 39,541,206 | <p>When you import a package (like <code>test</code>), the modules (like <code>test1</code>) are not automatically imported (unless perhaps you put some special code to do so in <code>__init__.py</code>). This is different from importing a module, where the contents of the module are available in the modules namespace.... | 0 | 2016-09-16T23:05:33Z | [
"python",
"python-2.7",
"import",
"package",
"python-import"
] |
approximate summation of exponential function in python | 39,540,442 | <p>I wish to find the approximate sum of exponential function , my code looks like this:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
import math
N = input ("Please enter an integer at which term you want to turncate your summation")
x = input ("please enter a number for which you want to run the... | 0 | 2016-09-16T21:38:30Z | 39,540,556 | <p>Which version of python are you using? The division that finds <code>nth_term</code> gives different results in python 2.x and in version 3.x.</p>
<p>It seems like you are using version 2.x. The division you use gives only integer results, so after the first two lines loops (1/factorial(0) + 1/factorial(1)) you are... | 1 | 2016-09-16T21:48:54Z | [
"python",
"exp"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.