title stringlengths 12 150 | question_id int64 469 40.1M | question_score int64 2 5.52k | question_date stringdate 2008-08-02 15:11:16 2016-10-18 06:16:31 | answer_id int64 536 40.1M | answer_score int64 7 8.38k | answer_date stringdate 2008-08-02 18:49:07 2016-10-18 06:19:33 | tags listlengths 1 5 | question_body_md stringlengths 15 30.2k | answer_body_md stringlengths 11 27.8k |
|---|---|---|---|---|---|---|---|---|---|
beginner installing nosetests package | 9,270,188 | 7 | 2012-02-14T00:40:04Z | 15,148,328 | 7 | 2013-03-01T00:29:30Z | [
"python",
"terminal",
"install",
"nosetests"
] | I'm trying to install the following as per the learnpythonthehardway tutorial:
1. pip from <http://pypi.python.org/pypi/pip>
2. distribute from <http://pypi.python.org/pypi/distribute>
3. nose from <http://pypi.python.org/pypi/nose/>
4. virtualenv from <http://pypi.python.org/pypi/virtualenv>
I've visited these links... | This works on mac, it may work on linux
1)Open terminal (Be prepared to enter your password)
2)Type: `sudo easy_install pip`
3)Type: `sudo pip install distribute`
4)Type: `sudo pip install nose`
5)Type: `sudo pip install virtualenv`
Hope that helps, cheers! |
Python - SSL Issue with Oauth2 | 9,270,195 | 13 | 2012-02-14T00:40:59Z | 9,271,040 | 8 | 2012-02-14T02:49:48Z | [
"python",
"ssl",
"oauth",
"certificate",
"ssl-certificate"
] | I seem to be having an issue with SSL whenever trying to use oAuth2 in Python. I've spent most of the afternoon attempting to debug it but can't seem to figure it out.
Here's my Python Script (Nice and simple):
```
import oauth2.oauth2 as oauth
import urlparse
import time
## If you're actually processing requests, y... | `cacerts.txt` contains too few CAs. If you replace it with [cacert.pem](https://curl.haxx.se/ca/cacert.pem) then there is no ssl error. Here's a test script:
```
#!/usr/bin/env python3
import http.client
import ssl
####context = ssl.create_default_context(cafile='cacerts.txt') # ssl.SSLError
####context = ssl.create_... |
Python list in a function in a class | 9,270,352 | 2 | 2012-02-14T01:02:27Z | 9,270,375 | 8 | 2012-02-14T01:05:44Z | [
"python",
"list",
"class",
"function"
] | I'm trying to print the list created by the functions in this class- what do I need to fix? I'm getting output from the terminal along the lines of `[<__main__.Person instance at 0x1004a0320>,`.
```
class Person:
def __init__(self,first,last,id,email):
self.firstName=first
self.lastName=last
... | You need to define `__repr__` or `__str__` in your `Person` class.
```
>>> class Person:
... def __init__(self,first,last,id,email):
... self.firstName=first
... self.lastName=last
... self.id=id
... self.email=email
... self.friends=[]
... def add_friend(self,friend):
.... |
How to pull out CSS attributes from inline styles with BeautifulSoup | 9,271,365 | 6 | 2012-02-14T03:37:28Z | 9,271,635 | 7 | 2012-02-14T04:18:31Z | [
"python",
"css",
"inline",
"beautifulsoup"
] | I have something like this:
```
<img style="background:url(/theRealImage.jpg) no-repate 0 0; height:90px; width:92px;") src="notTheRealImage.jpg"/>
```
I am using beautifulsoup to parse the html. Is there away to pull out the "url" in the "background" css attribute? | You've got a couple options- quick and dirty or the Right Way. The quick and dirty way (which will break easily if the markup is changed) looks like
```
>>> from BeautifulSoup import BeautifulSoup
>>> import re
>>> soup = BeautifulSoup('<html><body><img style="background:url(/theRealImage.jpg) no-repate 0 0; height:90... |
what does the __file__ wildcard mean/do? | 9,271,464 | 31 | 2012-02-14T03:52:35Z | 9,271,479 | 41 | 2012-02-14T03:55:19Z | [
"python"
] | ```
A = os.path.join(os.path.dirname(__file__), '..')
B = os.path.dirname(os.path.realpath(__file__))
C = os.path.abspath(os.path.dirname(__file__))
```
I usually just hardwire these with the actual path. But there is a reason for these statements that determine path at runtime, and I would really like to understant... | When a module is loaded in Python, `__file__` is set to its name. You can then use that with other functions to find the directory that the file is located in.
Taking your examples one at a time:
```
A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.
... |
what does the __file__ wildcard mean/do? | 9,271,464 | 31 | 2012-02-14T03:52:35Z | 9,271,617 | 22 | 2012-02-14T04:16:32Z | [
"python"
] | ```
A = os.path.join(os.path.dirname(__file__), '..')
B = os.path.dirname(os.path.realpath(__file__))
C = os.path.abspath(os.path.dirname(__file__))
```
I usually just hardwire these with the actual path. But there is a reason for these statements that determine path at runtime, and I would really like to understant... | I just want to address some confusion first. `__file__` is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.
<http://docs.python.org/reference/datamodel.html> shows many of the special methods and attributes, if not all... |
Python: Running Daemon Processes in Windows7 | 9,271,525 | 5 | 2012-02-14T04:04:06Z | 9,274,957 | 10 | 2012-02-14T10:02:04Z | [
"python",
"windows"
] | I had a program that Scraped certain data from certain Web-Pages, and when the Web-Pages changed, acted accordingly.
How would one set up the program so it continues to run in the background?
I don't need *any* specifics
I'm just really confused on this concept and would appreciate whatever help anybody has to offer... | `start path-to-pythonw.exe your-code.py`
pythonw means without console.
start means start on background.
if your python is installed system-wide, you can probably `start your-code.pyw`
`.pyw` is associated with `pythonw.exe`
remember you cannot use print (to stdout) in this case. |
Difference Between Multiple If's and Elif's Python | 9,271,712 | 23 | 2012-02-14T04:29:10Z | 9,271,755 | 38 | 2012-02-14T04:34:19Z | [
"python",
"if-statement"
] | In python, is there a difference between say:
```
if text == 'sometext':
print(text)
if text == 'nottext':
print("notanytext")
```
and
```
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
```
Just wondering if multiple ifs could cause any unwanted problems and... | Multiple if's means your code would go and check all the if conditions, where as in case of elif, if one if condition satisfies it would not check other conditions.. |
Difference Between Multiple If's and Elif's Python | 9,271,712 | 23 | 2012-02-14T04:29:10Z | 16,287,793 | 17 | 2013-04-29T20:37:40Z | [
"python",
"if-statement"
] | In python, is there a difference between say:
```
if text == 'sometext':
print(text)
if text == 'nottext':
print("notanytext")
```
and
```
if text == 'sometext':
print(text)
elif text == 'nottext':
print("notanytext")
```
Just wondering if multiple ifs could cause any unwanted problems and... | An other easy way to see the difference between the use of if and elif is this example here:
```
def analyzeAge( age ):
if age < 21:
print "You are a child"
if age > 21:
print "You are an adult"
else: #Handle all cases were 'age' is negative
print "The age must be a positive integer!"
... |
How do I find an open port in Linux? | 9,272,051 | 3 | 2012-02-14T05:14:12Z | 9,272,129 | 11 | 2012-02-14T05:24:03Z | [
"python",
"linux",
"unix",
"networking",
"tcp"
] | Is there some kind of system call that will return whether a port is available? Or at least a conventional way to do it that doesn't make your process a bad citizen?
At the moment this is how I'm doing it:
```
def find_open_port(min_port, max_port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
for po... | The simplest way that I know of to check if a particular port is available is to try and bind to it or try to connect to it (if you want TCP). If the bind (or connect) succeeds, it was available (is in use).
However, if you simply want *any* open port, you can bind to port 0, and the opperating system will assign you ... |
How can I send email using Python? | 9,272,257 | 8 | 2012-02-14T05:40:01Z | 9,274,387 | 14 | 2012-02-14T09:22:40Z | [
"python",
"email",
"smtplib"
] | I am writing a program that sends an email using Python. What I have learned from various forums is the following piece of code:
```
#!/usr/bin/env python
import smtplib
sender = "sachinites@gmail.com"
receivers = ["abhisheks@cse.iitb.ac.in"]
yourname = "Abhishek Sagar"
recvname = "receptionist"
sub = "Testing email"
... | If message headers, payload contain non-ascii characters then they should be encoded:
```
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from email.header import Header
from email.mime.text import MIMEText
from getpass import getpass
from smtplib import SMTP_SSL
login, password = 'user@gmail.com', ... |
python fabric logging | 9,273,280 | 14 | 2012-02-14T07:37:06Z | 9,273,493 | 13 | 2012-02-14T08:01:35Z | [
"python",
"logging",
"fabric"
] | I came across fabric modules - Its really cool. It works well for me. Now I have an issue ,how to collect output from fabric script?
```
# cat fabfile.py
from fabric.api import *
from fabric.contrib.console import confirm
env.hosts = ['localhost' , '172.16.10.112','172.16.10.106']
env.user='testuser'
env.password = '... | It looks like `fabric` itself doesn't use `logging`.
[Issue#57](https://github.com/fabric/fabric/issues/57) is already opened regarding that, but I'm afraid that until it's fixed you'll need to stick to redirection or have a look at some of the branches in github with changes to do that:
* [tswicegood/fabric](https:/... |
What's the right approach for calling functions after a flask app is run? | 9,276,078 | 9 | 2012-02-14T11:31:23Z | 23,035,786 | 21 | 2014-04-12T20:29:57Z | [
"python",
"web-frameworks",
"flask",
"werkzeug"
] | I'm a little confused about how to do something that I thought would be quite simple. I have a simple app written using `Flask`. It looks something like this:
```
from flask import Flask
app = Flask(__name__)
def _run_on_start(a_string):
print "doing something important with %s" % a_string
@app.route('/')
def r... | Probably you were looking for `Flask.before_first_request` decorator, as in:
```
@app.before_first_request
def _run_on_start(a_string):
print "doing something important with %s" % a_string
``` |
What exception class to use for file parsing error? | 9,276,663 | 8 | 2012-02-14T12:13:13Z | 9,276,687 | 9 | 2012-02-14T12:14:52Z | [
"python",
"exception"
] | I'm writing a parser for a certain file format. If a file is not correctly formatted (and can not be parsed) then the parser throws an exception.
What exception class, in the Python 2 exception hierarchy, should I use? | How about
```
class XyzParseError(Exception):
pass
```
where `XyzParser` is the name of your parser class? That's also what [`HTMLParser`](http://docs.python.org/library/htmlparser.html#HTMLParser.HTMLParseError) in the standard library does. |
How do I make sprites move evenly on all computers in Pygame & Python | 9,276,790 | 3 | 2012-02-14T12:22:25Z | 9,276,904 | 8 | 2012-02-14T12:31:50Z | [
"python",
"multithreading",
"sprite",
"pygame",
"python-multithreading"
] | I'm having a problem with evenly moving sprites; Currently I'm using a while loop to move them, the problem with this being the faster the computer, the faster the loop goes and the faster the sprites move. I have tried the timer / clock function (wait?) in pygame and it freezes the cursor while it waits, therefore mai... | You're dependent of the framerate, faster the framerate is, faster your movement will be.
Usually, we are calculating the time between 2 frames/loop iteration, and we called it the "delta time". Then we multiply that delta time to the movement vector.
Here is a loop sample:
```
clock = pygame.time.Clock()
while True... |
Multilevel relative import | 9,277,200 | 15 | 2012-02-14T12:52:56Z | 9,277,493 | 12 | 2012-02-14T13:14:45Z | [
"python",
"import",
"module",
"relative"
] | Multilevel relative import
I have following folder structure
```
top\
__init__.py
util\
__init__.py
utiltest.py
foo\
__init__.py
foo.py
bar\
__init__.py
foobar.py
```
I want to access from `foobar.py` the module `utiltest.py`. I tried following relative import... | You must import `foobar` from the parent folder of `top`:
```
import top.foo.bar.foobar
```
This tells Python that `top` is the top level package. Relative imports are possible only inside a package. |
Does Python have anything like Ruby's Fog? | 9,277,532 | 4 | 2012-02-14T13:16:57Z | 9,277,622 | 8 | 2012-02-14T13:23:07Z | [
"python",
"ruby",
"cloud",
"fog"
] | Read about Fog: <http://fog.io>
Does Python have anything like it? (a library for cloud services.)
Does it need one? | I've only just looked at the Fog website, but it reminds me of [Apache Libcloud](http://libcloud.apache.org/). |
Django: Accessing Logged in User when specifying Generic View in urlpatterns | 9,279,753 | 3 | 2012-02-14T15:41:56Z | 9,280,052 | 13 | 2012-02-14T16:00:13Z | [
"python",
"django",
"django-views"
] | I have a model that looks like this:
```
from django.db import models
from django.contrib.auth.models import User
class Application(models.Model):
STATUS_CHOICES = (
(u'IP',u'In Progress'),
(u'C',u'Completed'))
status = models.CharField(max_length=2 ,choices=STATUS_CHOICES, defau... | You can't filter on the user in your `urls.py`, because you don't know the user when the urls are loaded.
Instead, subclass `ListView` and override the `get_queryset` method to filter on the logged in user.
```
class PendingApplicationView(ListView):
def get_queryset(self):
return Application.objects.filt... |
Matplotlib python show() returns immediately | 9,280,171 | 26 | 2012-02-14T16:06:58Z | 9,280,538 | 16 | 2012-02-14T16:31:01Z | [
"python",
"matplotlib"
] | I have a simple python script which plots some graphs in the same figure. All graphs are created by the draw() and in the end I call the show() function to block.
The script used to work with Python 2.6.6, Matplotlib 0.99.3, and Ubuntu 11.04. Tried to run it under Python 2.7.2, Matplotlib 1.0.1, and Ubuntu 11.10 but t... | I think that using `show(block=True)` should fix your problem. |
Matplotlib python show() returns immediately | 9,280,171 | 26 | 2012-02-14T16:06:58Z | 11,364,849 | 27 | 2012-07-06T15:07:47Z | [
"python",
"matplotlib"
] | I have a simple python script which plots some graphs in the same figure. All graphs are created by the draw() and in the end I call the show() function to block.
The script used to work with Python 2.6.6, Matplotlib 0.99.3, and Ubuntu 11.04. Tried to run it under Python 2.7.2, Matplotlib 1.0.1, and Ubuntu 11.10 but t... | I had this same problem, and it was caused by calling `show()` on the Figure object instead of the pyplot object.
Incorrect code. Causes the graph to flash on screen for a brief instant:
```
import matplotlib.pyplot as plt
x = [1,2,3]
y = [5,6,7]
fig = plt.figure()
plt.plot(x, y)
fig.show()... |
Error: SMTPRecipientsRefused 553, '5.7.1 #while working on contact form in django | 9,281,334 | 5 | 2012-02-14T17:22:33Z | 9,281,548 | 7 | 2012-02-14T17:36:01Z | [
"python",
"django",
"smtp",
"sendmail"
] | im trying to make a contact form in django 1.3, python 2.6.
Whats the reason of following error?
error:
```
SMTPRecipientsRefused at /contact/
{'test@test.megiteam.pl': (553, '5.7.1 <randomacc@hotmail.com>: Sender address
rejected: not owned by user test@test.megiteam.pl')}
```
my settings.py:
```
EMAIL_HOST = 'te... | The explanation is in the error message. Your email host is rejecting the email because of the sender address `randomacc@hotmail.com` that you have taken from the contact form.
Instead, you should use your own email address as the sender address. You can then set a `Reply-To` header so that replies go to your user.
`... |
Get longest element in Dict | 9,281,788 | 3 | 2012-02-14T17:54:57Z | 9,281,817 | 8 | 2012-02-14T17:57:28Z | [
"python",
"dictionary"
] | I store data in dictionary, where key is an integer, and value is a tuple of integers.
I need to get the length of the longest element, and its key.
I found this for getting the max value over dict:
```
def GetMaxFlow(flows):
maks=max(flows, key=flows.get)
return flows[maks],maks
```
I tried to modif... | This is one of the reasons `lambda` still exists in Python I think.
```
def GetMaxFlow(flows):
maks=max(flows, key=lambda k: len(flows[k]))
return flows[maks],maks
```
To specifically return a len...
```
def GetMaxFlow(flows):
maks=max(flows, key=lambda k: len(flows[k]))
return len(fl... |
Making Django go green | 9,282,628 | 10 | 2012-02-14T19:01:56Z | 9,310,782 | 10 | 2012-02-16T11:50:34Z | [
"python",
"django",
"coroutine",
"gevent",
"greenlets"
] | I have a Django management command that makes thousands of TCP/UDP requests. I've used Gevent to speed this up as I've restructured my code to work as coroutines. The socket connections no longer block but from what I've read, parts of Django still aren't green. (By green, I mean using greenlets.)
Could you tell me wh... | The gevent monkey patcher will patch the standard library to be Greenlet friendly. This should take of a lot of common Django calls.
```
from gevent import monkey; monkey.patch_all()
```
As far as databases, normally the interfaces are blocking. If you use PostgreSQL look into [psyco\_gevent](https://bitbucket.org/de... |
How to open a file using the open with statement | 9,282,967 | 56 | 2012-02-14T19:26:53Z | 9,283,003 | 10 | 2012-02-14T19:29:39Z | [
"python",
"file",
"python-3.x",
"file-io",
"io"
] | I'm trying to learn Python using a number of tutorials. I currently looking at file input and output. I've written the following code to read a list of names (one per line) from a file into another file while checking a name against the names in the file and appending text to the occurrences in the file. The code works... | Use nested blocks like this,
```
with open(newfile, 'w') as outfile:
with open(oldfile, 'r', encoding='utf-8') as infile:
#your logic goes here
``` |
How to open a file using the open with statement | 9,282,967 | 56 | 2012-02-14T19:26:53Z | 9,283,052 | 117 | 2012-02-14T19:33:29Z | [
"python",
"file",
"python-3.x",
"file-io",
"io"
] | I'm trying to learn Python using a number of tutorials. I currently looking at file input and output. I've written the following code to read a list of names (one per line) from a file into another file while checking a name against the names in the file and appending text to the occurrences in the file. The code works... | Python allows putting multiple `open()` statements in a single `with`. You comma-separate them. Your code would then be:
```
def filter(txt, oldfile, newfile):
'''\
Read a list of names from a file line by line into an output file.
If a line begins with a particular name, insert a string of text
after ... |
Python bidirectional mapping | 9,282,997 | 3 | 2012-02-14T19:29:12Z | 9,283,467 | 8 | 2012-02-14T20:07:15Z | [
"python",
"mapping"
] | I'm not sure what to call what I'm looking for; so if I failed to find this question else where, I apologize. In short, I am writing python code that will interface directly with the Linux kernel. Its easy to get the required values from include header files and write them in to my source:
```
IFA_UNSPEC = 0
IFA_... | If you want to use two dicts, you can try this to create the inverted dict:
```
b = {v: k for k, v in a.iteritems()}
``` |
supplemental codepoints to unicode string in python | 9,284,199 | 3 | 2012-02-14T21:08:50Z | 13,436,167 | 8 | 2012-11-18T00:13:44Z | [
"python",
"unicode",
"python-2.x",
"supplementary"
] | `unichr(0x10000)` fails with a `ValueError` when cpython is compiled without `--enable-unicode=ucs4`.
Is there a language builtin or core library function that converts an arbitrary unicode scalar value or code-point to a `unicode` string that works regardless of what kind of python interpreter the program is running ... | Yes, here you go:
```
>>> unichr(0xd800)+unichr(0xdc00)
u'\U00010000'
```
The crucial point to understand is that `unichr()` converts an integer to a single code unit in the Python interpreter's string encoding. The [The Python Standard Library documentation for 2.7.3, *2. Built-in Functions*, on `unichr()`](http://d... |
Change matplotlib line style mid-graph | 9,284,877 | 9 | 2012-02-14T22:04:32Z | 9,285,779 | 13 | 2012-02-14T23:27:59Z | [
"python",
"styles",
"matplotlib",
"line",
"graphing"
] | I'm graphing some data (two lines) and I'd like to change the line style for the portions of the lines where the difference between them is statistically significant. So, in the below image (now a link b/c anti-spam policies don't allow me to post an image) I'd like the lines to look different (i.e. dashed perhaps) up ... | Edit: I'd had this open and left, so I didn't notice @Ricardo's answer. Because matplotlib will convert things to numpy arrays regardless, there are more efficient ways to do it.
As an example:
Just plot two different lines, one with a dashed linestyle and another with a solid linestyle.
E.g.
```
import numpy as np... |
Access dict key and return None if doesn't exist | 9,285,086 | 18 | 2012-02-14T22:20:37Z | 9,285,135 | 10 | 2012-02-14T22:25:03Z | [
"python",
"dictionary"
] | In Python what is the most efficient way to do this:
```
my_var = some_var['my_key'] | None
```
ie. assign `some_var['my_key']` to `my_var` if `some_var` contains `'my_key'`, otherwise make `my_var` be `None`. | You are looking for the [`get()`](http://docs.python.org/library/stdtypes.html#dict.get) method of `dict`.
```
my_var = some_var.get('some_key')
```
The `get()` method will return the value associated with `'some_key'`, if such a value exists. If the key is not present, then `None` will be returned. |
Access dict key and return None if doesn't exist | 9,285,086 | 18 | 2012-02-14T22:20:37Z | 9,285,161 | 27 | 2012-02-14T22:27:28Z | [
"python",
"dictionary"
] | In Python what is the most efficient way to do this:
```
my_var = some_var['my_key'] | None
```
ie. assign `some_var['my_key']` to `my_var` if `some_var` contains `'my_key'`, otherwise make `my_var` be `None`. | Python will throw a `KeyError` if the key doesn't exist in the dictionary so you can't write your code in quite the same way as your JavaScript. However, if you are operating specifically with dicts as in your example, there is a very nice function `mydict.get('key', default)` which attempts to get the key from the dic... |
Pyplot annotate with image (png or numpy array) instead of text | 9,285,159 | 6 | 2012-02-14T22:27:06Z | 9,287,152 | 7 | 2012-02-15T02:35:29Z | [
"python",
"matplotlib"
] | Is it possible to annotate a pyplot figure, but not with text or circles or the other similar objects, but an image instead?
For example read a png from a file and present it below a plotted data in the same graph. | [This](http://matplotlib.sourceforge.net/examples/pylab_examples/demo_annotation_box.html) demo seems to do what you're looking for. Below is the the resulting plot:
 |
How does import work with Boost.Python from inside python files | 9,285,384 | 7 | 2012-02-14T22:49:13Z | 9,288,360 | 11 | 2012-02-15T05:34:57Z | [
"python",
"c++",
"boost",
"import",
"boost-python"
] | I am using Boost.Python to embed an interpreter in my C++ executable and execute some prewritten scripts. I have got it working so that I can call functions in the python file but the python code I want to use imports external files and these imports fail because 'no module named '. If I run the script directly from py... | So it turns out that my problem is a simple case of the module search path not being set correctly when initialised from within C++.
[From the Python Documentation intro:](http://docs.python.org/c-api/intro.html)
> On most systems (in particular, on Unix and Windows, although the
> details are slightly different), Py... |
scrapy filtering duplicate requests | 9,286,514 | 4 | 2012-02-15T00:59:39Z | 9,347,372 | 12 | 2012-02-19T06:55:31Z | [
"python",
"scrapy"
] | What is the difference between the Duplicate Filter which exists in the Scheduler and the [IgnoreVisitedItems middleware](http://snipplr.com/view/67018/middleware-to-avoid-revisiting-already-visited-items/)?
Google group thread which suggests that there is a duplicate filter present in the Scheduler: <http://groups.go... | The duplicate filter in the scheduler only filters out the URLs already seen in a single spider run (meaning that it will get reset on subsequent runs). The IgnoreVistedItems middleware will keep a state between runs and avoiding visiting URLs seen in the past, but only for final item urls so that the rest of the site ... |
Can I get an item from a PriorityQueue without removing it yet? | 9,287,919 | 11 | 2012-02-15T04:34:25Z | 9,288,155 | 13 | 2012-02-15T05:08:08Z | [
"python",
"python-3.x",
"queue"
] | I want to get the next item in queue but I don't want to dequeue it. Is it possible in Python's Priority Queue? From the [docs](http://docs.python.org/py3k/library/queue.html?highlight=priorityqueue#queue.PriorityQueue), I don't see how can it be done | If a is a PriorityQueue object, You can use a.queue[0] to get the next item:
```
from Queue import PriorityQueue
a = PriorityQueue()
a.put((10, "a"))
a.put((4, "b"))
a.put((3,"c"))
print a.queue
print a.get()
print a.queue
print a.get()
print a.queue
```
output is :
```
[(3, 'c'), (10, 'a'), (4, 'b')]
(3, 'c')
[(... |
Need more mechanize documentation (python) | 9,288,662 | 13 | 2012-02-15T06:08:34Z | 16,402,297 | 15 | 2013-05-06T15:43:13Z | [
"python",
"mechanize"
] | I'm having a really hard time finding a good comprehensive source for Mechanize's documentation. Even the main documentation on [mechanize's site](http://wwwsearch.sourceforge.net/mechanize/doc.html) isn't really that great: it only seems to list examples.
Is there a more formal place for documentation where I can see... | A google search turned up the below, courtesy of one Joe. He parsed the source through pydoc and posted the generated results. Nice one, Joe.
<http://joesourcecode.com/Documentation/mechanize0.2.5/>
<http://joesourcecode.com/Documentation/mechanize0.2.5/mechanize._mechanize.Browser-class.html> |
can I make shared library using gfortran? | 9,288,806 | 4 | 2012-02-15T06:22:37Z | 9,288,947 | 9 | 2012-02-15T06:37:18Z | [
"python",
"fortran",
"gfortran",
"f2py"
] | I would like to make so file in order to use it in python.
how can I make shared library from fortran source?
I have tested like below code.
```
gfortran -c mod.f90
#gfortran -c sub1.f90
gfortran -c func.f90
gfortran -shared -fPIC -o func.so func.f90 mod.o
```
but I couldn't import it in python. I used module file i... | You need some "glue" between Fortran and Python. Check out [F2PY - Fortran to Python interface generator](http://docs.scipy.org/doc/numpy/user/c-info.python-as-glue.html)
EDIT. Example:
```
f2py -c -m func func.f90 mod.f90 sub1.f90
python
>>> import func
>>> dir(func)
['__doc__', '__file__', '__name__', '__version__'... |
About slices in Python | 9,289,427 | 2 | 2012-02-15T07:27:32Z | 9,289,467 | 8 | 2012-02-15T07:31:35Z | [
"python",
"slice"
] | 1. Is there any difference between `mylist[:]` and `mylist[::]`?
2. What's the rationale for `mylist[::0]` to raise an error since negative steps are allowed? | 1. No. Both result in `slice(None, None, None)`.
2. Positive strides go forwards. Negative strides go backwards. Zero strides go... nowhere? How exactly would that work? An infinite sequence of a single value? |
How to put items into priority queues? | 9,289,614 | 17 | 2012-02-15T07:47:30Z | 9,289,760 | 19 | 2012-02-15T08:01:40Z | [
"python",
"queue"
] | In the Python docs,
> The lowest valued entries are retrieved first (the lowest valued entry is the one returned by `sorted(list(entries))[0]`). A typical pattern for entries is a tuple in the form: `(priority_number, data)`.
It appears the queue will be sorted by priority then data, which may not be always correct. ... | As far as I know, what you're looking for isn't available out of the box. Anyway, note that it wouldn't be hard to implement:
```
from Queue import PriorityQueue
class MyPriorityQueue(PriorityQueue):
def __init__(self):
PriorityQueue.__init__(self)
self.counter = 0
def put(self, item, priorit... |
How to put items into priority queues? | 9,289,614 | 17 | 2012-02-15T07:47:30Z | 9,289,866 | 22 | 2012-02-15T08:12:48Z | [
"python",
"queue"
] | In the Python docs,
> The lowest valued entries are retrieved first (the lowest valued entry is the one returned by `sorted(list(entries))[0]`). A typical pattern for entries is a tuple in the form: `(priority_number, data)`.
It appears the queue will be sorted by priority then data, which may not be always correct. ... | Just use the second item of the tuple as a secondary priority if a alphanumeric sort on your string data isn't appropriate. A date/time priority would give you a priority queue that falls back to a FIFIO queue when you have multiple items with the same priority. Here's some example code with just a secondary numeric pr... |
How to set my xlabel at the end of xaxis | 9,290,938 | 20 | 2012-02-15T09:38:50Z | 9,295,719 | 22 | 2012-02-15T15:02:00Z | [
"python",
"matplotlib"
] | I want my x axis has the label like this format
```
0 1 2 3 4 5 Xlabel
```
but I try code below it result me in 2 lines
```
self.axes.set_xticks(np.arange(0,6,1))
self.axes.set_xlabel('Xlabel', fontsize=9,x=1,y=1)
```
=> my result :(
```
0 1 2 3 4 5
Xlabel
```
Need help please, | When setting the xlabel, the `x` parameter assigns the position in axis units, so 0 is the origin and 1 is the right edge of the plot. `y` is ignored as it's expected to be a default value, just below the tick marks.
To override this behavior, you can set the position in axis units using the `Axis` `set_label_coords` ... |
How to set my xlabel at the end of xaxis | 9,290,938 | 20 | 2012-02-15T09:38:50Z | 9,297,944 | 13 | 2012-02-15T17:13:05Z | [
"python",
"matplotlib"
] | I want my x axis has the label like this format
```
0 1 2 3 4 5 Xlabel
```
but I try code below it result me in 2 lines
```
self.axes.set_xticks(np.arange(0,6,1))
self.axes.set_xlabel('Xlabel', fontsize=9,x=1,y=1)
```
=> my result :(
```
0 1 2 3 4 5
Xlabel
```
Need help please, | In addition to what @Yann already said, it's actually easier to do this with `annotate`. It will also stay in the correct position when zoomed/panned.
```
import matplotlib.pyplot as plt
import matplotlib as mpl
ticklabelpad = mpl.rcParams['xtick.major.pad']
fig, ax = plt.subplots()
ax.set_xlim([0, 5])
# Add the la... |
api = twitter.Api() AttributeError: 'module' object has no attribute 'Api | 9,291,122 | 9 | 2012-02-15T09:51:19Z | 9,291,608 | 13 | 2012-02-15T10:26:34Z | [
"python",
"api",
"twitter",
"archlinux"
] | I have been trying to write a simple mention grabber to get started with the twitter Api. Howsoever I've been experienceing some difficulties when initializing the Api.
Running python2 on archlinux I installed twitter via easy\_install, built it from source and installed it via pip. None of this seems to be working.
`... | I think you've installed one twitter package, and look at another documentation. Ie: python-1.7.2 is the project from <https://github.com/sixohsix/twitter>, while you're looking at the <http://code.google.com/p/python-twitter/> documentation. No match between both :)
So for the one you've installed, if you check the s... |
How to get CherryPy version | 9,293,256 | 10 | 2012-02-15T12:20:05Z | 9,293,306 | 25 | 2012-02-15T12:23:28Z | [
"python",
"ubuntu",
"terminal",
"cherrypy"
] | I'm very new to CherryPy. I want to know which CherryPy version is installed in my machine. How to get CherryPy version in terminal?
Thank you for educate me. | ```
python -c "import cherrypy;print cherrypy.__version__"
``` |
Scriptable HTTP benchmark (preferable in Python) | 9,293,335 | 2 | 2012-02-15T12:25:50Z | 19,098,878 | 8 | 2013-09-30T16:10:21Z | [
"python",
"web-applications",
"benchmarking",
"stress-testing",
"performance-testing"
] | I'm searching for a good way to stress test a web application. Basically I'm searching für something like [ab](http://httpd.apache.org/docs/2.0/programs/ab.html) with a scriptable interface. Ideally I want to define some tasks, that simulate different action on the webapp (register a account, login, search, etc.) and ... | If you're familiar with the python requests package, locust is very easy to write load tests in.
<http://locust.io/>
I've used it to write all of our perf tests in it. |
Equivalent of Python urllib in Haskell | 9,294,870 | 5 | 2012-02-15T14:06:48Z | 9,295,132 | 7 | 2012-02-15T14:25:21Z | [
"python",
"haskell",
"urllib2"
] | Is there an equivalent of Python's urllib library in Haskell? I want to login into course homepage (on Moodle) and download assignments automatically. | I recommend [http-conduit](http://hackage.haskell.org/package/http-conduit); it's widely-used, has a simple interface and an efficient implementation, plus [automation for multi-page request flows](http://hackage.haskell.org/packages/archive/http-conduit/latest/doc/html/Network-HTTP-Conduit-Browser.html) (including coo... |
Matplotlib plots: removing axis, legends and white spaces | 9,295,026 | 71 | 2012-02-15T14:18:53Z | 9,295,367 | 37 | 2012-02-15T14:40:14Z | [
"python",
"matplotlib"
] | I'm new to Python and Matplotlib, I would like to simply apply colormap to an image and write the resulting image, without using axes, labels, titles or anything usually automatically added by matplotlib. Here is what I did:
```
def make_image(inputname,outputname):
data = mpimg.imread(inputname)[:,:,0]
fig = ... | I learned this trick from [matehat, here](http://stackoverflow.com/q/8218887/190597):
```
import matplotlib.pyplot as plt
import numpy as np
def make_image(inputname,outputname):
# data = mpimg.imread(inputname)[:,:,0]
data = np.arange(1,10).reshape((3, 3))
fig = plt.figure()
fig.set_size_inches(1, 1)... |
Matplotlib plots: removing axis, legends and white spaces | 9,295,026 | 71 | 2012-02-15T14:18:53Z | 9,295,472 | 91 | 2012-02-15T14:46:24Z | [
"python",
"matplotlib"
] | I'm new to Python and Matplotlib, I would like to simply apply colormap to an image and write the resulting image, without using axes, labels, titles or anything usually automatically added by matplotlib. Here is what I did:
```
def make_image(inputname,outputname):
data = mpimg.imread(inputname)[:,:,0]
fig = ... | I think that the command `axis('off')` takes care of one of the problems more succinctly than changing each axis and the border separately. It still leaves the white space around the border however. Adding `bbox_inches='tight'` to the `savefig` command almost gets you there, you can see in the example below that the wh... |
Matplotlib plots: removing axis, legends and white spaces | 9,295,026 | 71 | 2012-02-15T14:18:53Z | 26,610,602 | 11 | 2014-10-28T14:15:06Z | [
"python",
"matplotlib"
] | I'm new to Python and Matplotlib, I would like to simply apply colormap to an image and write the resulting image, without using axes, labels, titles or anything usually automatically added by matplotlib. Here is what I did:
```
def make_image(inputname,outputname):
data = mpimg.imread(inputname)[:,:,0]
fig = ... | Possible simplest solution:
I simply combined the method described in the question and the method from the answer by Hooked.
```
fig = plt.imshow(my_data)
plt.axis('off')
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.savefig('pict.png', bbox_inches='tight', pad_inches = 0)
```
A... |
Stopping Twisted from swallowing exceptions | 9,295,359 | 18 | 2012-02-15T14:39:34Z | 9,302,057 | 17 | 2012-02-15T21:55:07Z | [
"python",
"twisted"
] | Is there a way to stop Twisted reactor from automatically swallowing exceptions (eg. NameError)? I just want it to stop execution, and give me a stack trace in console?
There's even a FAQ [question](http://twistedmatrix.com/trac/wiki/FrequentlyAskedQuestions#Myexceptionsandtracebacksarentgettingprinted) about it, but ... | Let's explore "swallow" a little bit. What does it mean to "swallow" an exception?
Here's the most direct and, I think, faithful interpretation:
```
try:
user_code()
except:
pass
```
Here any exceptions from the call to user code are caught and then discarded with no action taken. If you look through Twisted... |
Python json.loads fails with `ValueError: Invalid control character at: line 1 column 33 (char 33)` | 9,295,439 | 22 | 2012-02-15T14:44:29Z | 9,295,597 | 34 | 2012-02-15T14:54:33Z | [
"python",
"json"
] | I have a string like this:
```
s = u"""{"desc": "\u73cd\u54c1\u7f51-\u5168\u7403\u6f6e\u6d41\u5962\u54c1\u7f51\u7edc\u96f6\u552e\u5546 <br \/>\r\nhttp:\/\/www.zhenpin.com\/ <br \/>\r\n<br \/>\r\n200\u591a\u4e2a\u56fd\u9645\u4e00\u7ebf\u54c1\u724c\uff0c\u9876\u7ea7\u4e70\u624b\u5168\u7403\u91c7\u8d2d\uff0c100%\u6b63\u5... | The problem is your unicode string contains carriage returns (`\r`) and newlines (`\n`) *within* a string literal in the JSON data. If they were meant to be part of the string itself, they should be escaped appropriately. If they weren't meant to be part of the string, they shouldn't be in your JSON either.
If you can... |
Python json.loads fails with `ValueError: Invalid control character at: line 1 column 33 (char 33)` | 9,295,439 | 22 | 2012-02-15T14:44:29Z | 9,295,607 | 9 | 2012-02-15T14:55:11Z | [
"python",
"json"
] | I have a string like this:
```
s = u"""{"desc": "\u73cd\u54c1\u7f51-\u5168\u7403\u6f6e\u6d41\u5962\u54c1\u7f51\u7edc\u96f6\u552e\u5546 <br \/>\r\nhttp:\/\/www.zhenpin.com\/ <br \/>\r\n<br \/>\r\n200\u591a\u4e2a\u56fd\u9645\u4e00\u7ebf\u54c1\u724c\uff0c\u9876\u7ea7\u4e70\u624b\u5168\u7403\u91c7\u8d2d\uff0c100%\u6b63\u5... | The problem is that the character at index 33 is a carriage return control character.
```
>>> s[33]
u'\r'
```
According to the JSON spec, valid characters are:
* Any Unicode character except: `"`, `\`, and control-characters (`ord(char) < 32`).
* The following character sequences are allowed: `\"`, `\\`, `\/`, `\b` ... |
Python json.loads fails with `ValueError: Invalid control character at: line 1 column 33 (char 33)` | 9,295,439 | 22 | 2012-02-15T14:44:29Z | 16,544,933 | 32 | 2013-05-14T13:45:46Z | [
"python",
"json"
] | I have a string like this:
```
s = u"""{"desc": "\u73cd\u54c1\u7f51-\u5168\u7403\u6f6e\u6d41\u5962\u54c1\u7f51\u7edc\u96f6\u552e\u5546 <br \/>\r\nhttp:\/\/www.zhenpin.com\/ <br \/>\r\n<br \/>\r\n200\u591a\u4e2a\u56fd\u9645\u4e00\u7ebf\u54c1\u724c\uff0c\u9876\u7ea7\u4e70\u624b\u5168\u7403\u91c7\u8d2d\uff0c100%\u6b63\u5... | Another option, perhaps, is to use the `strict=False` argument
According to <http://docs.python.org/2/library/json.html>
"If strict is False (True is the default), then control characters will be allowed inside strings. Control characters in this context are those with character codes in the 0-31 range, including '\t... |
How to filter a numpy array with another array's values | 9,296,658 | 9 | 2012-02-15T15:55:58Z | 9,296,696 | 19 | 2012-02-15T15:58:26Z | [
"python",
"arrays",
"filter",
"numpy"
] | I have 2 numpy arrays, e.g.:
```
a = [1,2,3,4,5]
```
and a filter array, e.g.:
```
f = [False, True, False, False, True]
len(a) == len(f)
```
How can I get a new numpy array with only the values in a where the same index in f is True, in my case: [2, 5]
(this is not homework and the lists can be 10 million length... | NumPy supports [boolean indexing](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#boolean-array-indexing)
```
a[f]
```
This assumes that `a` and `f` are NumPy arrays rather than Python lists (as in the question). You can convert with `f = np.array(f)`. |
Convert numpy array from values to indices | 9,296,893 | 2 | 2012-02-15T16:10:18Z | 9,296,963 | 8 | 2012-02-15T16:13:40Z | [
"python",
"arrays",
"numpy"
] | I have a numpy array a: [True, False, True, False, False, ...]
And I like to have a numpy array that has the indices of the True and False values, i.e. [0, 2, ...] and [1, 3, 4, ...] | To get the indices of the `True` values in `a`, you can use
```
a.nonzero()
```
For the indices of the `False` values, use
```
(~a).nonzero()
``` |
Python generator expression parentheses oddity | 9,297,653 | 6 | 2012-02-15T16:56:00Z | 9,297,682 | 8 | 2012-02-15T16:57:48Z | [
"python",
"parentheses",
"generator-expression"
] | I want to determine if a list contains a certain string, so I use a generator expression, like so:
```
g = (s for s in myList if s == myString)
any(g)
```
Of course I want to inline this, so I do:
```
any((s for s in myList if s == myString))
```
Then I think it would look nicer with single parens, so I try:
```
a... | It is legal, and the general rule is that you do need parentheses around a generator expression. As a special exception, the parentheses from a function call also count (for functions with only a single parameter). ([Documentation](http://docs.python.org/reference/expressions.html#generator-expressions))
Note that tes... |
Cannot import scipy.misc.imread | 9,298,665 | 15 | 2012-02-15T17:58:16Z | 11,943,724 | 14 | 2012-08-13T23:32:56Z | [
"python",
"scipy"
] | I've seen this problem before with other people, but haven't found a fix.
All I'm trying to do is:
`from scipy.misc import imread`
and I get
```
/home1/users/joe.borg/<ipython-input-2-f9d3d927b58f> in <module>()
----> 1 from scipy.misc import imread
/software/Python/272/lib/python2.7/site-packages/scipy/misc/__ini... | You might need to install [PIL](http://www.pythonware.com/products/pil/) or [Pillow](http://pillow.readthedocs.org). |
Python "and" operator with ints | 9,299,020 | 9 | 2012-02-15T18:22:36Z | 9,299,079 | 15 | 2012-02-15T18:26:17Z | [
"python",
"boolean"
] | What is the explanation for this behavior in Python?
```
a = 10
b = 20
a and b # 20
b and a # 10
```
`a and b` evaluates to 20, while `b and a` evaluates to 10. Are positive ints equivalent to True? Why does it evaluate to the second value? Because it is second? | The [documentation](http://docs.python.org/reference/expressions.html#boolean-operations) explains this quite well:
> The expression `x and y` first evaluates `x`; if `x` is false, its value is returned; otherwise, `y` is evaluated and the resulting value is returned.
And similarly for `or` which will probably be the... |
Fastest SVM implementation usable in Python | 9,299,346 | 27 | 2012-02-15T18:46:13Z | 9,300,826 | 18 | 2012-02-15T20:29:17Z | [
"python",
"machine-learning",
"gpu",
"svm",
"scikit-learn"
] | I'm building some predictive models in Python and have been using scikits learn's SVM implementation. It's been really great, easy to use, and relatively fast.
Unfortunately, I'm beginning to become constrained by my runtime. I run a rbf SVM on a full dataset of about 4 - 5000 with 650 features. Each run takes about a... | Alternatively you can run the grid search on 1000 random samples instead of the full dataset:
```
>>> from sklearn.cross_validation import ShuffleSplit
>>> cv = ShuffleSplit(3, test_fraction=0.2, train_fraction=0.2, random_state=0)
>>> gs = GridSeachCV(clf, params_grid, cv=cv, n_jobs=-1, verbose=2)
>>> gs.fit(X, y)
``... |
Fastest SVM implementation usable in Python | 9,299,346 | 27 | 2012-02-15T18:46:13Z | 9,300,883 | 23 | 2012-02-15T20:33:39Z | [
"python",
"machine-learning",
"gpu",
"svm",
"scikit-learn"
] | I'm building some predictive models in Python and have been using scikits learn's SVM implementation. It's been really great, easy to use, and relatively fast.
Unfortunately, I'm beginning to become constrained by my runtime. I run a rbf SVM on a full dataset of about 4 - 5000 with 650 features. Each run takes about a... | The most scalable kernel SVM implementation I know of is [LaSVM](http://leon.bottou.org/projects/lasvm). It's written in C hence wrap-able in Python if you know [Cython](http://en.wikipedia.org/wiki/Cython), [ctypes](https://en.wikipedia.org/wiki/Ctypes#Software) or [cffi](http://cffi.readthedocs.org/en/latest/). Alter... |
Fastest SVM implementation usable in Python | 9,299,346 | 27 | 2012-02-15T18:46:13Z | 12,613,674 | 7 | 2012-09-27T03:30:39Z | [
"python",
"machine-learning",
"gpu",
"svm",
"scikit-learn"
] | I'm building some predictive models in Python and have been using scikits learn's SVM implementation. It's been really great, easy to use, and relatively fast.
Unfortunately, I'm beginning to become constrained by my runtime. I run a rbf SVM on a full dataset of about 4 - 5000 with 650 features. Each run takes about a... | Firstly, according to scikit-learn's benchmark ([here](http://scikit-learn.sourceforge.net/ml-benchmarks/)), scikit-learn is already one of the fastest if not fastest SVM package around. Hence, you might want to consider other ways of speeding up the training.
As suggested by bavaza, you can try to multi-thread the tr... |
Add number to set | 9,299,919 | 19 | 2012-02-15T19:27:51Z | 9,299,947 | 20 | 2012-02-15T19:29:34Z | [
"python",
"set"
] | What am I doing wrong here?
```
a = set().add(1)
print a # Prints `None`
```
I'm trying to add the number `1` to the empty set. | The `add()` method adds an element to the set, but it does not return the set again -- it returns `None`.
```
a = set()
a.add(1)
```
or better
```
a = set([1])
```
would work. |
Add number to set | 9,299,919 | 19 | 2012-02-15T19:27:51Z | 9,300,257 | 38 | 2012-02-15T19:49:09Z | [
"python",
"set"
] | What am I doing wrong here?
```
a = set().add(1)
print a # Prints `None`
```
I'm trying to add the number `1` to the empty set. | It is a convention in Python that methods that mutate sequences return `None`.
Consider:
```
>>> a_list = [3, 2, 1]
>>> print a_list.sort()
None
>>> a_list
[1, 2, 3]
>>> a_dict = {}
>>> print a_dict.__setitem__('a', 1)
None
>>> a_dict
{'a': 1}
>>> a_set = set()
>>> print a_set.add(1)
None
>>> a_set
set([1])
```
So... |
Python Formatting Large Text | 9,301,466 | 7 | 2012-02-15T21:11:57Z | 9,301,735 | 14 | 2012-02-15T21:31:04Z | [
"python",
"string-formatting"
] | What's the best way to format a large blob of text in python? I don't mean formatting the output, but rather for readability. I've been trying to follow the [guidelines for python layout](http://www.python.org/dev/peps/pep-0008/), but I don't see any remarks on how to format a large blob of text.
For example:
```
cla... | The standard library has tools for this:
```
import textwrap
#...
def getCalendarHeader(self):
print textwrap.dedent("""\
BEGIN:VCALENDAR
PRODID:-//Atlassian Software Systems//Confluence Calendar Plugin//EN
VERSION:2.0
CALSCALE:GREGORIAN
X-WR-CA... |
Python float round error 117.285 round to 117.28 not 117.29 | 9,301,690 | 4 | 2012-02-15T21:28:21Z | 9,301,754 | 10 | 2012-02-15T21:32:10Z | [
"python"
] | I am using python 2.7, and the code I have is:
```
a = 10.5 * 22.34 / 2.0
print "%.2f" % a
```
and the result I expect is 117.29, but it shows 117.28. How to solve the problem? | If Python is using a 64-bit IEEE-754 binary floating point type, then the *exact* value it's using will be
```
117.284999999999996589394868351519107818603515625
```
... and that's obviously lower than the midpoint between 117.28 and 117.29. It's possible that that's what's going on.
Another option is that Python is ... |
NoSQL Solution for Persisting Graphs at Scale | 9,302,295 | 22 | 2012-02-15T22:12:30Z | 9,645,518 | 36 | 2012-03-10T09:54:12Z | [
"python",
"nosql",
"graph-theory",
"networkx"
] | I'm hooked on using Python and NetworkX for analyzing graphs and as I learn more I want to use more and more data (guess I'm becoming a data junkie :-). Eventually I think my NetworkX graph (which is stored as a dict of dict) will exceed the memory on my system. I know I can probably just add more memory but I was wond... | There are two general types of containers for storing graphs:
1. **true graph databases:** e.g., *Neo4J*, *agamemnon*, *GraphDB*, and *AllegroGraph*; these not only store a graph but they also understand that a graph is, so for instance, you can query these
databases e.g., *how many nodes are between the shortest p... |
python: function takes exactly 1 argument (2 given) | 9,302,436 | 5 | 2012-02-15T22:23:06Z | 9,302,446 | 14 | 2012-02-15T22:24:24Z | [
"python",
"class",
"methods"
] | I have this method in a class
```
class CatList:
lista = codecs.open('googlecat.txt', 'r', encoding='utf-8').read()
soup = BeautifulSoup(lista)
# parse the list through BeautifulSoup
def parseList(tag):
if tag.name == 'ul':
return [parseList(item)
for item i... | You forgot the `self` argument.
You need to change this line:
```
def parseList(tag):
```
with:
```
def parseList(self, tag):
```
You also got a global name error, since you're trying to access `parseList` without `self`.
While you should to do something like:
```
self.parseList(item)
```
inside your method.
... |
Changing variables in multiple Python instances | 9,302,789 | 3 | 2012-02-15T22:56:12Z | 9,304,924 | 11 | 2012-02-16T03:00:09Z | [
"python",
"class",
"object"
] | Is there anyway to set the variables of all instances of a class at the same time? I've got a simplified example below:
```
class Object():
def __init__(self):
self.speed=0
instance0=Object()
instance1=Object()
instance2=Object()
#Object.speed=5 doesn't work of course
```
I can see it would be possible by... | One, simpler way, as the other answers put it, is to keep your attribute always as a class attribute. If it is set on the class body, and all write access to the attribute is via the class name, not an instance, that would work:
```
>>> class Object(object):
... speed = 0
...
>>> a = Object()
>>> b = Object()
>>>... |
Is it okay to write own magic methods? | 9,302,814 | 4 | 2012-02-15T22:58:00Z | 9,302,851 | 9 | 2012-02-15T23:00:24Z | [
"python"
] | In my web application I often need to serialize objects as JSON.
Not all objects are JSON-serializable by default so I am using my own `encode_complex` method which is passed to the `simplejson.dumps` as follows: `simplejson.dumps(context, default=self.encode_complex)`
Is it okay to define my own magic method called `... | The `__double_underscore__` names are reserved for future extensions of the Python language and should not be used for your own code (except for the ones already defined, of course). Why not simply call the method `json()`?
Here is the relevant section from the [Python language reference](http://docs.python.org/refere... |
Why does importing a python module not import nested modules? | 9,303,179 | 9 | 2012-02-15T23:25:58Z | 9,303,305 | 10 | 2012-02-15T23:36:31Z | [
"python",
"python-module"
] | If I do this:
```
import lxml
```
in python, `lxml.html` is not imported. For instance, I cannot call the `lxml.html.parse()` function. Why is this so? | Importing a module or package in Python is a conceptually simple operation:
1. Find the .py file corresponding to the import. This involves the Python path and some other machinery, but will result in a specific .py file being found.
2. For every directory level in the import (`import foo.bar.baz` has two levels), fin... |
Proper way to import a single Django settings constant to avoid the full settings import overhead? | 9,303,273 | 4 | 2012-02-15T23:34:42Z | 9,303,375 | 10 | 2012-02-15T23:43:07Z | [
"python",
"django",
"import"
] | From [Django Importing Settings File](http://stackoverflow.com/questions/8780756/django-importing-settings-file), I understand the accepted way to import the settings file:
```
from django.conf import settings
```
I've also read [Good or bad practice in Python: import in the middle of a file](http://stackoverflow.com... | If this is a Django project, then the settings file has already been imported, it doesn't cost you anything to simply import it and use the constant you want. Importing a module many times in Python only executes the file once.
The usual way to import settings:
```
from django.conf import settings
```
This just assi... |
Matplotlib yaxis range display using absolute values rather than offset values? | 9,303,728 | 15 | 2012-02-16T00:17:22Z | 9,303,922 | 25 | 2012-02-16T00:42:43Z | [
"python",
"numpy",
"matplotlib"
] | I have the following range of numpy data (deltas of usec timestamps):
```
array([ 4.312, 4.317, 4.316, 4.32 , 4.316, 4.316, 4.319, 4.317,
4.317, 4.316, 4.318, 4.316, 4.318, 4.316, 4.318, 4.317,
4.317, 4.317, 4.316, 4.317, 4.318, 4.316, 4.318, 4.316,
4.318, 4.316, 4.317, 4.317, 4.31... | set useOffset to False:
```
ax = plt.gca()
ax.ticklabel_format(useOffset=False)
``` |
Matplotlib yaxis range display using absolute values rather than offset values? | 9,303,728 | 15 | 2012-02-16T00:17:22Z | 9,304,011 | 7 | 2012-02-16T00:53:47Z | [
"python",
"numpy",
"matplotlib"
] | I have the following range of numpy data (deltas of usec timestamps):
```
array([ 4.312, 4.317, 4.316, 4.32 , 4.316, 4.316, 4.319, 4.317,
4.317, 4.316, 4.318, 4.316, 4.318, 4.316, 4.318, 4.317,
4.317, 4.317, 4.316, 4.317, 4.318, 4.316, 4.318, 4.316,
4.318, 4.316, 4.317, 4.317, 4.31... | You can also use
```
ax = plt.gca()
ax.set_yticklabels(ax.get_yticks())
```
Although I like @HYRY's answer better. |
ImportError: cannot import name reverse_lazy | 9,304,330 | 3 | 2012-02-16T01:40:47Z | 9,304,351 | 9 | 2012-02-16T01:44:18Z | [
"python",
"django"
] | I'm very new to python and trying to run a piece of Django code on my system, but I'm running into this problem.
```
$ python manage.py runserver
Running in development mode.
Traceback (most recent call last):
File "manage.py", line 11, in <module>
import settings
File "/Users/Kinnovate/Desktop/fsdjango/platfo... | `reverse_lazy` is newer than any released version of Django. Are you sure you have a trunk version of Django? |
Is there a nice idiom for adding a new list or appending to a list (if present) in a dictionary? | 9,304,396 | 4 | 2012-02-16T01:51:11Z | 9,304,413 | 8 | 2012-02-16T01:53:12Z | [
"dictionary",
"python",
"idioms"
] | This is the second time I've implemented something like this and I suspect there has to be a better *(read: more pythonic)* way to do this:
```
phone_book = {}
def add_number(name,number):
if name in phone_book:
phone_book['name'].append(number)
else:
phone_book['name'] = [number]
```
I realize the code ... | Yep, you can use [`defaultdict`](http://docs.python.org/library/collections.html#defaultdict-objects). With this `dict` subclass, when you access an element in the dictionary, if a value doesn't already exist, it automatically creates one using a constructor function you specify.
```
from collections import defaultdic... |
Is there a nice idiom for adding a new list or appending to a list (if present) in a dictionary? | 9,304,396 | 4 | 2012-02-16T01:51:11Z | 9,304,424 | 7 | 2012-02-16T01:55:20Z | [
"dictionary",
"python",
"idioms"
] | This is the second time I've implemented something like this and I suspect there has to be a better *(read: more pythonic)* way to do this:
```
phone_book = {}
def add_number(name,number):
if name in phone_book:
phone_book['name'].append(number)
else:
phone_book['name'] = [number]
```
I realize the code ... | Use `dict`'s [`setdefault`](http://docs.python.org/library/stdtypes.html#dict.setdefault) like this:
```
phone_book.setdefault('name', []).append(number)
``` |
How to add an integer to each element in a list? | 9,304,408 | 28 | 2012-02-16T01:52:43Z | 9,304,419 | 46 | 2012-02-16T01:54:04Z | [
"python",
"loops",
"addition"
] | If I have `list=[1,2,3]` and I want to add `1` to each element to get the output `[2,3,4]`,
how would I do that?
I assume I would use a for loop but not sure exactly how. | ```
new_list = [x+1 for x in my_list]
``` |
How to add an integer to each element in a list? | 9,304,408 | 28 | 2012-02-16T01:52:43Z | 9,304,433 | 11 | 2012-02-16T01:56:14Z | [
"python",
"loops",
"addition"
] | If I have `list=[1,2,3]` and I want to add `1` to each element to get the output `[2,3,4]`,
how would I do that?
I assume I would use a for loop but not sure exactly how. | ```
>>> mylist = [1,2,3]
>>> [x+1 for x in mylist]
[2, 3, 4]
>>>
```
[list-comprehensions python](http://docs.python.org/tutorial/datastructures.html#list-comprehensions). |
How to add an integer to each element in a list? | 9,304,408 | 28 | 2012-02-16T01:52:43Z | 9,304,486 | 7 | 2012-02-16T02:03:57Z | [
"python",
"loops",
"addition"
] | If I have `list=[1,2,3]` and I want to add `1` to each element to get the output `[2,3,4]`,
how would I do that?
I assume I would use a for loop but not sure exactly how. | The other answers on list comprehension are probably the best bet for simple addition, but if you have a more complex function that you needed to apply to all the elements then [map](http://docs.python.org/library/functions.html#map) may be a good fit.
In your example it would be:
```
>>> map(lambda x:x+1, [1,2,3])
[... |
django filter with list of values | 9,304,908 | 97 | 2012-02-16T02:57:24Z | 9,304,968 | 219 | 2012-02-16T03:05:57Z | [
"python",
"django"
] | I'm sure this is a trivial operation, but I can't figure out how it's done... How can I create a django query for a list of values.
There got to be something smarter than this:
```
ids = [1, 3, 6, 7, 9]
for id in ids:
MyModel.objects.filter( pk=id )
```
I'm looking to get them all in one show with something like:... | From the [Django documentation](https://docs.djangoproject.com/en/dev/topics/db/queries/#the-pk-lookup-shortcut):
```
Blog.objects.filter(pk__in=[1,4,7])
``` |
django filter with list of values | 9,304,908 | 97 | 2012-02-16T02:57:24Z | 9,305,618 | 24 | 2012-02-16T04:36:14Z | [
"python",
"django"
] | I'm sure this is a trivial operation, but I can't figure out how it's done... How can I create a django query for a list of values.
There got to be something smarter than this:
```
ids = [1, 3, 6, 7, 9]
for id in ids:
MyModel.objects.filter( pk=id )
```
I'm looking to get them all in one show with something like:... | When you have list of items and you want to check the possible values from the list then you can't use `=`.
The sql query will be like `SELECT * FROM mytable WHERE ids=[1, 3, 6, 7, 9]` which is not true. You have to use `in` operator for this so you query will be like `SELECT * FROM mytable WHERE ids in (1, 3, 6, 7, 9... |
Force python class member variable to be specific type | 9,305,751 | 13 | 2012-02-16T04:54:09Z | 9,321,953 | 19 | 2012-02-17T02:06:25Z | [
"python",
"class",
"variables"
] | How do I restrict a class member variable to be a specific type in Python?
---
Longer version:
I have a class that has several member variables which are set externally to the class. Due to the way they're used, they must be of specific types, either int or list. If this was C++, I would simply make them private and... | You can use a property like the other answers put it -
so, if you want to constraina single attribute, say "bar",
and constrain it to an integer, you could write code like this:
```
class Foo(object):
def _get_bar(self):
return self.__bar
def _set_bar(self, value):
if not isinstance(value, int)... |
Status 405 from the task queue | 9,306,315 | 5 | 2012-02-16T06:01:33Z | 9,306,944 | 11 | 2012-02-16T07:06:28Z | [
"python",
"google-app-engine",
"gae-datastore",
"python-2.7"
] | I want to resolve a status 405 that I get from the task queue when trying to generate a report:
```
2012-02-16 03:56:53.012 /report/ 405 3ms 0kb AppEngine-Google; (+http://code.google.com/appengine)
2012-02-16 03:56:53.007 /createreport/ 302 20ms 0kb Mozilla/5.0 (X11; Linux x86_64; rv:2.0) Gecko/20100101 Firefox/4.0
... | I came from GAE/J-land, so I am not familiar with Python, but I had encountered `405` response from my taskqueue worker before. In my case, it is caused due to setting the `TaskOption` method to `POST` while building the `Task`, while my handler only serves `GET` requests.
EDIT: After checking the [TaskQueue.add() doc... |
Why python time has 61 seconds | 9,306,328 | 9 | 2012-02-16T06:03:06Z | 9,306,345 | 14 | 2012-02-16T06:04:44Z | [
"python",
"python-2.7"
] | Did anybody notice that the interval of second in Python datetime is [00,61]
see the table in the bottom of this page.
<http://docs.python.org/library/datetime.html#strftime-strptime-behavior>
Why? | The answer is a little further down in the page:
> The range really is 0 to 61; according to the Posix standard this
> accounts for leap seconds and the (very rare) double leap seconds. The
> time module may produce and does accept leap seconds since it is based
> on the Posix standard, but the datetime module does no... |
Difference between statement and function | 9,307,291 | 8 | 2012-02-16T07:38:11Z | 9,307,317 | 15 | 2012-02-16T07:40:04Z | [
"javascript",
"python",
"ruby"
] | It's almost midnight and I just got a question in my head is "for loop" a statement or a function.
I always thought it is a statement, but I did a google search on it being a function and there are indeed results for that. So what is it? And in that case what is the difference between function and statement? | A for loop is a not usually a function, it is a special kind of statement called a flow control structure.
A [**statement**](http://en.wikipedia.org/wiki/Statement_%28computer_science%29) is a command. It does something. In most languages, statements do not return values. Example:
```
print "Hello World"
```
A [**fu... |
What is the Heroku equivalent for Django applications? | 9,308,047 | 2 | 2012-02-16T08:47:57Z | 9,308,100 | 10 | 2012-02-16T08:52:02Z | [
"python",
"django",
"heroku"
] | What is the Heroku equivalent for Django applications? (Edit: Question not relevant anymore as Heroku now supports Django) | Just to answer this for future reference, Heroku supports python and Django. See [here](https://devcenter.heroku.com/categories/language-support) for documentation on what languages is supported by Heroku. |
How to make my SWIG extension module work with Pickle? | 9,310,053 | 8 | 2012-02-16T10:57:19Z | 9,325,185 | 8 | 2012-02-17T08:42:51Z | [
"python",
"swig",
"pickle"
] | I have an extension module for Python that uses SWIG as a wrapper and I try to serialize it with Pickle and I fail =)
1. If anyone has a source of SWIG extension that can be pickled, would love to see it!
2. It seems like I should implement [`__reduce_ex__`](http://docs.python.org/library/pickle.html#pickling-and-unpi... | Seems like I found simlple solution that works for me:
So let's say we have class `C` that was generated with SWIG, then we wrap it with
```
class PickalableC(C, PickalableSWIG):
def __init__(self, *args):
self.args = args
C.__init__(self)
```
where `PickalableSWIG` is
```
class PickalableSWIG:... |
Is there a numpy max min function? | 9,312,756 | 15 | 2012-02-16T14:11:43Z | 9,312,778 | 26 | 2012-02-16T14:13:09Z | [
"python",
"numpy",
"max",
"min"
] | Is there a numpy function that gives for a given numpy array its maximum - minimum value, i.e. numpy.max(a) - numpy.min(a) ?
e.g.
```
numpy.xxx([4,3,2, 6] = 4 since max = 6, min = 2, 6 - 4 = 2)
```
Reason: performance increase since max and min would cause twice the iteration of the array (which is in my case 7.5 mi... | Indeed there is such a function -- it's called [`numpy.ptp()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ptp.html) for "peak to peak". |
PyGame Collision? | 9,312,781 | 3 | 2012-02-16T14:13:34Z | 9,312,895 | 10 | 2012-02-16T14:21:06Z | [
"python",
"pygame",
"collision"
] | How do I find collisions between characters and images within PyGame?
I have drawn a player from an image, and have drawn the walls from tiles, so how would I detect these collisions? | If you use the pygame [Rect](http://www.pygame.org/docs/ref/rect.html) class to represent the boundaries of your object, you can detect whether two are colliding by using the Rect.colliderect function. For example:
```
import pygame
a = pygame.Rect((1, 1), (2, 2))
b = pygame.Rect((0, 0), (2, 2))
c = pygame.Rect((0, 0... |
How to send the selected item in the listWidget to another function as a parameter | 9,313,227 | 2 | 2012-02-16T14:41:21Z | 9,315,013 | 8 | 2012-02-16T16:25:29Z | [
"python",
"qt4",
"pyqt4"
] | Whenever I click any function in the list widget, it ran a specific function. Now I want to send the item itself, as a parameter to that function. Here is the code:
```
QtCore.QObject.connect(self.listWidget, QtCore.SIGNAL("itemClicked(QListWidgetItem *)"), self.test)
def test(self):
print 'hello'
```
Instead I ... | That should already work - when `itemClicked` is emitted it sends the clicked `QListWidgetItem` as a parameter. You just need to edit your `test` function to accept an extra parameter, and that will be your `QListWidgetItem`.
```
from PyQt4.QtCore import QCoreApplication, Qt
from PyQt4.QtGui import QListWidget, QListW... |
Installing IPython 0.12 on Windows 7 64 | 9,313,508 | 7 | 2012-02-16T14:58:06Z | 9,320,910 | 7 | 2012-02-16T23:49:44Z | [
"python",
"windows-7",
"64bit",
"ipython"
] | I read the installation notes [here](http://ipython.org/ipython-doc/rel-0.12/install/install.html#windows). The installation notes say that for Windows 7 64 I should probably follow this method:
> Install from source, but using setuptools (python setupegg.py
> install).
So I first installed Python 2.7.2 using the off... | I suggest you try methods 1 (`easy_install ipython`) or 2 (the exe installer) first. Note that in any case, you should install [distribute](http://pypi.python.org/pypi/distribute#installation-instructions) first. (If you really want to use method 3, you'll need to get the source zip, not the egg.)
To run the notebook,... |
"Out of Memory" error with mechanize | 9,314,149 | 5 | 2012-02-16T15:35:13Z | 9,338,773 | 13 | 2012-02-18T05:11:27Z | [
"python",
"memory",
"urllib2",
"mechanize"
] | I was trying to scrape some information from a website page by page, basically here's what I did:
```
import mechanize
MechBrowser = mechanize.Browser()
Counter = 0
while Counter < 5000:
Response = MechBrowser.open("http://example.com/page" + str(Counter))
Html = Response.read()
Response.close()
Out... | This is not exactly a memory leak, but rather an undocumented feature. Basically, `mechanize.Browser()` is collectively storing all browser history in memory as it goes.
If you add a call to `MechBrowser.clear_history()` after `Response.close()`, it should resolve the problem. |
How to concatenate `Object` with a string? | 9,314,612 | 3 | 2012-02-16T16:03:22Z | 9,314,708 | 8 | 2012-02-16T16:08:48Z | [
"python",
"casting"
] | How to concatenate `Object` with a string (primitive) without overloading and explicit type cast (`str()`)?
```
class Foo:
def __init__(self, text):
self.text = text
def __str__(self):
return self.text
_string = Foo('text') + 'string'
```
**Output:**
```
Traceback (most recent call last):
... | Just define the `__add__()` and `__radd__()` methods:
```
class Foo:
def __init__(self, text):
self.text = text
def __str__(self):
return self.text
def __add__(self, other):
return str(self) + other
def __radd__(self, other):
return other + str(self)
```
They will be ca... |
Python: Create Dictionary from Text/File that's in Dictionary Format | 9,314,824 | 9 | 2012-02-16T16:14:33Z | 9,314,908 | 13 | 2012-02-16T16:19:26Z | [
"python",
"file",
"dictionary",
"external"
] | I'd like to create a dictionary from a text file that I have, who's contents are in a 'dictionary' format. Here's a sample of what the file contains:
> {'fawn': [1], 'sermersheim': [3], 'sonji': [2], 'scheuring': [2]}
It's exactly this except it contains 125,000 entries. I am able to read in the text file using read(... | You can use the [`eval`](http://docs.python.org/library/functions.html#eval) built-in. For example, this would work if each dictionary entry is on a different line:
```
dicts_from_file = []
with open('myfile.txt','r') as inf:
for line in inf:
dicts_from_file.append(eval(line))
# dicts_from_file now con... |
Python 2.7: Print to File | 9,316,023 | 59 | 2012-02-16T17:28:37Z | 9,316,083 | 34 | 2012-02-16T17:32:38Z | [
"python",
"file",
"python-2.7"
] | Why does trying to print directly to a file instead of `sys.stdout` produce the following syntax error:
```
Python 2.7.2+ (default, Oct 4 2011, 20:06:09)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f1=open('./testfile', 'w+')
>>> print('This is a test', file=f1)
... | print is a keyword in python 2.X. You should use the following:
```
f1=open('./testfile', 'w+')
f1.write('This is a test')
``` |
Python 2.7: Print to File | 9,316,023 | 59 | 2012-02-16T17:28:37Z | 9,316,155 | 15 | 2012-02-16T17:36:25Z | [
"python",
"file",
"python-2.7"
] | Why does trying to print directly to a file instead of `sys.stdout` produce the following syntax error:
```
Python 2.7.2+ (default, Oct 4 2011, 20:06:09)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f1=open('./testfile', 'w+')
>>> print('This is a test', file=f1)
... | `print(args, file=f1)` is the python 3.x syntax.
For python 2.x use `print >> f1, args`. |
Python 2.7: Print to File | 9,316,023 | 59 | 2012-02-16T17:28:37Z | 9,316,160 | 99 | 2012-02-16T17:36:44Z | [
"python",
"file",
"python-2.7"
] | Why does trying to print directly to a file instead of `sys.stdout` produce the following syntax error:
```
Python 2.7.2+ (default, Oct 4 2011, 20:06:09)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f1=open('./testfile', 'w+')
>>> print('This is a test', file=f1)
... | If you want to use the `print` function in Python 2, you have to import from `__future__`:
```
from __future__ import print_function
```
But you can have the same effect without using the function, too:
```
print >>f1, 'This is a test'
``` |
What is the "correct" way to pass a boolean to a Python C extension? | 9,316,179 | 17 | 2012-02-16T17:37:59Z | 9,316,413 | 14 | 2012-02-16T17:52:53Z | [
"python",
"python-c-api",
"python-c-extension"
] | This is a simple example from the python documentation (http://docs.python.org/extending/extending.html):
```
static PyObject *
spam_system(PyObject *self, PyObject *args)
{
const char *command;
int sts;
if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
return... | > 4 maybe there's a way to get any type of variable and get its truth value (i.e an empty array will is falsy etc.) which is what python
> function usually do.
Yes: (from [Python/C API Reference](http://docs.python.org/c-api/object.html))
> ```
> int PyObject_IsTrue(PyObject *o)
> ```
>
> Returns 1 if the object o is... |
What is the "correct" way to pass a boolean to a Python C extension? | 9,316,179 | 17 | 2012-02-16T17:37:59Z | 10,700,727 | 13 | 2012-05-22T11:01:48Z | [
"python",
"python-c-api",
"python-c-extension"
] | This is a simple example from the python documentation (http://docs.python.org/extending/extending.html):
```
static PyObject *
spam_system(PyObject *self, PyObject *args)
{
const char *command;
int sts;
if (!PyArg_ParseTuple(args, "s", &command))
return NULL;
sts = system(command);
return... | Currently, parsing an integer (as `"i"`) is the accepted way to take a bool.
From Python 3.3, `PyArg_ParseTuple` will accept `"p"` (for "predicate"), per [the latest NEWS](http://hg.python.org/cpython/file/05274ab06182/Misc/NEWS):
> * [Issue #14705](http://bugs.python.org/issue14705): The PyArg\_Parse() family of fun... |
running system commands on linux using python? | 9,316,468 | 3 | 2012-02-16T17:56:52Z | 9,316,500 | 7 | 2012-02-16T17:59:27Z | [
"python",
"linux"
] | I'm wondering if someone can either direct me to a example or help me with my code for running commands on linux(centos). Basically, I am assuming I have a basic fresh server and want to configure it. I thought I could list the commands I need to run and it would work but I'm getting errors. The errors are related to n... | Since `commands` has been deprecated for a long time, you should really be using `subprocess`, specifically [`subprocess.check_output`](http://docs.python.org/library/subprocess.html#subprocess.check_output). Also, `cd thrift-0.8.0` only affects the subprocess, and not yours. You can either call [os.chdir](http://docs.... |
django request.user.is_authenticated is always true? | 9,316,666 | 8 | 2012-02-16T18:12:41Z | 9,316,695 | 28 | 2012-02-16T18:14:28Z | [
"python",
"django"
] | Can anyone tell me why in the following code I get redirected to yahoo.com instead of google.com?
urls
```
urlpatterns = patterns('', (r'^$', initialRequest,))
```
view
```
def initialRequest(request):
if request.user.is_authenticated:
return HttpResponseRedirect('http://yahoo.com')
else:
r... | Shouldn't it be request.user.is\_authenticated() ie with brackets as it's a function ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.