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 |
|---|---|---|---|---|---|---|---|---|---|
Why is the speed difference between these 2 functions so large? | 4,602,242 | 5 | 2011-01-05T08:55:14Z | 4,602,279 | 7 | 2011-01-05T09:00:57Z | [
"python",
"function",
"performance"
] | I've been reading through some of the MIT opencourseware quizes and they had a question that goes like this:
> 6) Consider the two functions specified below that are used to play a âguess a number game.â
```
def cmpGuess(guess):
"""Assumes that guess is an integer in range(maxVal). returns -1 if guess is < than t... | The most obvious thing I can see is that every time you call the teacher's function it creates a list of 1,000,000 integers (assuming Python 2.x), and then when it returns it destroys that list again.
That is going to take a while. |
Twisted server for multiple clients | 4,604,580 | 10 | 2011-01-05T13:32:31Z | 4,604,641 | 7 | 2011-01-05T13:38:30Z | [
"python",
"twisted"
] | I want to write a server that can accept multiple clients in python (twisted). I am already quite familiar with socket programming with the standard python socket module but here comes the trouble..
I think twisted is really hard to get into and i have read some tutorials about it.
But a thing that i can't really find ... | I think, you did not get the essence of twisted. If you create a twisted socket server it is by default available connection via multiple clients. I would suggested the following tutorials in order and then read the twisted documentation. Write small snippets as its given in these tutorials to understand what is actual... |
Twisted server for multiple clients | 4,604,580 | 10 | 2011-01-05T13:32:31Z | 4,605,104 | 11 | 2011-01-05T14:24:05Z | [
"python",
"twisted"
] | I want to write a server that can accept multiple clients in python (twisted). I am already quite familiar with socket programming with the standard python socket module but here comes the trouble..
I think twisted is really hard to get into and i have read some tutorials about it.
But a thing that i can't really find ... | Say, you want to run a server accepting client connections on port 9000:
```
from twisted.internet import reactor, protocol
PORT = 9000
class MyServer(protocol.Protocol):
pass
class MyServerFactory(protocol.Factory):
protocol = MyServer
factory = MyServerFactory()
reactor.listenTCP(PORT, factory)
reactor.r... |
Django Model Field Default to Null | 4,604,814 | 32 | 2011-01-05T13:56:02Z | 4,604,826 | 50 | 2011-01-05T13:57:26Z | [
"python",
"django",
"django-models"
] | I need to have my Django application allow me to have a default value of NULL set for a certain model field. I've looked over the *null*, *blank*, and *default* parameters, but it's not very clear what combination of the three I need to use to get the desired effect. I've tried setting `default=NULL` but it threw an er... | Try `default=None`. There is no `NULL` in **python**. |
Django Model Field Default to Null | 4,604,814 | 32 | 2011-01-05T13:56:02Z | 4,604,988 | 19 | 2011-01-05T14:12:42Z | [
"python",
"django",
"django-models"
] | I need to have my Django application allow me to have a default value of NULL set for a certain model field. I've looked over the *null*, *blank*, and *default* parameters, but it's not very clear what combination of the three I need to use to get the desired effect. I've tried setting `default=NULL` but it threw an er... | If you specify null=True on the model field then the value will be stored as NULL in the database if the user does not provide a value. |
Detecting whether or not text is English (in bulk) | 4,605,062 | 6 | 2011-01-05T14:20:18Z | 4,605,147 | 8 | 2011-01-05T14:28:37Z | [
"python",
"nlp",
"language-detection"
] | I'm looking for a simple way to detect whether a short excerpt of text, a few sentences, is English or not. Seems to me that this problem is much easier than trying to detect an arbitrary language. Is there any software out there that can do this? I'm writing in python, and would prefer a python library, but something ... | I read a method to detect Enlgish langauge by using Trigrams
<http://en.wikipedia.org/wiki/Trigram>
You can go over the text, and try to detect the most used trigrams in the words. If the most used ones match with the most used among english words, the text may be written in English
Try to look in this ruby project:... |
What is the simplest way to swap char in a string with Python? | 4,605,439 | 7 | 2011-01-05T14:57:00Z | 4,606,057 | 8 | 2011-01-05T15:52:40Z | [
"python",
"string"
] | I want to swap each pair of characters in a string. `'2143'` becomes `'1234'`, `'badcfe'` becomes `'abcdef'`.
How can I do this in Python? | oneliner:
```
>>> s = 'badcfe'
>>> ''.join([ s[x:x+2][::-1] for x in range(0, len(s), 2) ])
'abcdef'
```
* s[x:x+2] returns string slice from x to x+2; it is safe for odd len(s).
* [::-1] reverses the string in Python
* range(0, len(s), 2) returns 0, 2, 4, 6 ... while x < len(s) |
Finding outliers in a data set | 4,606,288 | 17 | 2011-01-05T16:09:43Z | 4,608,817 | 7 | 2011-01-05T20:23:33Z | [
"python",
"statistics"
] | I have a python script that creates a list of lists of server uptime and performance data, where each sub-list (or 'row') contains a particular cluster's stats. For example, nicely formatted it looks something like this:
```
------- ------------- ------------ ---------- -------------------
Cluster %Availability ... | Your stated goal of "finding badness" implies that it is not the outliers that you are looking for, but observations that fall above or below some threshold, and I would presume that the threshold would remain the same over time.
As an example, if all of your servers were at 98 ± 0.1 % availability, a server at 100% ... |
Finding outliers in a data set | 4,606,288 | 17 | 2011-01-05T16:09:43Z | 4,609,787 | 8 | 2011-01-05T22:18:31Z | [
"python",
"statistics"
] | I have a python script that creates a list of lists of server uptime and performance data, where each sub-list (or 'row') contains a particular cluster's stats. For example, nicely formatted it looks something like this:
```
------- ------------- ------------ ---------- -------------------
Cluster %Availability ... | One good way of identifying outliers visually is to make a boxplot (or box-and-whiskers plot), which will show the median, and a couple of quartiles above and below the median, and the points that lie "far" from this box (see Wikipedia entry <http://en.wikipedia.org/wiki/Box_plot>). In R, there's a `boxplot` function t... |
How can I specify a database for Django Tests to use instead of having it build it everytime? | 4,606,756 | 11 | 2011-01-05T16:51:11Z | 4,606,983 | 14 | 2011-01-05T17:14:28Z | [
"python",
"django",
"unit-testing"
] | I want to be able to use an existing test database to run my tests against and not have Django create and delete a database everytime I want to run the tests. Is this possible? | It's possible, here is a way :
1) Define your own test runner look [here](https://docs.djangoproject.com/en/1.5/topics/testing/advanced/#defining-a-test-runner) to see how.
2) For your custom test runner look in the [default test runner](https://github.com/django/django/blob/stable/1.5.x/django/test/simple.py#L237), ... |
In Python try until no error | 4,606,919 | 14 | 2011-01-05T17:08:34Z | 4,606,963 | 14 | 2011-01-05T17:12:19Z | [
"python",
"error-handling"
] | I have a piece of code in Python that seems to cause an error probabilistically because it is accessing a server and sometimes that server has a 500 internal server error. I want to keep trying until I do not get the error. My solution was:
```
while True:
try:
#code with possible error
except:
... | Maybe something like this:
```
connected = False
while not connected:
try:
try_connect()
connected = True
except ...:
pass
``` |
In Python try until no error | 4,606,919 | 14 | 2011-01-05T17:08:34Z | 4,606,966 | 13 | 2011-01-05T17:12:29Z | [
"python",
"error-handling"
] | I have a piece of code in Python that seems to cause an error probabilistically because it is accessing a server and sometimes that server has a 500 internal server error. I want to keep trying until I do not get the error. My solution was:
```
while True:
try:
#code with possible error
except:
... | It won't get much cleaner. This is not a very clean thing to do. At best (which would be more readable anyway, since the condition for the `break` is up there with the `while`), you could create a variable `result = None` and loop while it `is None`. You should also adjust the variables and you can replace `continue` w... |
Why can't I handle a KeyboardInterrupt in python? | 4,606,942 | 27 | 2011-01-05T17:10:32Z | 4,607,230 | 16 | 2011-01-05T17:34:51Z | [
"python",
"windows",
"keyboardinterrupt"
] | I'm writing python 2.6.6 code on windows that looks like this:
```
try:
dostuff()
except KeyboardInterrupt:
print "Interrupted!"
except:
print "Some other exception?"
finally:
print "cleaning up...."
print "done."
```
`dostuff()` is a function that loops forever, reading a line at a time from an i... | Asynchronous exception handling is unfortunately not reliable (exceptions raised by signal handlers, outside contexts via C API, etc). You can increase your chances of handling the async exception properly if there is some coordination in the code about what piece of code is responsible for catching them (highest possi... |
How to access a superclass's class attributes in Python? | 4,608,968 | 5 | 2011-01-05T20:41:49Z | 4,609,102 | 7 | 2011-01-05T20:56:03Z | [
"python",
"super",
"superclass"
] | Have a look at the following code:
```
class A(object):
defaults = {'a': 1}
def __getattr__(self, name):
print('A.__getattr__')
return self.get_default(name)
@classmethod
def get_default(cls, name):
# some debug output
print('A.get_default({}) - {}'.format(name, cls))
... | Not really an answer but an observation:
This looks overengineered to me, a common trap when looking for excuses to use python magic.
If you can be bothered to define a `defaults` dict for a class why not just define the attributes instead? the effect is the same.
```
class A:
a = 1
class B(A):
b = 2
class... |
Zed Shaw's Learn Python the Hard way Tutorial | 4,609,373 | 4 | 2011-01-05T21:26:20Z | 4,609,398 | 17 | 2011-01-05T21:29:01Z | [
"python"
] | I'm new to programming and currently going through the exercises in Zed Shaw's Python book.
In Zed's Ex41, there is this function:
```
def runner(map, start):
next = start
while True:
room = map[next]
print "\n-------"
next = room()
```
My question is, why did he have to assign '... | The second example works, yes, but he's trying to write a Python tutorial style book, and I think the first one is much more clear about exactly what's going on. `start` as a variable name loses meaning when it's no longer the actual `start`, but instead the `next` room that we're going into. |
Zed Shaw's Learn Python the Hard way Tutorial | 4,609,373 | 4 | 2011-01-05T21:26:20Z | 4,609,430 | 11 | 2011-01-05T21:31:57Z | [
"python"
] | I'm new to programming and currently going through the exercises in Zed Shaw's Python book.
In Zed's Ex41, there is this function:
```
def runner(map, start):
next = start
while True:
room = map[next]
print "\n-------"
next = room()
```
My question is, why did he have to assign '... | I think it was done for readability. In the programmer's mind, `start` is supposed to represent the start of something. `next` was presumably supposed to represent the next item.
You are correct that the code could be shortened, but it mangles the meaning of `start`.
Note that in current versions of Python (2.6 or la... |
Django doesn't create translation .po files | 4,609,728 | 4 | 2011-01-05T22:11:27Z | 4,610,608 | 7 | 2011-01-06T00:16:42Z | [
"python",
"django",
"localization"
] | I have my translation strings only in templates (stored in the project\_dir/Templates), I tried running the `$ django-admin.py createmessages -l ru` both in the project root directory and in the app directories that use templates with trans. strings. It created folders locale/ru/LC\_MESSAGES but the folders were empty.... | did you try :
```
python manage.py makemessages -a
```
from project root and app ?
this should create a .po that you have to edit.
be sure to remove 'fuzzy' stuff everywhere.
then :
```
python manage.py compilemessages
```
You need to **restart** the server |
Fixing tostring() in Python's lxml | 4,610,019 | 5 | 2011-01-05T22:52:01Z | 4,610,267 | 11 | 2011-01-05T23:22:23Z | [
"python",
"xml",
"lxml"
] | lxml's `tostring()` function seems quite broken when printing only parts of documents. Witness:
```
from lxml.html import fragment_fromstring, tostring
frag = fragment_fromstring('<p>This stuff is <em>really</em> great!')
em = frag.cssselect('em').pop(0)
print tostring(em)
```
I expect `<em>really</em>` but instead i... | How about `xml = lxml.etree.tostring(e, with_tail=False)`?
```
from lxml.html import fragment_fromstring
from lxml.etree import tostring
frag = fragment_fromstring('<p>This stuff is <em>really</em> great!')
em = frag.cssselect('em').pop(0)
print tostring(em, with_tail=False)
```
Looks like `with_tail` was added in v2... |
Django - determining if geographic coordinates are inside of an circle | 4,610,717 | 3 | 2011-01-06T00:33:48Z | 4,610,776 | 12 | 2011-01-06T00:45:38Z | [
"python",
"django",
"gis",
"geodjango",
"geopy"
] | Does django have anything that will look at a geographic coordinate (decimal lat/long) and determine if is inside a circle with a certain radius (let's say 100 Km)?
I have certain type of data, each has a lat/long and I would like to make a search in the database to see if that data is located inside of a circle with ... | This problem can be solved in pure SQL if you dont mind about very good precision.
You can find points around a GPS position with this specific SQL query :
```
# find point around :
latitude = 46.2037010192871
longitude = 5.20353984832764
query= "SELECT ID, NOM, LAT, LON, 3956 * 2 * ASIN(SQRT(POWER(SIN((%s - LAT) * 0... |
can I put my sqlite connection and cursor in a function? | 4,610,791 | 6 | 2011-01-06T00:47:57Z | 4,610,876 | 12 | 2011-01-06T01:05:58Z | [
"python",
"oop",
"sqlite3"
] | I was thinking I'd try to make my sqlite db connection a function instead of copy/pasting the ~6 lines needed to connect and execute a query all over the place.
I'd like to make it versatile so I can use the same function for create/select/insert/etc...
Below is what I have tried. The 'INSERT' and 'CREATE TABLE' queri... | I think the problem is a little more difficult than it looks at first.
Your seeing that error because you've closed your connection to the database in your "connection" function.
Your probably better off creating a DatabaseManagement Class, to manage a single connection.
Something like:
```
import sqlite3
class Da... |
Calculate next scheduled time based on cron spec | 4,610,904 | 11 | 2011-01-06T01:12:39Z | 4,611,170 | 8 | 2011-01-06T02:13:14Z | [
"python",
"algorithm",
"cron",
"scheduler"
] | What's an efficient way to calculate the next run time of an event given the current time and a cron spec?
I'm looking for something other than "loop through every minute checking if it matches spec".
Examples of specs might be:
* Every month, on the 1st and 15 at 15:01
* At 10,20,30,40,50 mins past the hour every h... | Just looking at it, I think you need to:
* parse the chron spec to five arrays containing acceptable values for each field;
* parse 'now' to a value for each field;
* in order of minute, hour, {day-of-month OR day-of-week}, month-of year: find the lowest array value that matches or exceeds the current value, correctin... |
Django - get HTML output into a variable | 4,611,410 | 16 | 2011-01-06T03:14:33Z | 4,611,580 | 12 | 2011-01-06T03:54:09Z | [
"python",
"django",
"django-templates",
"django-views"
] | instead of using `render_to_response` which will send the HTML output back to browser.
I would like to take the results, generate HTML (using templates) & output the html into a variable in my `views.py`. How can I do this?
**UPDATE:** SOLVED! the way to do this -
```
from django.template.loader import render_to_str... | Adapted from the [Django docs](http://docs.djangoproject.com/en/dev/ref/templates/api/#using-the-template-system):
```
from django.template import Context, Template
t = Template("My name is {{ my_name }}.")
c = Context({"my_name": "Adrian"})
output = t.render(c)
``` |
Python 256bit Hash function with number output | 4,612,150 | 9 | 2011-01-06T05:51:02Z | 4,612,189 | 13 | 2011-01-06T05:56:56Z | [
"python",
"hash",
"long-integer"
] | I need a Hash function with a 256bit output (as long int).
First I thought I could use SHA256 from the hashlib but it has an String Output and I need a number to calculate with.
Converting the 32 Byte String to a long would work also but I didn't find anything.
In struct there is a unpack function but this only works... | How about:
```
>>> import hashlib
>>> h = hashlib.sha256('something to hash')
>>> h.hexdigest()
'a3899c4070fc75880fa445b6dfa44207cbaf924a450ce7175cd8500e597d3ec1'
>>> n = int(h.hexdigest(),base=16)
>>> print n
73970130776712578303406724846815845410916448611708558169000368019946742824641
``` |
What is the 'cls' variable used in python classes? | 4,613,000 | 99 | 2011-01-06T08:17:53Z | 4,613,013 | 33 | 2011-01-06T08:21:10Z | [
"python",
"class",
"object",
"self"
] | Why is 'cls' used instead of 'self'?
Any help appreciated | It's used in case of a class method. See <http://docs.python.org/library/functions.html#classmethod> for further reference.
EDIT: As clarified by Adrien, it's a convention. You can actually use anything but `cls` and `self` are used (**PEP8**). |
What is the 'cls' variable used in python classes? | 4,613,000 | 99 | 2011-01-06T08:17:53Z | 4,795,306 | 115 | 2011-01-25T15:27:00Z | [
"python",
"class",
"object",
"self"
] | Why is 'cls' used instead of 'self'?
Any help appreciated | The distinction between `"self"` and `"cls"` is defined in [`PEP 8`](http://www.python.org/dev/peps/pep-0008/#function-and-method-arguments) . As Adrien said, this is not a mandatory. It's a coding style. `PEP 8` says:
> *Function and method arguments*:
>
> Always use `self` for the first argument to instance methods.... |
Python & Pygame: Ball collision with interior of circle | 4,613,345 | 6 | 2011-01-06T09:16:45Z | 4,629,657 | 11 | 2011-01-07T19:53:17Z | [
"python",
"physics",
"collision-detection",
"pygame"
] | I'm making a game in which balls bounce around the *inside* of a much larger circle. The larger circle doesn't move.
Here's the code that I'm currently using for these collisions:
```
def collideCircle(circle, ball):
"""Check for collision between a ball and a circle"""
dx = circle.x - ball.x
dy = circle.... | Without answering your question, I'd like to comment on your implementation strategy and recommend a new approach. You represent the velocity of the ball in polar coordinate form, as `ball.angle` and `ball.speed`.
I think that this is going to be generally inconvenient for you. For example, in your collision code you ... |
Python & Pygame: Ball collision with interior of circle | 4,613,345 | 6 | 2011-01-06T09:16:45Z | 4,629,993 | 11 | 2011-01-07T20:28:42Z | [
"python",
"physics",
"collision-detection",
"pygame"
] | I'm making a game in which balls bounce around the *inside* of a much larger circle. The larger circle doesn't move.
Here's the code that I'm currently using for these collisions:
```
def collideCircle(circle, ball):
"""Check for collision between a ball and a circle"""
dx = circle.x - ball.x
dy = circle.... | I'm glad you liked my tutorial. I like your variation, it should actually be simpler.
First, I think you need change the test for collision to:
```
if distance >= circle.size - ball.size:
```
Because the larger the ball size, the smaller the distance between its centre and the centre of the circle can be. This shoul... |
Using python to write mysql query to csv, need to show field names | 4,613,465 | 9 | 2011-01-06T09:31:16Z | 4,614,070 | 7 | 2011-01-06T10:45:57Z | [
"python",
"mysql",
"csv"
] | I have the following:
```
import MySQLdb as dbapi
import sys
import csv
dbServer='localhost'
dbPass='supersecretpassword'
dbSchema='dbTest'
dbUser='root'
dbQuery='SELECT * FROM pbTest.Orders;'
db=dbapi.connect(host=dbServer,user=dbUser,passwd=dbPass)
cur=db.cursor()
cur.execute(dbQuery)
result=cur.fetchall()
c = c... | `result` is a list of rows. So you'll need to iterate through that list and write each row:
```
for row in result:
c.writerow(row)
``` |
Using python to write mysql query to csv, need to show field names | 4,613,465 | 9 | 2011-01-06T09:31:16Z | 11,726,011 | 13 | 2012-07-30T16:51:04Z | [
"python",
"mysql",
"csv"
] | I have the following:
```
import MySQLdb as dbapi
import sys
import csv
dbServer='localhost'
dbPass='supersecretpassword'
dbSchema='dbTest'
dbUser='root'
dbQuery='SELECT * FROM pbTest.Orders;'
db=dbapi.connect(host=dbServer,user=dbUser,passwd=dbPass)
cur=db.cursor()
cur.execute(dbQuery)
result=cur.fetchall()
c = c... | You can dump all results to the csv file without looping:
```
rows = cursor.fetchall()
fp = open('/tmp/file.csv', 'w')
myFile = csv.writer(fp)
myFile.writerows(rows)
fp.close()
``` |
How can I simplify "for x in a for y in b for z in c ..." with the unordered? | 4,613,481 | 5 | 2011-01-06T09:33:32Z | 4,613,538 | 12 | 2011-01-06T09:40:55Z | [
"python",
"list-comprehension",
"research",
"cartesian-product",
"unordered"
] | ```
#!/usr/bin/python
#
# Description: I try to simplify the implementation of the thing below.
# Sets, such as (a,b,c), with irrelavant order are given. The goal is to
# simplify the messy "assignment", not sure of the term, below.
#
#
# QUESTION: How can you simplify it?
#
# >>> a=['1','2','3']
# >>> b=['bc','b']
# ... | Try this
```
>>> import itertools
>>> a=['1','2','3']
>>> b=['bc','b']
>>> c=['#']
>>> print [ "".join(res) for res in itertools.product(a,b,c) ]
['1bc#', '1b#', '2bc#', '2b#', '3bc#', '3b#']
``` |
How can I simplify "for x in a for y in b for z in c ..." with the unordered? | 4,613,481 | 5 | 2011-01-06T09:33:32Z | 4,613,761 | 8 | 2011-01-06T10:07:06Z | [
"python",
"list-comprehension",
"research",
"cartesian-product",
"unordered"
] | ```
#!/usr/bin/python
#
# Description: I try to simplify the implementation of the thing below.
# Sets, such as (a,b,c), with irrelavant order are given. The goal is to
# simplify the messy "assignment", not sure of the term, below.
#
#
# QUESTION: How can you simplify it?
#
# >>> a=['1','2','3']
# >>> b=['bc','b']
# ... | ```
>>> from itertools import product
>>> a=['1','2','3']
>>> b=['bc','b']
>>> c=['#']
>>> map("".join, product(a,b,c))
['1bc#', '1b#', '2bc#', '2b#', '3bc#', '3b#']
```
edit:
you can use product on a bunch of things like you would like to also
```
>>> list_of_things = [a,b,c]
>>> map("".join, product(*list_of_thing... |
Running Python from a virtualenv with Apache/mod_wsgi, on Windows | 4,614,121 | 11 | 2011-01-06T10:51:54Z | 4,615,026 | 10 | 2011-01-06T12:46:20Z | [
"python",
"apache",
"wamp",
"virtualenv",
"wampserver"
] | I'm trying to set up WAMP server. I've got Apache working correctly, and I've installed mod\_wsgi without a hitch.
Problem is, I'm using virtual environments (using virtualenv) for my projects. So obviously, mod\_wsgi is having problems locating my installation of Django.
I'm trying to understand how I can get mod\_w... | You can activate the environment programmatically from Python adding this to your .wsgi file before importing anything else.
From [virtualenv's docs](http://pypi.python.org/pypi/virtualenv):
> Sometimes you can't or don't want to
> use the Python interpreter created by
> the virtualenv. For instance, in a
> mod\_pyth... |
How do I pass in the 'id' portion of the URL to a view_callable? | 4,614,260 | 4 | 2011-01-06T11:10:53Z | 4,615,473 | 9 | 2011-01-06T13:40:17Z | [
"python",
"pylons",
"pyramid"
] | I've been playing around with Pyramid lately and, coming from a Pylons background, I've been focusing in URL routing rather than traversal.
I've also been looking at using handlers to group together 'controller' specific functions into the one class. Rather than having view.py polluted with a bunch of functions.
Conf... | You can access «id» through request.matchdict:
```
from pyramid.response import Response
from pyramid.view import action
class Page(object):
def __init__(self, request):
self.request = request
def view_page(self):
matchdict = request.matchdict
id = matchdict.get('id', None)
... |
Python: Convert Relative Date String to Absolute Date Stamp | 4,615,250 | 2 | 2011-01-06T13:14:21Z | 4,615,451 | 11 | 2011-01-06T13:37:36Z | [
"python",
"string",
"datetime",
"date"
] | There are several questions along the same lines in Stackoverflow but this case is different.
As input, I have a date string that can take three general formats. Either
a) January 6, 2011
b) 4 days ago
c) 12 hours ago
I want the script to be able to recognize the format and call the appropriate function with the par... | Using [parsedatetime](https://github.com/bear/parsedatetime), you could parse all three date formats into `datetime.datetime` objects without having to code the logic yourself:
```
import parsedatetime.parsedatetime as pdt
import parsedatetime.parsedatetime_consts as pdc
import datetime
c = pdc.Constants()
p = pdt.Cal... |
get base class type in python | 4,615,762 | 8 | 2011-01-06T14:10:24Z | 4,615,797 | 15 | 2011-01-06T14:14:06Z | [
"python"
] | ```
class a:
pass
class b(a):
pass
c = b()
type(c) == a #returns False
```
Is there an alternative to type() that can check if an object inherits from a class? | Yes, [isinstance](http://docs.python.org/library/functions.html#isinstance): `isinstance(obj, Klass)` |
In Python, why is a module implemented in C faster than a pure Python module, and how do I write one? | 4,616,129 | 6 | 2011-01-06T14:46:46Z | 4,616,206 | 12 | 2011-01-06T14:54:08Z | [
"python",
"c",
"python-c-api"
] | The python documentation states, that the reason cPickle is faster than Pickle is, that the former is implemented in C. What does that mean exactly?
I am making a module for advanced mathematics in Python, and some calculations take a significant amount of time. Does that mean that if my program is implemented in C it... | you can write fast C code and then use it in your python scripts, so your program will run faster. [1]
<http://docs.python.org/extending/index.html#extending-index>
an example is Numpy, written in C ( <http://numpy.scipy.org/> )
a typical use is to implement the bottleneck in C (or to use a library written in C, of c... |
Handling Signals in Python Threads | 4,616,361 | 7 | 2011-01-06T15:10:04Z | 4,616,691 | 10 | 2011-01-06T15:43:42Z | [
"python",
"multithreading",
"signals",
"interrupt"
] | I have a threaded application written in Python, and whenever an interrupt is received via **`Ctrl`+`C`** or sometimes with kill, the application will hang. A stack trace is presented from one thread, but the application remains in the foreground, and I usually have to background it with **`Ctrl`+`Z`** then attempt to ... | If you set `newthread.daemon = True` before starting each thread, the threads will automatically be killed when the main thread exits. That's not precisely what you were asking, but from what you've described, it sounds like it could be worth knowing. |
Automatically Generating Documentation for All Python Package Contents | 4,616,693 | 38 | 2011-01-06T15:44:02Z | 4,617,804 | 16 | 2011-01-06T17:32:49Z | [
"python",
"documentation",
"documentation-generation",
"python-sphinx"
] | I'm trying to auto-generate basic documentation for my codebase using Sphinx. However, I'm having difficulty instructing Sphinx to recursively scan my files.
I have a Python codebase with a folder structure like:
```
<workspace>
src
mypackage
__init__.py
subpackageA
... | Perhaps apigen.py can help: <https://github.com/nipy/nipy/tree/master/tools>.
This tool is described very briefly here: <http://comments.gmane.org/gmane.comp.python.sphinx.devel/2912>.
---
Update: the [sphinx-apidoc](http://sphinx.pocoo.org/invocation.html#invocation-of-sphinx-apidoc) utility was added in Sphinx [ve... |
Automatically Generating Documentation for All Python Package Contents | 4,616,693 | 38 | 2011-01-06T15:44:02Z | 8,086,048 | 35 | 2011-11-10T20:44:45Z | [
"python",
"documentation",
"documentation-generation",
"python-sphinx"
] | I'm trying to auto-generate basic documentation for my codebase using Sphinx. However, I'm having difficulty instructing Sphinx to recursively scan my files.
I have a Python codebase with a folder structure like:
```
<workspace>
src
mypackage
__init__.py
subpackageA
... | You can try using sphinx-apidoc.
```
$ sphinx-apidoc --help
Usage: sphinx-apidoc [options] -o <output_path> <module_path> [exclude_paths, ...]
Look recursively in <module_path> for Python modules and packages and create
one reST file with automodule directives per package in the <output_path>.
```
You can mix sphinx... |
Can i get console input without echo in python? | 4,616,813 | 15 | 2011-01-06T15:55:00Z | 4,616,837 | 27 | 2011-01-06T15:56:54Z | [
"python"
] | Can I get console input without echo in python? | Use [getpass](http://docs.python.org/library/getpass.html):
```
>>> from getpass import getpass
>>> getpass()
Password:
'secret'
``` |
How can I open multiple files using "with open" in Python? | 4,617,034 | 283 | 2011-01-06T16:16:43Z | 4,617,069 | 435 | 2011-01-06T16:19:55Z | [
"python",
"file-io"
] | I want to change a couple of files at one time, **iff** I can write to all of them. I'm wondering if I somehow can combine the multiple open calls with the `with` statement:
```
try:
with open('a', 'w') as a and open('b', 'w') as b:
do_something()
except IOError as e:
print 'Operation failed: %s' % e.strerror
... | As of Python 2.7 (or 3.1 respectively) you can write
```
with open('a', 'w') as a, open('b', 'w') as b:
do_something()
```
In earlier versions of Python, you can sometimes use
[`contextlib.nested()`](http://docs.python.org/library/contextlib.html#contextlib.nested) to nest context managers. This won't work as exp... |
How can I open multiple files using "with open" in Python? | 4,617,034 | 283 | 2011-01-06T16:16:43Z | 4,617,080 | 58 | 2011-01-06T16:20:42Z | [
"python",
"file-io"
] | I want to change a couple of files at one time, **iff** I can write to all of them. I'm wondering if I somehow can combine the multiple open calls with the `with` statement:
```
try:
with open('a', 'w') as a and open('b', 'w') as b:
do_something()
except IOError as e:
print 'Operation failed: %s' % e.strerror
... | Just replace `and` with `,` and you're done:
```
try:
with open('a', 'w') as a, open('b', 'w') as b:
do_something()
except IOError as e:
print 'Operation failed: %s' % e.strerror
``` |
python convert string to datetime | 4,617,267 | 3 | 2011-01-06T16:41:11Z | 4,618,090 | 7 | 2011-01-06T18:02:52Z | [
"python",
"datetime",
"date"
] | i have a loop where i try to process set of data where one action is to convert ordinary string to datetime. everything works fine except sometimes happend a weird thing ... here is what i know
* there are exactly the same parameters entering the function always
* those parameters are the same type always
* first time... | You probably have a different locale set up. %B is March in locales that use English, but in other locales it will fail.
For example:
```
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'sv_SE.utf8')
'sv_SE.utf8'
>>> import datetime
>>>
>>> data = ['January 20 1999', 'March 4 2010', 'June 11 1819']
>>> for ite... |
How do I get a raw, compiled SQL query from a SQLAlchemy expression? | 4,617,291 | 35 | 2011-01-06T16:43:05Z | 4,617,623 | 20 | 2011-01-06T17:14:34Z | [
"python",
"sql",
"mysql",
"sqlalchemy"
] | I have a SQLAlchemy query object and want to get the text of the compiled SQL statement, with all its parameters bound (e.g. no `%s` or other variables waiting to be bound by the statement compiler or MySQLdb dialect engine, etc).
Calling `str()` on the query reveals something like this:
```
SELECT id WHERE date_adde... | This should work with Sqlalchemy >= 0.6
```
from sqlalchemy.sql import compiler
from psycopg2.extensions import adapt as sqlescape
# or use the appropiate escape function from your db driver
def compile_query(query):
dialect = query.session.bind.dialect
statement = query.statement
comp = compiler.SQLComp... |
How do I get a raw, compiled SQL query from a SQLAlchemy expression? | 4,617,291 | 35 | 2011-01-06T16:43:05Z | 4,618,052 | 8 | 2011-01-06T18:00:12Z | [
"python",
"sql",
"mysql",
"sqlalchemy"
] | I have a SQLAlchemy query object and want to get the text of the compiled SQL statement, with all its parameters bound (e.g. no `%s` or other variables waiting to be bound by the statement compiler or MySQLdb dialect engine, etc).
Calling `str()` on the query reveals something like this:
```
SELECT id WHERE date_adde... | Thing is, sqlalchemy never mixes the data with your query. The query and the data are passed separately to your underlining database driver - the interpolation of data happens in your database.
Sqlalchemy passes the query as you've seen in `str(myquery)` to the database, and the values will go in a separate tuple.
Yo... |
How do I get a raw, compiled SQL query from a SQLAlchemy expression? | 4,617,291 | 35 | 2011-01-06T16:43:05Z | 4,618,647 | 16 | 2011-01-06T18:59:15Z | [
"python",
"sql",
"mysql",
"sqlalchemy"
] | I have a SQLAlchemy query object and want to get the text of the compiled SQL statement, with all its parameters bound (e.g. no `%s` or other variables waiting to be bound by the statement compiler or MySQLdb dialect engine, etc).
Calling `str()` on the query reveals something like this:
```
SELECT id WHERE date_adde... | For the MySQLdb backend I modified albertov's awesome answer (thanks so much!) a bit. I'm sure they could be merged to check if comp.positional was True but that's slightly beyond the scope of this question.
```
def compile_query(query):
from sqlalchemy.sql import compiler
from MySQLdb.converters import conver... |
How do I get a raw, compiled SQL query from a SQLAlchemy expression? | 4,617,291 | 35 | 2011-01-06T16:43:05Z | 25,563,491 | 37 | 2014-08-29T07:24:23Z | [
"python",
"sql",
"mysql",
"sqlalchemy"
] | I have a SQLAlchemy query object and want to get the text of the compiled SQL statement, with all its parameters bound (e.g. no `%s` or other variables waiting to be bound by the statement compiler or MySQLdb dialect engine, etc).
Calling `str()` on the query reveals something like this:
```
SELECT id WHERE date_adde... | [This](http://nicolascadou.com/blog/2014/01/printing-actual-sqlalchemy-queries/) blog provides an updated answer.
Quoting from the blog post, this is suggested and worked for me.
```
>>> from sqlalchemy.dialects import postgresql
>>> print str(q.statement.compile(dialect=postgresql.dialect()))
```
Where q is defined... |
How do I get a raw, compiled SQL query from a SQLAlchemy expression? | 4,617,291 | 35 | 2011-01-06T16:43:05Z | 36,141,722 | 9 | 2016-03-21T21:14:50Z | [
"python",
"sql",
"mysql",
"sqlalchemy"
] | I have a SQLAlchemy query object and want to get the text of the compiled SQL statement, with all its parameters bound (e.g. no `%s` or other variables waiting to be bound by the statement compiler or MySQLdb dialect engine, etc).
Calling `str()` on the query reveals something like this:
```
SELECT id WHERE date_adde... | The [documentation](http://docs.sqlalchemy.org/en/latest/faq/sqlexpressions.html) uses `literal_binds` to print a query `q` including parameters:
```
print(q.statement.compile(compile_kwargs={"literal_binds": True}))
```
> the above approach has the caveats that it is only supported for basic types, such as ints and ... |
Best way to run remote commands thru ssh in Twisted? | 4,617,507 | 12 | 2011-01-06T17:02:12Z | 4,618,095 | 16 | 2011-01-06T18:03:32Z | [
"python",
"ssh",
"twisted"
] | I have a twisted application which now needs to monitor processes running on several boxes. The way I manually do is 'ssh and ps', now I'd like my twisted application to do. I have 2 options.
Use `paramiko` or leverage the power of `twisted.conch`
I really want to use `twisted.conch` but my research led me to believe... | Followup - Happily, the ticket I referenced below is now resolved. The simpler API will be included in the next release of Twisted. The original answer is still a valid way to use Conch and may reveal some interesting details about what's going on, but from Twisted 13.1 and on, if you just want to run a command and han... |
Python Twisted Daemon | 4,617,987 | 2 | 2011-01-06T17:52:54Z | 4,618,033 | 8 | 2011-01-06T17:58:32Z | [
"python",
"twisted",
"twisted.web",
"twisted.client",
"twisted.internet"
] | I have written a simple twisted server -
```
from twisted.internet import reactor
from twisted.internet import protocol
from twisted.web import server, resource
from twisted.internet import reactor
class Index(resource.Resource):
isLeaf = True
def render_GET(self, request):
args = request.args
... | I'd recommend looking into twistd. That way you don't have to worry about handling any of the start up, pid file management, etc. The documentation on their site is quite good: <http://twistedmatrix.com/documents/current/core/howto/basics.html>. Also check <http://twistedmatrix.com/documents/current/core/howto/tap.html... |
randomly mix lines of 3 million-line file | 4,618,298 | 13 | 2011-01-06T18:22:41Z | 4,618,361 | 21 | 2011-01-06T18:28:20Z | [
"python",
"vim",
"random",
"fortran"
] | Everything is in the title. I'm wondering if any one knows a quick and with reasonable memory demands way of randomly mixing all the lines of a 3 million lines file. I guess it is not possible with a simple vim command, so any simple script using python or fortran may be an option too... I tried with python by using a ... | Takes only a few seconds in Python:
```
>>> import random
>>> lines = open('3mil.txt').readlines()
>>> random.shuffle(lines)
>>> open('3mil.txt', 'w').writelines(lines)
``` |
randomly mix lines of 3 million-line file | 4,618,298 | 13 | 2011-01-06T18:22:41Z | 4,618,363 | 15 | 2011-01-06T18:28:33Z | [
"python",
"vim",
"random",
"fortran"
] | Everything is in the title. I'm wondering if any one knows a quick and with reasonable memory demands way of randomly mixing all the lines of a 3 million lines file. I guess it is not possible with a simple vim command, so any simple script using python or fortran may be an option too... I tried with python by using a ... | ```
import random
with open('the_file','r') as source:
data = [ (random.random(), line) for line in source ]
data.sort()
with open('another_file','w') as target:
for _, line in data:
target.write( line )
```
That should do it. 3 million lines will fit into most machine's memory unless the lines are HUG... |
How do I use the HTMLUnit driver with Selenium from Python? | 4,618,373 | 13 | 2011-01-06T18:29:37Z | 5,518,175 | 12 | 2011-04-01T19:55:22Z | [
"python",
"selenium-rc",
"htmlunit",
"selenium-webdriver"
] | How do I tell Selenium to use HTMLUnit?
I'm running selenium-server-standalone-2.0b1.jar as a Selenium server in the background, and the latest Python bindings installed with "pip install -U selenium".
Everything works fine with Firefox. But I'd like to use HTMLUnit, as it is lighter weight and doesn't need X. This i... | As of the 2.0b3 release of the python client you can create an HTMLUnit webdriver via a remote connection like so:
```
from selenium import webdriver
driver = webdriver.Remote(
desired_capabilities=webdriver.DesiredCapabilities.HTMLUNIT)
driver.get('http://www.google.com')
```
You can also use the `HTMLUNITWITHJS` ... |
Avoid object aliasing in python? | 4,619,367 | 5 | 2011-01-06T20:12:56Z | 4,619,706 | 9 | 2011-01-06T20:49:54Z | [
"python",
"alias"
] | I am trying to write a function to check whether a list is sorted (returning `True` or `False`). How can I avoid multiple variables pointing to the same thing?
```
def is_sorted(t):
a = t
a.sort()
```
When I do that, it sorts both `a` and `t`. How can I avoid this? | Here is the O(n) way to do it
```
>>> from itertools import islice, izip
>>> def is_sorted(L):
... return all(i<=j for i,j in izip(L, islice(L,1,None)))
...
>>> is_sorted(range(50))
True
>>> is_sorted(range(50)+[20])
False
```
It shortcircuits, so if the list is unsorted right near the beginning it will be very ... |
How to run Ruby/Python scripts from inside PHP passing and receiving parameters? | 4,619,996 | 8 | 2011-01-06T21:20:57Z | 4,621,239 | 12 | 2011-01-06T23:48:51Z | [
"php",
"python",
"html",
"ruby",
"markdown"
] | I need to turn HTML into equivalent Markdown-structured text.
OBS.: [Quick and clear way of doing this with PHP & Python](http://stackoverflow.com/questions/4686842/how-to-stdin-and-stdout-with-php-and-python-to-use-html2text-and-get-a-markdown-f).
As I am programming in PHP, some people indicates **Markdownify** to ... | Have PHP open the Ruby or Python script via [`proc_open`](http://www.php.net/manual/en/function.proc-open.php), piping the HTML into STDIN in the script. The Ruby/Python script reads and processes the data and returns it via STDOUT back to the PHP script, then exits. This is a common way of doing things via `popen`-lik... |
Partial order sorting? | 4,620,100 | 12 | 2011-01-06T21:32:18Z | 4,620,227 | 17 | 2011-01-06T21:44:34Z | [
"python",
"algorithm",
"topological-sort"
] | Say, we have some items, and each defines some partial sorting rules, like this:
> I'm `A` and I want to be before `B`
>
> I'm `C` and I want to be after `A` but before `D`
So we have items `A,B,C,D` with these rules:
* `A>B`
* `C<A`, `C>D`
* nothing else! So, `B` and `D` have no 'preferences' in ordering and are co... | You'll want to construct a [dependency graph](http://en.wikipedia.org/wiki/Dependency_graph) (which is just a flavor of directed graph), and then follow a [topologically sorted](http://en.wikipedia.org/wiki/Topological_sorting) ordering. It's been a while since I took a combinatorics class, so the Wikipedia article wil... |
How do I add an extra attribute in my input for Django forms? | 4,620,474 | 6 | 2011-01-06T22:10:03Z | 4,620,598 | 7 | 2011-01-06T22:23:12Z | [
"javascript",
"python",
"html",
"css",
"django"
] | ```
{{ theform.address }}
{{ theform.phone }}
```
This is what I do in my templates.
However, what if I want to add `placeholder="Username"` to the input text field? (Custom attribute)
```
<input type="text" name="address" id="id_address" placeholder="username"/>
``` | Add the `attrs` keyword argument to your field constructor's `widget`, and include write your attribute in there:
```
address = forms.TextField(widget=forms.TextInput(attrs={'placeholder': 'username'}))
```
If you want to see it in action, take a look at [django-registration's forms.py](https://github.com/nathanborro... |
Python: How to unshadow the keyword 'property'? | 4,621,718 | 3 | 2011-01-07T01:25:25Z | 4,621,758 | 8 | 2011-01-07T01:33:47Z | [
"python"
] | I am supporting a **legacy** python application which has a class written as such (still running in python 2.4):
```
class MyClass(object):
def property(self, property_code, default):
...
```
Now I am adding some new code to it:
```
def _check_ok(self):
...
ok = property(lamdba self:sel... | Python 2:
```
import __builtin__
__builtin__.property
```
Python 3:
```
import builtins
builtins.property
``` |
Plotting 3D Polygons in python-matplotlib | 4,622,057 | 35 | 2011-01-07T02:38:37Z | 4,622,449 | 34 | 2011-01-07T04:13:26Z | [
"python",
"matplotlib",
"plot"
] | I was unsuccessful browsing web for a solution for the following simple question:
---
How to draw 3D polygon (say a filled rectangle or triangle) using vertices values?
I have tried many ideas but all failed, see:
```
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
import ma... | I think you've almost got it. Is this what you want?
```
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
x = [0,1,1,0]
y = [0,0,1,1]
z = [0,1,0,1]
verts = [zip(x, y,z)]
ax.add_collection3d(Poly3DCollecti... |
How to convert a list to a csv in python | 4,622,234 | 3 | 2011-01-07T03:20:32Z | 4,622,245 | 9 | 2011-01-07T03:22:59Z | [
"python"
] | I have a list: ['1','2','3'] and want to convert it to 1,2,3 i.e. no brackets or quotation marks. | If you want to generate a canonical CSV file, use the [csv](http://docs.python.org/library/csv.html) module.
---
Example from the docs:
```
>>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'wb'), delimiter=' ',
... quotechar='|', quoting=csv.QUOTE_MINIMAL)
>>> spamWriter.writerow([... |
How to control padding of Unicode string containing east Asia characters | 4,622,357 | 4 | 2011-01-07T03:50:10Z | 4,632,373 | 8 | 2011-01-08T04:42:57Z | [
"python",
"unicode",
"string-formatting"
] | I got three UTF-8 stings:
```
hello, world
hello, ä¸ç
hello, ä¸rld
```
I only want the first 10 ascii-char-width so that the bracket in one column:
```
[hello, wor]
[hello, ä¸ ]
[hello, ä¸r]
```
In console:
```
width('ä¸ç')==width('worl')
width('ä¸ ')==width('wor') #a white space behind 'ä¸'
```
One c... | When trying to line up ASCII text with Chinese in fixed-width font, there is a set of full width versions of the printable ASCII characters. Below I made a translation table of ASCII to full width version:
```
# coding: utf8
# full width versions (SPACE is non-contiguous with ! through ~)
SPACE = '\N{IDEOGRAPHIC SPAC... |
Python finding substring between certain characters using regex and replace() | 4,622,472 | 11 | 2011-01-07T04:18:27Z | 4,622,606 | 9 | 2011-01-07T04:50:29Z | [
"python",
"regex",
"string",
"replace"
] | Suppose I have a string with lots of random stuff in it like the following:
```
strJunk ="asdf2adsf29Value=five&lakl23ljk43asdldl"
```
And I'm interested in obtaining the substring sitting between 'Value=' and '&', which in this example would be 'five'.
I can use a regex like the following:
```
match = re.search(r... | Named groups make it easier to get the group contents afterwards. Compiling your regex once, and then reusing the compiled object, will be much more efficient than recompiling it for each use (which is what happens when you call re.search repeatedly). You can use positive lookbehind and lookahead assertions to make thi... |
How do you sort files numerically? | 4,623,446 | 15 | 2011-01-07T07:34:12Z | 4,623,518 | 15 | 2011-01-07T07:48:16Z | [
"python",
"sorting"
] | First off, I'm posting this because when I was looking for a solution to the problem below, I could not find one on stackoverflow. So, I'm hoping to add a little bit to the knowledge base here.
I need to process some files in a directory and need the files to be sorted numerically. I found some examples on sorting--sp... | This is called "natural sorting" or "human sorting" (as opposed to lexicographical sorting, which is the default). [Ned B wrote up a quick version of one.](http://nedbatchelder.com/blog/200712/human_sorting.html)
```
import re
def tryint(s):
try:
return int(s)
except:
return s
def alphanum_ke... |
Is there support for sparse matrices in Python? | 4,623,800 | 10 | 2011-01-07T08:36:18Z | 4,626,929 | 23 | 2011-01-07T15:12:44Z | [
"python",
"numpy",
"scipy",
"sparse-matrix"
] | Is there support for sparse matrices in python?
Possibly in numpy or in scipy? | **Yes.**
SciPi provides [scipy.sparse](http://docs.scipy.org/doc/scipy/reference/sparse.html), a "2-D sparse matrix package for numeric data".
> There are seven available sparse matrix types:
>
> 1. csc\_matrix: Compressed Sparse Column format
> 2. csr\_matrix: Compressed Sparse Row format
> 3. bsr\_matrix: Block Spa... |
Get all text inside a tag in lxml | 4,624,062 | 33 | 2011-01-07T09:24:36Z | 4,624,146 | 23 | 2011-01-07T09:35:28Z | [
"python",
"parsing",
"lxml"
] | I'd like to write a code snippet that would grab all of the text inside the `<content>` tag, in lxml, in all three instances below, including the code tags. I've tried `tostring(getchildren())` but that would miss the text in between the tags. I didn't have very much luck searching the API for a relevant function. Coul... | Try:
```
def stringify_children(node):
from lxml.etree import tostring
from itertools import chain
parts = ([node.text] +
list(chain(*([c.text, tostring(c), c.tail] for c in node.getchildren()))) +
[node.tail])
# filter removes possible Nones in texts and tails
return ''.joi... |
Get all text inside a tag in lxml | 4,624,062 | 33 | 2011-01-07T09:24:36Z | 11,963,661 | 38 | 2012-08-15T03:14:52Z | [
"python",
"parsing",
"lxml"
] | I'd like to write a code snippet that would grab all of the text inside the `<content>` tag, in lxml, in all three instances below, including the code tags. I've tried `tostring(getchildren())` but that would miss the text in between the tags. I didn't have very much luck searching the API for a relevant function. Coul... | Does [text\_content()](http://lxml.de/lxmlhtml.html#html-element-methods) do what you need? |
Get all text inside a tag in lxml | 4,624,062 | 33 | 2011-01-07T09:24:36Z | 15,074,386 | 21 | 2013-02-25T19:00:23Z | [
"python",
"parsing",
"lxml"
] | I'd like to write a code snippet that would grab all of the text inside the `<content>` tag, in lxml, in all three instances below, including the code tags. I've tried `tostring(getchildren())` but that would miss the text in between the tags. I didn't have very much luck searching the API for a relevant function. Coul... | Just use the `node.itertext()` method, as in:
```
"".join([x for x in node.itertext()])
``` |
How to send custom http_headers for RPC calls using python xmlrpclib? | 4,624,085 | 2 | 2011-01-07T09:27:30Z | 4,708,099 | 9 | 2011-01-16T21:13:48Z | [
"python",
"http-headers",
"xml-rpc",
"xmlrpclib"
] | How can I send custom `HTTP Headers` using python `xmlrpclib` library ! ?
I need to send some special custom `http_headers` at the time of calling `RPC` methods. | You can subclass `xmlrpclib.Transport` and pass that as an argument to `ServerProxy`. Pick a method to override (I chose `send_content`) and you're set.
```
# simple test program (from the XML-RPC specification)
from xmlrpclib import ServerProxy, Transport, Error
class SpecialTransport(Transport):
def send_conte... |
Grouping 2D numpy array in average | 4,624,112 | 9 | 2011-01-07T09:32:07Z | 4,624,923 | 15 | 2011-01-07T11:17:21Z | [
"python",
"numpy"
] | I am trying to group a numpy array into smaller size by taking average of the elements. Such as take average foreach 5x5 sub-arrays in a 100x100 array to create a 20x20 size array. As I have a huge data need to manipulate, is that an efficient way to do that? | I have tried this for smaller array, so test it with yours:
```
import numpy as np
Nbig = 100
Nsmall = 20
big = np.arange(Nbig * Nbig).reshape([Nbig, Nbig]) # 100x100
small = big.reshape([Nsmall, Nbig/Nsmall, Nsmall, Nbig/Nsmall]).mean(3).mean(1)
```
An example with 6x6 -> 3x3:
```
Nbig = 6
Nsmall = 3
big = np.ara... |
Is there a posibility to execute a Python script while being in interactive mode | 4,624,416 | 28 | 2011-01-07T10:10:33Z | 4,624,441 | 18 | 2011-01-07T10:12:58Z | [
"python",
"interactive",
"mode"
] | Normally you can execute a Python script for example: python myscript.py, but if you are in the interactive mode, how is it possible to execute a Python script on the filesystem?
>>> exec(File) ???
It should be possible to execute the script more than one time. | `import file` without the .py extension will do it, however `__name__` will not be `"__main__"` so if the script does any checks to see if it's being run interactively you'll need to bypass them.
Alternately, if you're wanting to have a look at the environment after the script runs try `python -i script.py`
EDIT: To ... |
Is there a posibility to execute a Python script while being in interactive mode | 4,624,416 | 28 | 2011-01-07T10:10:33Z | 4,624,521 | 25 | 2011-01-07T10:22:06Z | [
"python",
"interactive",
"mode"
] | Normally you can execute a Python script for example: python myscript.py, but if you are in the interactive mode, how is it possible to execute a Python script on the filesystem?
>>> exec(File) ???
It should be possible to execute the script more than one time. | Use [execfile('script.py')](http://docs.python.org/library/functions.html#execfile) but it only work on python 2.x, if you are using 3.0 try [this](http://stackoverflow.com/questions/436198/what-is-an-alternative-to-execfile-in-python-3-0) |
Is there a posibility to execute a Python script while being in interactive mode | 4,624,416 | 28 | 2011-01-07T10:10:33Z | 4,624,846 | 7 | 2011-01-07T11:07:52Z | [
"python",
"interactive",
"mode"
] | Normally you can execute a Python script for example: python myscript.py, but if you are in the interactive mode, how is it possible to execute a Python script on the filesystem?
>>> exec(File) ???
It should be possible to execute the script more than one time. | You might want to look into [IPython](http://ipython.scipy.org/moin/), a more powerful interactive shell. It has various "magic" commands including `%run script.py` (which, of course, runs the script and leaves any variables it defined for you to examine). |
Building 64-bit C Python extensions on Windows | 4,624,507 | 22 | 2011-01-07T10:20:42Z | 5,171,276 | 7 | 2011-03-02T17:41:15Z | [
"python",
"c",
"64bit"
] | I am asking this question because I need to build a specific module (aspell\_python, <http://wm.ite.pl/proj/aspell-python/>) to work with my 64-bit Python 2.6 which runs on a Windows 7 (64-bit of course) machine. I also always wanted to know how to speed up certain functions with C code so I'd like to make my own exter... | I've successfully compiled C extensions for Python on 64-bit Windows before by running the following commands from the "Visual Studio 2008 x64 Win64 Command Prompt" in the top level directory of the source distribution of the extension:
```
set DISTUTILS_USE_SDK=1
set MSSdk=1
python setup.py install
``` |
Pulling python module up into package namespace | 4,624,754 | 7 | 2011-01-07T10:54:51Z | 4,624,798 | 13 | 2011-01-07T11:01:22Z | [
"python",
"namespaces"
] | If I have a directory structure like this:
```
package/
__init__.py
functions.py #contains do()
classes.py #contains class A()
```
And I want to be able to call
```
import package as p
```
How do I make the contents of `functions`, `classes`, accessible as:
```
p.do()
p.A()
```
**in stead ... | You *could* do this in `__init__.py` (because that's what you import when you `import package`):
```
from package.functions import *
from package.classes import *
```
However, [`import *` is nearly always a bad idea](http://docs.python.org/howto/doanddont.html#from-module-import) and this isn't one of the exceptions.... |
Finding local maxima/minima with Numpy in a 1D numpy array | 4,624,970 | 49 | 2011-01-07T11:22:09Z | 4,625,132 | 34 | 2011-01-07T11:41:35Z | [
"python",
"numpy"
] | Can you suggest a module function from numpy/scipy that can find local maxima/minima in a 1D numpy array? Obviously the simplest approach ever is to have a look at the nearest neighbours, but I would like to have an accepted solution that is part of the numpy distro. | If you are looking for all entries in the 1d array `a` smaller than their neighbors, you can try
```
numpy.r_[True, a[1:] < a[:-1]] & numpy.r_[a[:-1] < a[1:], True]
```
You could also [smooth](http://scipy-cookbook.readthedocs.org/items/SignalSmooth.html) your array before this step using `numpy.convolve()`.
I don't... |
Finding local maxima/minima with Numpy in a 1D numpy array | 4,624,970 | 49 | 2011-01-07T11:22:09Z | 9,667,121 | 22 | 2012-03-12T12:35:51Z | [
"python",
"numpy"
] | Can you suggest a module function from numpy/scipy that can find local maxima/minima in a 1D numpy array? Obviously the simplest approach ever is to have a look at the nearest neighbours, but I would like to have an accepted solution that is part of the numpy distro. | For curves with not too much noise, I recommend the following small code snippet:
```
from numpy import *
# example data with some peaks:
x = linspace(0,4,1e3)
data = .2*sin(10*x)+ exp(-abs(2-x)**2)
# that's the line, you need:
a = diff(sign(diff(data))).nonzero()[0] + 1 # local min+max
b = (diff(sign(diff(data))) >... |
Finding local maxima/minima with Numpy in a 1D numpy array | 4,624,970 | 49 | 2011-01-07T11:22:09Z | 13,491,866 | 96 | 2012-11-21T11:03:50Z | [
"python",
"numpy"
] | Can you suggest a module function from numpy/scipy that can find local maxima/minima in a 1D numpy array? Obviously the simplest approach ever is to have a look at the nearest neighbours, but I would like to have an accepted solution that is part of the numpy distro. | In SciPy >= 0.11
```
import numpy as np
from scipy.signal import argrelextrema
x = np.random.random(12)
# for local maxima
argrelextrema(x, np.greater)
# for local minima
argrelextrema(x, np.less)
```
Produces
```
>>> x
array([ 0.56660112, 0.76309473, 0.69597908, 0.38260156, 0.24346445,
0.56021785, 0.241... |
Finding local maxima/minima with Numpy in a 1D numpy array | 4,624,970 | 49 | 2011-01-07T11:22:09Z | 19,825,314 | 7 | 2013-11-06T23:49:55Z | [
"python",
"numpy"
] | Can you suggest a module function from numpy/scipy that can find local maxima/minima in a 1D numpy array? Obviously the simplest approach ever is to have a look at the nearest neighbours, but I would like to have an accepted solution that is part of the numpy distro. | Another approach (more words, less code) that may help:
The locations of local maxima and minima are also the locations of the zero crossings of the first derivative. It is generally much easier to find zero crossings than it is to directly find local maxima and minima.
Unfortunately, the first derivative tends to "a... |
How to replace a Widget with another using Qt? | 4,625,102 | 6 | 2011-01-07T11:38:16Z | 4,625,175 | 15 | 2011-01-07T11:47:51Z | [
"python",
"qt",
"pyqt"
] | I have an `QHBoxLayout` with a `QTreeWidget` on the left, a separator on the middle and a widget on the right.
When I click on the `QTreeWidget`, I want to change the widget on the right to modify the `QTreeWidgetItem`
I tried to do this with this code :
```
def new_rendez_vous(self):
self.ui.horizontalLayout_4.... | The most common solution is to use [`QStackedWidget`](http://pyqt.sourceforge.net/Docs/PyQt4/qstackedwidget.html) and put all possible widgets into the stack. When selecting an item, just call `setCurrentWidget` to display the one you want. |
How to replace a Widget with another using Qt? | 4,625,102 | 6 | 2011-01-07T11:38:16Z | 6,143,874 | 11 | 2011-05-26T19:17:42Z | [
"python",
"qt",
"pyqt"
] | I have an `QHBoxLayout` with a `QTreeWidget` on the left, a separator on the middle and a widget on the right.
When I click on the `QTreeWidget`, I want to change the widget on the right to modify the `QTreeWidgetItem`
I tried to do this with this code :
```
def new_rendez_vous(self):
self.ui.horizontalLayout_4.... | I have the same question as Natim.
The QStackedWidget is a solution for a preset layout. It acts like the flippy thing in an old diner for a music box. (X-amount of albums in the jukebox, flip through the installed albums).
However this does not solve the question.
For instance I have code I am prototyping with a UI... |
python lock method annotation | 4,625,182 | 12 | 2011-01-07T11:49:18Z | 4,625,483 | 14 | 2011-01-07T12:34:34Z | [
"python",
"locking",
"annotations"
] | Is there a python lock annotation which has the same effect to a python method as the "synchronized" keyword to java methods? | I can assume that no builtin feature exist in python but you can implement it by understanding how it work in Java from [this](http://www.javamex.com/tutorials/synchronization_concurrency_synchronized1.shtml) link :
> Every Java object created, including
> every Class loaded, has an associated
> lock or monitor. Putti... |
mask a 2D numpy array based on values in one column | 4,625,744 | 8 | 2011-01-07T13:08:20Z | 4,625,803 | 7 | 2011-01-07T13:14:53Z | [
"python",
"arrays",
"numpy",
"mask"
] | Suppose I have the following numpy array:
```
a = [[1, 5, 6],
[2, 4, 1],
[3, 1, 5]]
```
I want to mask all the rows which have `1` in the first column. That is, I want
```
[[--, --, --],
[2, 4, 1],
[3, 1, 5]]
```
Is this possible to do using numpy masked array operations? How can one do it?
... | ```
import numpy as np
a = np.array([[1, 5, 6],
[2, 4, 1],
[3, 1, 5]])
np.ma.MaskedArray(a, mask=(np.ones_like(a)*(a[:,0]==1)).T)
# Returns:
masked_array(data =
[[-- -- --]
[2 4 1]
[3 1 5]],
mask =
[[ True True True]
[False False False]
[False False False]])
``` |
Creating a dictionary from a string | 4,627,981 | 7 | 2011-01-07T16:49:11Z | 4,628,007 | 15 | 2011-01-07T16:51:25Z | [
"python",
"string",
"dictionary"
] | I have a string in the form of:
```
s = 'A - 13, B - 14, C - 29, M - 99'
```
and so on (the length varies). What is the easiest way to create a dictionary from this?
```
A: 13, B: 14, C: 29 ...
```
I know I can split but I can't get the right syntax on how to do it. If I split on `-`, then how do I join the two par... | To solve your example you can do this:
```
mydict = dict((k.strip(), v.strip()) for k,v in
(item.split('-') for item in s.split(',')))
```
It does 3 things:
* split the string into `"<key> - <value>"` parts: `s.split(',')`
* split each part into `"<key> ", " <value>"` pairs: `item.split('-')`
* remove... |
Creating a dictionary from a string | 4,627,981 | 7 | 2011-01-07T16:49:11Z | 4,628,011 | 9 | 2011-01-07T16:51:46Z | [
"python",
"string",
"dictionary"
] | I have a string in the form of:
```
s = 'A - 13, B - 14, C - 29, M - 99'
```
and so on (the length varies). What is the easiest way to create a dictionary from this?
```
A: 13, B: 14, C: 29 ...
```
I know I can split but I can't get the right syntax on how to do it. If I split on `-`, then how do I join the two par... | ```
>>> s = 'A - 13, B - 14, C - 29, M - 99'
>>> dict(e.split(' - ') for e in s.split(','))
{'A': '13', 'C': '29', 'B': '14', 'M': '99'}
```
EDIT: The next solution is for when you want the values as integers, which I think is what you want.
```
>>> dict((k, int(v)) for k, v in (e.split(' - ') for e in s.split(',')))... |
How to construct a timedelta object from a simple string | 4,628,122 | 42 | 2011-01-07T17:03:48Z | 4,628,148 | 36 | 2011-01-07T17:06:25Z | [
"python",
"timedelta"
] | I'm writing a function that needs a timedelta input to be passed in as a string. The user must enter something like "32m" or "2h32m", or even "4:13" or "5hr34m56s"... Is there a library or something that has this sort of thing already implemented? | for the 4:13, and other standard formats(but if you don't know which one) use dateutil.parser.parse from [python-dateutil](http://niemeyer.net/python-dateutil)
For the first format(5hr34m56s), you should parse using regular expressions
Here is re-based solution:
```
import re
from datetime import timedelta
regex =... |
How to construct a timedelta object from a simple string | 4,628,122 | 42 | 2011-01-07T17:03:48Z | 12,352,624 | 29 | 2012-09-10T13:20:58Z | [
"python",
"timedelta"
] | I'm writing a function that needs a timedelta input to be passed in as a string. The user must enter something like "32m" or "2h32m", or even "4:13" or "5hr34m56s"... Is there a library or something that has this sort of thing already implemented? | To me the most elegant solution, without having to resort to external libraries such as [dateutil](http://niemeyer.net/python-dateutil) or manually parsing the input, is to use [datetime's](http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior) powerful `strptime` string parsing method.
```
from ... |
How to construct a timedelta object from a simple string | 4,628,122 | 42 | 2011-01-07T17:03:48Z | 21,498,018 | 20 | 2014-02-01T12:26:20Z | [
"python",
"timedelta"
] | I'm writing a function that needs a timedelta input to be passed in as a string. The user must enter something like "32m" or "2h32m", or even "4:13" or "5hr34m56s"... Is there a library or something that has this sort of thing already implemented? | I had a bit of time on my hands yesterday, so I developed [@virhilo](http://stackoverflow.com/users/492048/virhilo)'s [answer](http://stackoverflow.com/a/4628148) into a Python module, adding a few more time expression formats, including all those requested by [@priestc](http://stackoverflow.com/users/118495/priestc).
... |
Pairs from single list | 4,628,290 | 51 | 2011-01-07T17:20:04Z | 4,628,365 | 21 | 2011-01-07T17:27:00Z | [
"list",
"zip",
"python",
"slice"
] | Often enough, I've found the need to process a list by pairs. I was wondering which would be the pythonic and efficient way to do it, and found this on Google:
```
pairs = zip(t[::2], t[1::2])
```
I thought that was pythonic enough, but after a recent discussion involving [idioms versus efficiency](http://stackoverfl... | I'd say that your initial solution `pairs = zip(t[::2], t[1::2])` is the best one because it is easiest to read (and in Python 3, `zip` automatically returns an iterator instead of a list).
To ensure that all elements are included, you could simply extend the list by `None`.
Then, if the list has an odd number of ele... |
Pairs from single list | 4,628,290 | 51 | 2011-01-07T17:20:04Z | 4,628,446 | 20 | 2011-01-07T17:35:40Z | [
"list",
"zip",
"python",
"slice"
] | Often enough, I've found the need to process a list by pairs. I was wondering which would be the pythonic and efficient way to do it, and found this on Google:
```
pairs = zip(t[::2], t[1::2])
```
I thought that was pythonic enough, but after a recent discussion involving [idioms versus efficiency](http://stackoverfl... | My favorite way to do it:
```
from itertools import izip
def pairwise(t):
it = iter(t)
return izip(it,it)
# for "pairs" of any length
def chunkwise(t, size=2):
it = iter(t)
return izip(*[it]*size)
```
When you want to pair all elements you obviously might need a fillvalue:
```
from itertools import... |
converting a list of integers into range in python | 4,628,333 | 7 | 2011-01-07T17:24:47Z | 4,629,241 | 11 | 2011-01-07T19:04:50Z | [
"python",
"list",
"range",
"integer"
] | Is there something existing in python that can convert an increasing list of integers into a range list
E.g. given the set {0, 1, 2, 3, 4, 7, 8, 9, 11} I want to get { {0,4}, {7,9}, {11,11} }.
I can write a program to do this, but want to know if there is an inbuilt function in python | Using itertools.groupby produces a concise but tricky implementation:
```
import itertools
def ranges(i):
for a, b in itertools.groupby(enumerate(i), lambda (x, y): y - x):
b = list(b)
yield b[0][1], b[-1][1]
print list(ranges([0, 1, 2, 3, 4, 7, 8, 9, 11]))
```
Output:
```
[(0, 4), (7, 9), (11,... |
How can I created a PIL Image from an in-memory file? | 4,628,529 | 7 | 2011-01-07T17:45:27Z | 4,628,676 | 18 | 2011-01-07T17:58:29Z | [
"python",
"django",
"python-imaging-library",
"django-models"
] | More specifically, I want to change the filetype of an image uploaded through a Django ImageField.
My current thinking is to created a custom ImageField and overwrite the save method to manipulate the file.
I've having trouble getting an in memory file to because a PIL Image instance.
Thanks for the help. | Have you tried StringIO ?
see the docs <http://effbot.org/imagingbook/introduction.htm#more-on-reading-images>
```
#Reading from a string
import StringIO
im = Image.open(StringIO.StringIO(buffer))
``` |
How can I created a PIL Image from an in-memory file? | 4,628,529 | 7 | 2011-01-07T17:45:27Z | 4,628,840 | 8 | 2011-01-07T18:19:53Z | [
"python",
"django",
"python-imaging-library",
"django-models"
] | More specifically, I want to change the filetype of an image uploaded through a Django ImageField.
My current thinking is to created a custom ImageField and overwrite the save method to manipulate the file.
I've having trouble getting an in memory file to because a PIL Image instance.
Thanks for the help. | Note that Django's `ImageField` inherits the `open` method from `FieldFile`. This returns a stream object that can be passed to PIL's `Image.open` (the standard factory method for creating `Image` objects from an image stream):
```
stream = imagefield.open()
image = Image.open(stream)
stream.close()
# ... and then sav... |
Replace first occurence of string | 4,628,618 | 39 | 2011-01-07T17:53:10Z | 4,628,642 | 7 | 2011-01-07T17:55:14Z | [
"python",
"regex"
] | I have some sample string. How can I replace first occurrence of this string in longer string with empty sign? Tried this but it's not working as far as I can see.
```
regex = re.compile('text')
match = regex.match(url)
if match:
url = url.replace(regex, '')
``` | Use [`re.sub`](http://docs.python.org/library/re.html#re.sub) directly, this allows you to specify a `count`:
```
regex.sub('', url, 1)
```
(Note that the order of arguments is `replacement`, `original` not the opposite, as might be suspected.) |
Replace first occurence of string | 4,628,618 | 39 | 2011-01-07T17:53:10Z | 4,628,646 | 106 | 2011-01-07T17:55:30Z | [
"python",
"regex"
] | I have some sample string. How can I replace first occurrence of this string in longer string with empty sign? Tried this but it's not working as far as I can see.
```
regex = re.compile('text')
match = regex.match(url)
if match:
url = url.replace(regex, '')
``` | string [replace()](https://docs.python.org/2/library/string.html#string.replace) function if perfectly solves this problem:
> string.replace(s, old, new[, maxreplace])
>
> Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace... |
Best way to parse xml in Appengine with Python | 4,628,771 | 5 | 2011-01-07T18:10:44Z | 4,629,089 | 7 | 2011-01-07T18:46:56Z | [
"python",
"google-app-engine",
"xml-deserialization"
] | I am connecting to isbndb.com for book information and their response looks like this:
```
<?xml version="1.0" encoding="UTF-8"?>
<ISBNdb server_time="2005-02-25T23:03:41">
<BookList total_results="1" page_size="10" page_number="1" shown_results="1">
<BookData book_id="somebook" isbn="0123456789">
<Title>Interes... | use etree:)
```
>>> xml = """<?xml version="1.0" encoding="UTF-8"?>
... <ISBNdb server_time="2005-02-25T23:03:41">
... <BookList total_results="1" page_size="10" page_number="1" shown_results="1">
... <BookData book_id="somebook" isbn="0123456789">
... <Title>Interesting Book</Title>
... <TitleLong>Interestin... |
building jsoncpp (Linux) - an instruction for us mere mortals? | 4,628,922 | 10 | 2011-01-07T18:27:19Z | 4,629,086 | 26 | 2011-01-07T18:46:31Z | [
"c++",
"python",
"linux",
"json",
"scons"
] | I am trying to build jsoncpp on Ubuntu 10.x - however the 'instructions' are at times vague. For example, it is not clear exactly which folder the scons.py file needs to reside in before the lib can be built.
Can someone outline the steps required to build the jsoncpp library? on Linux, or failing that, if anyone is a... | Here's what I did:
```
apt-get install scons
wget "http://downloads.sourceforge.net/project/jsoncpp/jsoncpp/0.5.0/jsoncpp-src-0.5.0.tar.gz?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fjsoncpp%2F&ts=1294425421&use_mirror=freefr"
tar -xvzf jsoncpp-src-0.5.0.tar.gz
cd jsoncpp-src-0.5.0
scons platform=linux-gcc
```
jsoncp... |
Best way to build an application based on R? | 4,629,198 | 25 | 2011-01-07T18:59:42Z | 4,629,608 | 10 | 2011-01-07T19:47:55Z | [
"python",
"user-interface"
] | I'm looking for suggestions on how to go about building an application that uses `R` for analytics, table generation, and plotting. What I have in mind is an application that:
* displays various data tables in different tabs, somewhat like in Excel, and the columns should be sortable by clicking.
* takes user input pa... | There are lots of ways to do this, including the python approach you mention. If you want to do it solely within R and if your aims are modest enough, the gWidgets package can be used. This exposes some of the features of either RGtk2, tcltk or qtbase (see the qtinterfaces project on r-forge) in a manner that is about ... |
Best way to build an application based on R? | 4,629,198 | 25 | 2011-01-07T18:59:42Z | 4,629,949 | 7 | 2011-01-07T20:24:54Z | [
"python",
"user-interface"
] | I'm looking for suggestions on how to go about building an application that uses `R` for analytics, table generation, and plotting. What I have in mind is an application that:
* displays various data tables in different tabs, somewhat like in Excel, and the columns should be sortable by clicking.
* takes user input pa... | Python + Qt4 + RPy = Much Win.
For example, see what Carson Farmer has done with Qgis and the ManageR plugin - its a full R interface to geographic data in the Qgis mapping package.
Depending on how much statistical functionality you need you might even get away without needing it at all, doing all the stats in Pytho... |
Prototypal programming in Python | 4,629,224 | 6 | 2011-01-07T19:02:32Z | 4,630,006 | 7 | 2011-01-07T20:29:37Z | [
"javascript",
"python",
"inheritance",
"prototype",
"prototypal-inheritance"
] | Javascript uses a prototype-based model for its objects. Nevertheless, the language is very flexible, and it is easy to write in a few lines functions which replace other kind on constructs. For instance, one can make a `class` function, emulating the standard class behaviour, including inheritance or private members. ... | It's much easier in Python than in JS. Your JS code could be replaced with this in Python:
```
>>> class Foo(object):
... pass
>>> foo = Foo()
>>> foo.bar = 1
>>> foo.foobar = 2
```
Then you can add methods dynamically as well
```
>>> foo.method = lambda x: x**2
>>> foo.method(2)
4
```
For methods more compli... |
PyQt4: How do you iterate all items in a QListWidget | 4,629,584 | 16 | 2011-01-07T19:45:42Z | 4,629,770 | 15 | 2011-01-07T20:05:53Z | [
"python",
"pyqt4",
"qlistwidget"
] | Currently, I use the following while loop in a class that inherits QtGui.QListWidget to iterate all items:
```
i = 0
while i < self.count():
item = self.item(i)
i += 1
```
I was hoping I could use:
```
for item in self.items():
```
but the items() method wants a QMimeData object which I don... | I don't know what's it with the MIME type either, and I couldn't find a convenience method either. But you could write a simple method like this and be done:
```
def iterAllItems(self):
for i in range(self.count()):
yield self.item(i)
```
It's even lazy (a generator). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.