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 |
|---|---|---|---|---|---|---|---|---|---|
ImportError: No module named PIL | 8,863,917 | 41 | 2012-01-14T17:24:27Z | 17,806,284 | 19 | 2013-07-23T09:24:18Z | [
"python",
"python-imaging-library",
"easy-install"
] | I use this command in the shell to install PIL:
```
easy_install PIL
```
then I run `python` and type this: `import PIL`. But I get this error:
```
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named PIL
```
I've never had such problem, what do you think? | On a different note, I can highly recommend the use of [Pillow](https://pypi.python.org/pypi/Pillow) which is backwards compatible with PIL and is better maintained/will work on newer systems.
When that is installed you can do
```
import PIL
```
or
```
from PIL import Image
```
etc.. |
ImportError: No module named PIL | 8,863,917 | 41 | 2012-01-14T17:24:27Z | 22,722,950 | 32 | 2014-03-28T20:49:48Z | [
"python",
"python-imaging-library",
"easy-install"
] | I use this command in the shell to install PIL:
```
easy_install PIL
```
then I run `python` and type this: `import PIL`. But I get this error:
```
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named PIL
```
I've never had such problem, what do you think? | In shell, run:
```
pip install image
```
Attention: PIL is deprecated, and [pillow](http://pillow.readthedocs.org/en/3.0.x/) is the successor. |
ImportError: No module named PIL | 8,863,917 | 41 | 2012-01-14T17:24:27Z | 35,395,419 | 9 | 2016-02-14T18:24:38Z | [
"python",
"python-imaging-library",
"easy-install"
] | I use this command in the shell to install PIL:
```
easy_install PIL
```
then I run `python` and type this: `import PIL`. But I get this error:
```
Traceback (most recent call last):
File "<console>", line 1, in <module>
ImportError: No module named PIL
```
I've never had such problem, what do you think? | At first install Pillow with
```
pip install Pillow
```
or as follows
```
c:\Python35>python -m pip install Pillow
```
Then in python code you may call
```
from PIL import Image
```
"Pillow is a fork of PIL, the Python Imaging Library, which is no longer maintained. However, to maintain backwards compatibility, t... |
How to declare a dictionary with inline function | 8,864,153 | 6 | 2012-01-14T17:55:57Z | 9,013,966 | 8 | 2012-01-26T04:32:25Z | [
"python"
] | Do I have to formally define a function before I can use it as an element of a dictionary?
```
def my_func():
print 'my_func'
d = {
'function': my_func
}
```
I would rather define the function inline. I just tried to type out what I want to do, but the whitespace policies of python syntax make it very hard to de... | The answer seems to be that there is no way to declare a function inline a dictionary definition in python. Thanks to everyone who took the time to contribute. |
Django/Python update field values (during model save) | 8,864,716 | 4 | 2012-01-14T19:19:03Z | 8,864,743 | 7 | 2012-01-14T19:23:25Z | [
"python",
"django",
"django-models"
] | I am trying to capitalize a number of fields in my django models, when they are saved. Looking at [this question](http://stackoverflow.com/questions/825955/changing-case-upper-lower-on-adding-data-through-django-admin-site), which had [this](http://stackoverflow.com/a/826126/907060) answer:
```
class Blog(models.Model... | You can use setattr(self, my\_field\_name, value) to achieve this.
```
for field in ['first_name', 'last_name']:
value = getattr(self, field)
setattr(self, field, value.title())
```
You won't be able to modify the value in-place as strings are immutables in Python. |
Tree traversing or what? | 8,864,975 | 3 | 2012-01-14T20:02:46Z | 8,865,057 | 8 | 2012-01-14T20:14:59Z | [
"python",
"tree",
"nlp"
] | In Python, I'm writing a Natural Language Processing module and can't work out how to code a function to do the following.
Input: a list of parts of speech (POS) derived from an inputted sentence as short strings. Some items in the list are themselves lists because that part of the program doesn't know which part of sp... | You should look at the [itertools module](http://docs.python.org/library/itertools.html) and the associated recipes. It looks like you want to consider the Cartesian product of all possible POS assignments. This can be easily done, although it's more convenient to have all elements of INPUT be lists, even if they're on... |
How to move a camera in Blender 2.61 with Python | 8,865,672 | 8 | 2012-01-14T21:58:27Z | 10,652,860 | 10 | 2012-05-18T12:42:17Z | [
"python",
"blender",
"blender-2.61"
] | I'm searching for a simple script to move a camera in Blender 2.61 with Python.
I thought this would be an easy task, but the Camera object has no properties like loc or something similar.
I only found scripts online for Blender 2.49 but they don't work anymore because of the immense API changes with Blender 2.5.
I w... | furtelwart's answer was quite usefull. I did some more digging so you can also set some other very usefull properties regarding the camera and render.
```
import bpy
tx = 0.0
ty = 0.0
tz = 80.0
rx = 0.0
ry = 0.0
rz = 0.0
fov = 50.0
pi = 3.14159265
scene = bpy.data.scenes["Scene"]
# Set render resolution
scene.re... |
Python Shell in Emacs 24? | 8,865,867 | 29 | 2012-01-14T22:27:55Z | 9,729,139 | 17 | 2012-03-15T22:29:18Z | [
"python",
"emacs",
"emacs24"
] | I recently upgraded from Emacs 23 to Emacs 24. Since the upgrade, it seems that I've lost the ability to call "M-x python-shell" (!).
What happened? Does the included python mode no longer ship with this functionality?
Using Emacs 23:
```
â /usr/local/bin/emacs -Q
Describe function: python-shell
python-shell ... | It seems like you only solved the `python-mode` issue. As to `M-x-python-shell` you can also get this by doing `M-x-run-python`. If it says directory not found its because the the python variable is not pointing to the correct path. So do `C-h-f run-python` then it will tell you that run-python's value is python-shell-... |
Python Shell in Emacs 24? | 8,865,867 | 29 | 2012-01-14T22:27:55Z | 10,176,706 | 12 | 2012-04-16T15:06:23Z | [
"python",
"emacs",
"emacs24"
] | I recently upgraded from Emacs 23 to Emacs 24. Since the upgrade, it seems that I've lost the ability to call "M-x python-shell" (!).
What happened? Does the included python mode no longer ship with this functionality?
Using Emacs 23:
```
â /usr/local/bin/emacs -Q
Describe function: python-shell
python-shell ... | Turns out this functionality is no longer available with Emacs' native python mode. However, it can be added back by installing `python-mode` via the package manager (although it is now named `py-shell` instead of `python-shell`). Here are the steps that I used to resolve this:
1. I'm not sure if you need the Marmalad... |
Skipping every other element after the first | 8,865,878 | 9 | 2012-01-14T22:29:28Z | 8,865,901 | 21 | 2012-01-14T22:33:39Z | [
"python",
"for-loop",
"elements"
] | I have the general idea of how to do this in Java, but I am learning Python and not sure how to do it.
I need to implement a function that returns a list containing every other element of the list, starting with the first element.
Thus far, I have and not sure how to do from here since I am just learning how for-loop... | Slice notation `a[start_index:end_index:step]`
```
return a[::2]
```
where `start_index` defaults to `0` and `end_index` defaults to the `len(a)`. |
Skipping every other element after the first | 8,865,878 | 9 | 2012-01-14T22:29:28Z | 8,865,905 | 25 | 2012-01-14T22:34:19Z | [
"python",
"for-loop",
"elements"
] | I have the general idea of how to do this in Java, but I am learning Python and not sure how to do it.
I need to implement a function that returns a list containing every other element of the list, starting with the first element.
Thus far, I have and not sure how to do from here since I am just learning how for-loop... | ```
def altElement(a):
return a[::2]
``` |
Python round up integer to next hundred | 8,866,046 | 29 | 2012-01-14T22:52:42Z | 8,866,054 | 11 | 2012-01-14T22:54:24Z | [
"python",
"math"
] | Seems that should have already been asked hundreds (pun are fun =) of times but i can only find function for rounding floats. How do I round up an integer, for example: `130 -> 200` ? | Try this:
```
int(round(130 + 49, -2))
``` |
Python round up integer to next hundred | 8,866,046 | 29 | 2012-01-14T22:52:42Z | 8,866,125 | 56 | 2012-01-14T23:07:49Z | [
"python",
"math"
] | Seems that should have already been asked hundreds (pun are fun =) of times but i can only find function for rounding floats. How do I round up an integer, for example: `130 -> 200` ? | Rounding is typically done on floating point numbers, and here there are three basic functions you should know: [`round`](http://docs.python.org/library/functions.html#round) (rounds to the nearest integer), [`math.floor`](http://docs.python.org/library/math.html#math.floor) (always rounds down), and [`math.ceil`](http... |
Python round up integer to next hundred | 8,866,046 | 29 | 2012-01-14T22:52:42Z | 8,866,236 | 14 | 2012-01-14T23:23:12Z | [
"python",
"math"
] | Seems that should have already been asked hundreds (pun are fun =) of times but i can only find function for rounding floats. How do I round up an integer, for example: `130 -> 200` ? | Here's a general way of rounding up to the nearest multiple of any positive integer:
```
def roundUpToMultiple(number, multiple):
num = number + (multiple - 1)
return num - (num % multiple)
```
Sample usage:
```
>>> roundUpToMultiple(101, 100)
200
>>> roundUpToMultiple(654, 321)
963
``` |
Python round up integer to next hundred | 8,866,046 | 29 | 2012-01-14T22:52:42Z | 14,092,788 | 7 | 2012-12-30T17:18:50Z | [
"python",
"math"
] | Seems that should have already been asked hundreds (pun are fun =) of times but i can only find function for rounding floats. How do I round up an integer, for example: `130 -> 200` ? | This is a late answer, but there's a simple solution that combines the best aspects of the existing answers: the next multiple of `100` up from `x` is `x - x % -100` (or if you prefer, `x + (-x) % 100`).
```
>>> x = 130
>>> x -= x % -100 # Round x up to next multiple of 100.
>>> x
200
```
This is fast and simple, gi... |
Determine if 2 lists have the same elements, regardless of order? | 8,866,652 | 56 | 2012-01-15T00:39:10Z | 8,866,661 | 73 | 2012-01-15T00:40:53Z | [
"python",
"list",
"equality",
"python-2.x"
] | Sorry for the simple question, but I'm having a hard time finding the answer.
When I compare 2 lists, I want to know if they are "equal" in that they have the same contents, but in different order.
Ex:
```
x = ['a', 'b']
y = ['b', 'a']
```
I want `x == y` to evaluate to `True`. | You can simply check whether the multisets with the elements of x and y are equal:
```
import collections
collections.Counter(x) == collections.Counter(y)
```
This requires the elements to be hashable; runtime will be in `O(n)`, where `n` is the size of the lists.
If the elements are also unique, you can also conver... |
Is there any case in python when using a while loop would be best practice? | 8,867,043 | 4 | 2012-01-15T02:09:22Z | 8,867,275 | 9 | 2012-01-15T03:08:20Z | [
"python",
"for-loop",
"while-loop",
"repeat",
"itertools"
] | I'm doing some python benchmarking, and I've discovered that `repeat(None)` is much faster than `while True` or `while 1`:
```
>>> def bench7():
... foo = 0
... a = time()
... for i in repeat(None):
... foo += 1
... if foo == 100000000:
... break
... b = time()
... print a, b, b-a
...
>>> def ... | The `while True` is only slower because of the global lookup for `True`. If you use `while 1` instead, the while-loop should handily beat the for-repeat (at least in terms of speed, beauty, and clarity):
```
>>> from dis import dis
>>> def f():
while True:
print
>>> dis(f)
2 0 SETUP_LO... |
adding extra fields to django-userena forms | 8,868,040 | 7 | 2012-01-15T06:47:47Z | 8,884,511 | 11 | 2012-01-16T18:24:13Z | [
"python",
"django",
"registration"
] | I am using `django-userena`. I have a model called `UserProfile`. I've added extra fields in signup form. and These fields are show up correctly but data is not saved. I want to save some fields data into another Model (`Business`) too. For example I've two field like `contact` and `business`. I want contact field will... | Author of Userena here. I already had an e-mail correspondence with "no\_access", but it's worth pointing to the solution if others have the same problem. The first mistake was that the `save` method returns a profile. This is not true, it returns a Django `User`. Because of this you first have to fetch the profile and... |
How to create <!DOCTYPE> with Python's cElementTree | 8,868,248 | 8 | 2012-01-15T07:38:08Z | 8,868,551 | 8 | 2012-01-15T08:52:48Z | [
"python",
"xml",
"elementtree"
] | I have tried to use the answer in this question, but can't make it work: [How to create "virtual root" with Python's ElementTree?](http://stackoverflow.com/questions/1070772/how-to-create-virtual-root-with-pythons-elementtree)
Here's my code:
```
import xml.etree.cElementTree as ElementTree
from StringIO import Strin... | You could set [xml\_declaration](http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.ElementTree.write) argument on `write` function to False, so output won't have xml declaration with encoding, then just append what header you need manually. Actually if you set your encoding as 'utf-8' (low... |
Problems with Rounding Decimals (python) | 8,868,985 | 18 | 2012-01-15T10:25:43Z | 8,869,027 | 35 | 2012-01-15T10:33:45Z | [
"python",
"decimal",
"rounding"
] | In my program, decimal accuracy is very important.
A lot of my calculations must be accurate to many decimal places (such as 50).
Because I am using python, I have been using the decimal module
(with context().prec = 99. ie; *Set to have 99 decimal places of accuracy when instantiating a decimal object*)
as python... | Since *[round()](http://docs.python.org/library/functions.html#round)* coerces its input to a regular binary float, the preferred way to round decimal objects is with the *[quantize()](http://docs.python.org/library/decimal.html#decimal.Decimal.quantize)* method:
```
>>> from decimal import Decimal
>>> d = Decimal('2.... |
How/Why does this work in python? rover._Dog__password() | 8,869,847 | 3 | 2012-01-15T13:11:11Z | 8,869,880 | 7 | 2012-01-15T13:15:55Z | [
"python",
"class",
"syntax",
"methods",
"private"
] | I am doing [the python koan](https://bitbucket.org/gregmalcolm/python_koans/wiki/Home) (for python 2.6) and ecnountered something I don't understand. [One of the files](https://bitbucket.org/gregmalcolm/python_koans/src/81e0997715bb/python%202/koans/about_methods.py) has the following code in line 160:
```
class Dog(o... | **Double underscore :**
> Any identifier of the form `__spam` (at least two leading underscores,
> at most one trailing underscore) is textually replaced with
> `_classname__spam`, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard
> to the syntactic pos... |
How to split text without spaces into list of words? | 8,870,261 | 44 | 2012-01-15T14:10:24Z | 8,870,388 | 8 | 2012-01-15T14:25:51Z | [
"python",
"algorithm",
"text",
"split"
] | **Input:** `"tableapplechairtablecupboard..."` many words
What would be an efficient algorithm to split such text to the list of words and get:
**Output:** `["table", "apple", "chair", "table", ["cupboard", ["cup", "board"]], ...]`
First thing that cames to mind is to go through all possible words (starting with fir... | Using a [trie](http://en.wikipedia.org/wiki/Trie) [data structure](http://www.eecs.harvard.edu/~ellard/Q-97/HTML/root/node22.html), which holds the list of possible words, it would not be too complicated to do the following:
1. Advance pointer (in the concatenated string)
2. Lookup and store the corresponding node in ... |
How to split text without spaces into list of words? | 8,870,261 | 44 | 2012-01-15T14:10:24Z | 8,870,575 | 12 | 2012-01-15T14:49:55Z | [
"python",
"algorithm",
"text",
"split"
] | **Input:** `"tableapplechairtablecupboard..."` many words
What would be an efficient algorithm to split such text to the list of words and get:
**Output:** `["table", "apple", "chair", "table", ["cupboard", ["cup", "board"]], ...]`
First thing that cames to mind is to go through all possible words (starting with fir... | Here is solution using recursive search:
```
def find_words(instring, prefix = '', words = None):
if not instring:
return []
if words is None:
words = set()
with open('/usr/share/dict/words') as f:
for line in f:
words.add(line.strip())
if (not prefix) an... |
How to split text without spaces into list of words? | 8,870,261 | 44 | 2012-01-15T14:10:24Z | 11,642,687 | 62 | 2012-07-25T04:23:18Z | [
"python",
"algorithm",
"text",
"split"
] | **Input:** `"tableapplechairtablecupboard..."` many words
What would be an efficient algorithm to split such text to the list of words and get:
**Output:** `["table", "apple", "chair", "table", ["cupboard", ["cup", "board"]], ...]`
First thing that cames to mind is to go through all possible words (starting with fir... | A naive algorithm won't give good results when applied to real-world data. Here is a 20-line algorithm that exploits relative word frequency to give accurate results for real-word text.
*(If you want an answer to your original question which does not use word frequency, you need to refine what exactly is meant by "lon... |
Adding data to end of existing file python | 8,870,840 | 3 | 2012-01-15T15:27:00Z | 8,870,850 | 9 | 2012-01-15T15:28:05Z | [
"python",
"file-io"
] | So my code looks like this ....
but I want to add data always to the end of the document
how would I do this
```
try:
f = open("file.txt", "w")
try:
f.write('blah') # Write a string to a file
f.writelines(lines) # Write a sequence of strings to a file
finally:
f.close()
except IOErr... | Open the file using `'a'` (append) instead of `'w'` (write, truncate)
Besides that, you can do the following isntead of the `try..finally` block:
```
with open('file.txt', 'a') as f:
f.write('blah')
f.writelines(lines)
```
The `with` block automatically takes care about closing the file at the end of the blo... |
How to initialize a list to a certain value in Python | 8,870,900 | 3 | 2012-01-15T15:37:07Z | 8,870,915 | 7 | 2012-01-15T15:39:25Z | [
"python",
"list"
] | I'd like to get a list where each item is set to a certain value (in my case, 0). I've solved this in my code with the code below, but it feels so messy. Surely there's a better way?
```
maxWidths = map(lambda x: 0, range(0, maxCols))
``` | Multiply a one-element list by the desired length.
```
maxWidths = [0] * maxCols
```
---
In the above, all elements of the list will be the same objects.
In case you're be creating a list of mutable values (such as dicts or lists), and you need them to be distinct, you can either use `map` as you did in the question... |
How do I get a lognormal distribution in Python with Mu and Sigma? | 8,870,982 | 12 | 2012-01-15T15:47:59Z | 8,871,222 | 9 | 2012-01-15T16:20:37Z | [
"python",
"statistics",
"scipy"
] | I have been trying to get the result of a [lognormal](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html) distribution using [Scipy](http://www.scipy.org/). I already have the Mu and Sigma, so I don't need to do any other prep work. If I need to be more specific (and I am trying to be with my ... | It sounds like you want to instantiate a "frozen" distribution from known parameters. In your example, you could do something like:
```
from scipy.stats import lognorm
stddev = 0.859455801705594
mean = 0.418749176686875
dist=lognorm([stddev],loc=mean)
```
which will give you a lognorm distribution object with the mea... |
How do I get a lognormal distribution in Python with Mu and Sigma? | 8,870,982 | 12 | 2012-01-15T15:47:59Z | 13,837,335 | 15 | 2012-12-12T10:08:23Z | [
"python",
"statistics",
"scipy"
] | I have been trying to get the result of a [lognormal](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.lognorm.html) distribution using [Scipy](http://www.scipy.org/). I already have the Mu and Sigma, so I don't need to do any other prep work. If I need to be more specific (and I am trying to be with my ... | I know this is a bit late (almost one year!) but I've been doing some research on the lognorm function in scipy.stats. A lot of folks seem confused about the input parameters, so I hope to help these people out. The example above is almost correct, but I found it strange to set the mean to the location ("loc") paramete... |
How can I unwrap t.co links with Python? | 8,872,232 | 3 | 2012-01-15T18:31:06Z | 8,872,288 | 8 | 2012-01-15T18:38:12Z | [
"python",
"twitter"
] | I want to expand t.co short links into a full URL. How can I do that? | The easiest way in python2 is to use [`urllib2.urlopen()`](http://docs.python.org/library/urllib2.html#urllib2.urlopen):
```
tco_url = "http://t.co/whatever"
req = urllib2.urlopen(tco_url)
print req.url
```
will print the URL `tco_url` finally resolves to, after following all redirects. |
Encoding used for u"" literals | 8,872,796 | 6 | 2012-01-15T19:50:58Z | 8,873,780 | 8 | 2012-01-15T22:09:09Z | [
"python",
"unicode",
"encoding"
] | Consider the next example:
```
>>> s = u"баба"
>>> s
u'\xe1\xe0\xe1\xe0'
>>> print s
áà áÃ
```
I'm using `cp1251` encoding within the idle, but it seems like the interpreter actually uses `latin1` to create unicode string:
```
>>> print s.encode('latin1')
баба
```
Why so? Is there spec for such behavior?... | When you type a character such as `б` into the terminal, you see a `б`, but what is really inputted is a sequence of bytes.
Since your terminal encoding is `cp1251`, typing `баба` results in the sequence of bytes equal to the unicode `баба` encoded in `cp1251`:
```
In [219]: "баба".decode('utf-8').encod... |
What is a good way to draw images using pygame? | 8,873,219 | 6 | 2012-01-15T20:43:10Z | 8,873,302 | 11 | 2012-01-15T20:54:10Z | [
"python",
"pygame"
] | I would like to know how to draw images using pygame. I know how to load them.
I have made a blank window.
When I use screen.blit(blank, (10,10)) it does not draw the image instead leaving the screen blank. | This is a typical layout:
```
myimage = pygame.image.load("myimage.bmp")
imagerect = myimage.get_rect()
while 1:
your_code_here
screen.fill(black)
screen.blit(myimage, imagerect)
pygame.display.flip()
``` |
Printing UTF-8-encoded byte string | 8,873,517 | 3 | 2012-01-15T21:30:11Z | 8,873,540 | 7 | 2012-01-15T21:33:40Z | [
"python",
"printing",
"utf-8",
"byte",
"character"
] | I have a data of a form:
`v = "\xc5\x84"`
This is a byte representation of an utf-8 encoded character "Å".
How can I print >>Å<< using variable v?
I'm using python 2.7.2
In original the variable v contained string:
`v = "\\xc5\\x84"` (double backslashes)
vs
`v = "\xc5\x84"` (single backslashes)
which is by it... | Edit In my machine the output depends on the shell/python used, as shown below.
As commented by Klaus a major actor here would be the locale setting in your system.
```
>>> v = "\xc5\x84"
>>> print v #in pycrust shell python 2.6
Ã
â
>>>
>>> print (v) #in idle python 3.2
Ã
>>>
```
the machine has the followin... |
How to catch "OpenCV Error" in Python | 8,873,657 | 5 | 2012-01-15T21:49:45Z | 8,874,487 | 9 | 2012-01-16T00:00:45Z | [
"python",
"opencv"
] | If I get OpenCV Error: ...
what's the syntax to catch it since OpenCV Error uses two words? I'm able to catch the following cv.error but how would I catch this?
**EDIT:**
I don't get it... is the answer obvious? Am I being unclear?
**EDIT 2**
I can't reproduce it b/c I'm on a different computer but it looked simil... | Try `cv2.error`.
```
try:
...
except cv2.error as e:
...
```
[Here's](http://opencv.itseez.com/modules/core/doc/utility_and_system_functions_and_macros.html?highlight=error) the page from the documentation but it's only for the C/C++ interface -- I can't find anything on the Python error handling for OpenCV (... |
Splitting a variable length string into multiple parts in python | 8,874,195 | 6 | 2012-01-15T23:11:11Z | 8,874,250 | 16 | 2012-01-15T23:17:58Z | [
"python",
"string",
"string-formatting"
] | I have a database:

As you can see in the 'desc' column, the text is of variable length (meaning no two strings I pull from this database are going to be of the same length). I will eventually add many more entries to this database, but this is what I'm testing with and starting... | Check out the [textwrap module](http://docs.python.org/library/textwrap.html).
```
>>> import textwrap
>>>
>>> s = "This command will create a 'close' button in the message window for the invoking character. If no window is currently on screen, the script execution will end."
>>>
>>> wrapped = textwrap.wrap(s, 40)
>... |
Run python function multiple times with different arguments | 8,874,785 | 4 | 2012-01-16T00:58:50Z | 8,874,880 | 7 | 2012-01-16T01:20:30Z | [
"python"
] | Hi I need to have a function that would take a function and return a function that will run that argument function eg. 1000 times and each time evaluate it's argument. I have something like this:
```
def runner(f):
def inner(*args):
for i in xrange(1000):
f(*args)
return inner
```
But it s... | The problem you're encountering is that `random.randint(1,UPPER_BOUND)` is being evaluated once at the time the `inner()` function returned by `runner()` is called. What you need is to delay the evaluation until later.
You could try something like this:
```
>>> def runner(f, callable):
... def inner():
... for ... |
Run multiple functions every second, write result to file | 8,875,507 | 5 | 2012-01-16T03:32:31Z | 8,875,632 | 7 | 2012-01-16T03:59:54Z | [
"python",
"multithreading",
"timer"
] | I'm trying to run three functions (each can take up to 1 second to execute) every second. I'd then like to store the output from each function, and write them to separate files.
At the moment I'm using `Timer`s for my delay handling. (I could subclass `Thread`, but that's getting a bit complicated for this simple scri... | I believe the python [Queue](http://docs.python.org/library/queue.html) module is designed for precisely this sort of scenario. You could do something like this, for example:
```
def main():
q = Queue.Queue()
for i in range(3):
t = threading.Timer(1, run_function, [q, i])
t.start()
while T... |
heapq with custom compare predicate | 8,875,706 | 30 | 2012-01-16T04:16:16Z | 8,875,823 | 40 | 2012-01-16T04:38:36Z | [
"python",
"algorithm",
"sorting",
"dictionary",
"containers"
] | I am trying to build a heap with a custom sort predicate. Since the values going into it are of 'user-defined' type, I cannot modify their built-in comparison predicate.
Is there a way to do something like:
```
h = heapq.heapify([...], key=my_lt_pred)
h = heapq.heappush(h, key=my_lt_pred)
```
Or even better, I could... | According to the [heapq documentation](http://docs.python.org/library/heapq.html), the way to customize the heap order is to have each element on the heap to be a tuple, with the first tuple element being one that accepts normal Python comparisons.
The functions in the heapq module are a bit cumbersome (since they are... |
Matplotlib Agg Rendering Complexity Error | 8,875,982 | 7 | 2012-01-16T05:06:57Z | 8,881,973 | 15 | 2012-01-16T15:14:08Z | [
"python",
"python-3.x",
"matplotlib"
] | I am trying to print a 600 dpi graph using Python matplotlib. However Python plotted 2 out of 8 graphs, and output the error:
```
OverflowError: Agg rendering complexity exceeded. Consider downsampling or decimating your data.
```
I am plotting a huge chunk of data (7,500,000 data per column) so I guess either that w... | In addition to @Lennart's point that there's no need for the full resolution, you might also consider a plot similar to the following.
Calculating the max/mean/min of a "chunked" version is very simple and efficient if you use a 2D view of the original array and the `axis` keyword arg to `x.min()`, `x.max()`, etc.
Ev... |
Convert list items to tuple | 8,876,125 | 2 | 2012-01-16T05:34:33Z | 8,876,137 | 12 | 2012-01-16T05:36:41Z | [
"python",
"list",
"tuples"
] | I have a list like this.
```
['February 01,2011 - February 28, 2011', 'March 01,2011 - March 31, 2011']
```
I want to convert it to
```
[('February 01,2011 - February 28, 2011'), ('March 01,2011 - March 31, 2011')]
```
Any Ideas??
Please help!!!
Thanks in advance!!! | To make a tuple with 1 element, append a comma in the parentheses:
```
>>> my_list = ['February 01,2011 - February 28, 2011', 'March 01,2011 - March 31, 2011']
>>> [(x,) for x in my_list]
[('February 01,2011 - February 28, 2011',), ('March 01,2011 - March 31, 2011',)]
``` |
Task state and django-celery | 8,876,863 | 10 | 2012-01-16T07:25:55Z | 13,241,895 | 10 | 2012-11-05T23:11:25Z | [
"python",
"celery",
"django-celery"
] | I use django-celery and have task like this:
```
class TestTask(Task):
name = "enabler.test_task"
def run(self, **kw):
debug_log("begin test task")
time.sleep(5)
debug_log("end test task")
def on_success(self, retval, task_id, args, kwargs):
debug_log("on success")
de... | What version of celery are you using? I notice I'm really late to this party but in case this helps someone in the future. If the task is set to ignore\_result (which it is by default in the latest version) it will stay at PENDING and not go to SUCCESS.
Their documentation here,
```
@celery.task(ignore_result=True)
d... |
Why is my form always unbound? | 8,877,344 | 2 | 2012-01-16T08:31:42Z | 8,877,387 | 8 | 2012-01-16T08:37:14Z | [
"python",
"django",
"django-forms"
] | I am new to Django, and I am trying to use django-friends in my website.
Here is a form from [django-friends](https://github.com/jtauber/django-friends/blob/master/friends/forms.py#L19):
```
>>> from django import forms
>>> class UserForm(forms.Form):
...
... def __init__(self, user=None, *args, **kwargs):
.... | Your `__init__` statement is swallowing the first argument.
Remove `user=None` from your init statement, and perhaps pull it from the `kwargs` instead.
```
class UserForm(forms.Form):
def __init__(self, *args, **kwargs):
self.user = kwargs.pop('user', None)
super(UserForm, self).__init__(*args, **... |
How can use python's argparse with a predefined argument string? | 8,878,478 | 4 | 2012-01-16T10:11:55Z | 8,878,535 | 10 | 2012-01-16T10:15:31Z | [
"python",
"argparse"
] | I want to use the pythons argparse module to parse my cli parameter string. This works for the parameters a pass from terminal, but not with a given string.
```
import argparse
parser = argparse.ArgumentParser(description='Argparse Test script')
parser.add_argument("param", help='some parameter')
argString = 'someTe... | Ah, no no no. `parser.parse_args()` expects a sequence in the same form as `sys.argv[1:]`. If you treat a string like a sys.argv sequence, you get `['s', 'o', 'm', 'e', 'T', 'e', 's', 't', 'F', 'i', 'l', 'e']`. 's' becomes the relevant argument, and then the rest of the string is unparseable.
Instead, you probably wan... |
How can use python's argparse with a predefined argument string? | 8,878,478 | 4 | 2012-01-16T10:11:55Z | 18,596,435 | 10 | 2013-09-03T15:47:36Z | [
"python",
"argparse"
] | I want to use the pythons argparse module to parse my cli parameter string. This works for the parameters a pass from terminal, but not with a given string.
```
import argparse
parser = argparse.ArgumentParser(description='Argparse Test script')
parser.add_argument("param", help='some parameter')
argString = 'someTe... | Another option is to use [shlex.split](http://docs.python.org/2/library/shlex.html#shlex.split). It it especially very convenient if you have real CLI arguments string:
```
import shlex
argString = '-vvvv -c "yes" --foo bar --some_flag'
args = parser.parse_args(shlex.split(argString))
``` |
python subprocess output to list or file | 8,880,461 | 4 | 2012-01-16T13:08:42Z | 8,880,539 | 16 | 2012-01-16T13:16:33Z | [
"python",
"python-3.x",
"subprocess"
] | I want to run the following bash command in Python 3:
```
ls -l
```
I know that I can do the following:
```
from subprocess import call
call(['ls', '-l'])
```
How do I save this output to a file, or put it into lists or sets?
```
[-rw-r--r--] [1] [name] [staff] [426] [14 Jan 21:52] [HelloWorld.class]
[-rw-r--r... | With python2.7 you can use [subprocess.check\_output](http://docs.python.org/library/subprocess.html#subprocess.check_output):
```
ls_lines = subprocess.check_output(['ls', '-l']).splitlines()
```
Prior to python2.7, you need to use the lower level api, which is a bit more involved.
```
ls_proc = subprocess.Popen(['... |
python subprocess output to list or file | 8,880,461 | 4 | 2012-01-16T13:08:42Z | 8,880,768 | 8 | 2012-01-16T13:37:00Z | [
"python",
"python-3.x",
"subprocess"
] | I want to run the following bash command in Python 3:
```
ls -l
```
I know that I can do the following:
```
from subprocess import call
call(['ls', '-l'])
```
How do I save this output to a file, or put it into lists or sets?
```
[-rw-r--r--] [1] [name] [staff] [426] [14 Jan 21:52] [HelloWorld.class]
[-rw-r--r... | One way to access to the information in `ls -l` output is to parse it. For example, `csv.DictReader` could be use to map each column to a field in a dictionary:
```
import subprocess
import csv
process = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE)
stdout, stderr = process.communicate()
reader = csv.DictRe... |
PyCharm: Forcing Django Template Syntax Highligting | 8,880,652 | 25 | 2012-01-16T13:26:20Z | 8,880,818 | 45 | 2012-01-16T13:39:48Z | [
"python",
"django",
"pycharm"
] | I've just installed PyCharm, and have opened an existing project with multiple apps.
When I open django templates, they are highlighted as if plain HTML, i.e. `{% block %}` elements and `{{variable}}` references are not treated specially.
Is there any way I can force it to use the django template syntax highlighter fo... | File » Settings » Template language, do you have Template language setting set to django? |
Getting package version using pkg_resources? | 8,880,661 | 11 | 2012-01-16T13:26:41Z | 8,881,255 | 13 | 2012-01-16T14:17:44Z | [
"python",
"pkg-resources"
] | What is the recommended way getting hold of the package version of a package in the $PYTHONPATH or sys.path? I remember that the pkg\_resource module has some functionality for this but I can not find any related information. Please don't point me to solution using a version.py file and reading it somehow. Using pkg\_r... | ```
>>> import pkg_resources
>>> pkg_resources.get_distribution("PIL").version
'1.1.7'
``` |
Automatically exporting all functions (vs manually specifying __all__) | 8,881,227 | 4 | 2012-01-16T14:15:38Z | 8,881,265 | 11 | 2012-01-16T14:18:35Z | [
"python"
] | I have a `helpers.py` file which defines about 30 helper functions to be exported as follows:
```
from helpers import *
```
To be able to do this, I have added all 30 functions to the `__all__` variable. Can I automatically have all functions exported, rather than having to specify each one? | Yes, by simply not specifying `__all__`. |
Automatically exporting all functions (vs manually specifying __all__) | 8,881,227 | 4 | 2012-01-16T14:15:38Z | 8,881,338 | 7 | 2012-01-16T14:23:48Z | [
"python"
] | I have a `helpers.py` file which defines about 30 helper functions to be exported as follows:
```
from helpers import *
```
To be able to do this, I have added all 30 functions to the `__all__` variable. Can I automatically have all functions exported, rather than having to specify each one? | Actually I think Gandaro is right, you don't have to specify `__all__`, but if, for some unknown reason, you would have to do it then, you can filter keywords from dir():
```
__all__ = [ helper for helper in dir() if helper == MY_CONDITION ]
``` |
how to read and write INI file with Python? | 8,884,188 | 43 | 2012-01-16T17:54:50Z | 8,884,294 | 7 | 2012-01-16T18:03:42Z | [
"python",
"ini"
] | i need read, write and create **INI** file with Python3.
**FILE.INI**
```
default_path = "/path/name/"
default_file = "file.txt"
```
**Python File:**
```
# read file and if not exists
ini = iniFile( 'FILE.INI' )
# Get and Print Config Line "default_path"
getLine = ini.default_path
# Print (string)/path/n... | <http://docs.python.org/library/configparser.html>
Python's standard library might be helpful in this case. |
how to read and write INI file with Python? | 8,884,188 | 43 | 2012-01-16T17:54:50Z | 8,884,638 | 68 | 2012-01-16T18:34:09Z | [
"python",
"ini"
] | i need read, write and create **INI** file with Python3.
**FILE.INI**
```
default_path = "/path/name/"
default_file = "file.txt"
```
**Python File:**
```
# read file and if not exists
ini = iniFile( 'FILE.INI' )
# Get and Print Config Line "default_path"
getLine = ini.default_path
# Print (string)/path/n... | This can be something to start with:
```
import configparser
config = configparser.ConfigParser()
config.read('FILE.INI')
print(config['DEFAULT']['path']) # -> "/path/name/"
config['DEFAULT']['path'] = '/var/shared/' # update
config['DEFAULT']['default_message'] = 'Hey! help me!!' # create
with open('FILE.I... |
how to read and write INI file with Python? | 8,884,188 | 43 | 2012-01-16T17:54:50Z | 29,479,549 | 19 | 2015-04-06T20:55:49Z | [
"python",
"ini"
] | i need read, write and create **INI** file with Python3.
**FILE.INI**
```
default_path = "/path/name/"
default_file = "file.txt"
```
**Python File:**
```
# read file and if not exists
ini = iniFile( 'FILE.INI' )
# Get and Print Config Line "default_path"
getLine = ini.default_path
# Print (string)/path/n... | Here's a complete read, update and write example.
Input file, test.ini
```
[section_a]
string_val = hello
bool_val = false
int_val = 11
pi_val = 3.14
```
Working code.
```
try:
from configparser import ConfigParser
except ImportError:
from ConfigParser import ConfigParser # ver. < 3.0
# instantiate
config... |
How to parse unicode month name to get datetime in Python 2.7 | 8,885,115 | 4 | 2012-01-16T19:16:44Z | 8,885,266 | 7 | 2012-01-16T19:30:27Z | [
"python",
"datetime"
] | I have a u'20 ÑÑÑÐ½Ñ 2012' and I need to get datetime object.
(u'20 ÑÑÑÐ½Ñ 2012' == u'20 January 2012')
It's very easy when you have a datetime.strptime('1 Jun 2005', '%d %b %Y') But what to do if I have month in different locale ?
(appengine + python 2.7)
It would be good to have a method get\_month(u'Month... | Maybe you can convert it to a datetime object first, then use locale to set another locale and convert it again..
Here is something to get you starting..
```
import locale, datetime
In [1]: datetime.datetime.strptime('February', '%B')
Out[1]: datetime.datetime(1900, 2, 1, 0, 0)
In [2]: locale.setlocale(locale.LC_AL... |
How to format a floating number to fixed width in Python | 8,885,663 | 112 | 2012-01-16T20:07:54Z | 8,885,688 | 184 | 2012-01-16T20:10:38Z | [
"python",
"string",
"numbers",
"number-formatting"
] | How do I format a floating number to a fixed width with the following requirements:
1. Leading zero if n < 1
2. Add trailing decimal zero(s) to fill up fixed width
3. Truncate decimal digits past fixed width
4. Align all decimal points
For example:
```
% formatter something like '{:06}'
numbers = [23.23, 0.123334987... | ```
for x in numbers:
print "{:10.4f}".format(x)
```
prints
```
23.2300
0.1233
1.0000
4.2230
9887.2000
``` |
How to format a floating number to fixed width in Python | 8,885,663 | 112 | 2012-01-16T20:07:54Z | 30,449,204 | 12 | 2015-05-26T03:56:49Z | [
"python",
"string",
"numbers",
"number-formatting"
] | How do I format a floating number to a fixed width with the following requirements:
1. Leading zero if n < 1
2. Add trailing decimal zero(s) to fill up fixed width
3. Truncate decimal digits past fixed width
4. Align all decimal points
For example:
```
% formatter something like '{:06}'
numbers = [23.23, 0.123334987... | In python3 the following works:
```
>>> v=10.4
>>> print('% 6.2f' % v)
10.40
>>> print('% 12.1f' % v)
10.4
>>> print('%012.1f' % v)
0000000010.4
``` |
Make Django URLs work with or without / | 8,885,740 | 4 | 2012-01-16T20:15:27Z | 8,885,786 | 7 | 2012-01-16T20:19:48Z | [
"python",
"django"
] | I have a django app that has / at the end of every URL conf. Example:
```
# user home page
(r'^home/$', 'user_home_page'),
```
However, I'm noticing this is causing a ton of redirects on my server, because when people dont add the /, it redirects them. Is there any way to have it accept both without a redirect except... | While you can accept both without doing a redirect by using:
```
(r'^home/?$', 'user_home_page'),
```
It is not best SEO practice because it will look like you have duplicate content and your hits will be split between the two pages. |
All possible (monogamous) pairings of two lists (of boys and girls) | 8,886,680 | 3 | 2012-01-16T21:42:37Z | 8,886,716 | 10 | 2012-01-16T21:45:32Z | [
"python",
"list",
"itertools"
] | I have these two lists:
```
boys = [1,2,3]
girls = [1,2,3]
```
How would you build all possible (monogamous) pairings `[boy, girl]`? With only 3 of both `boys` and `girls`, I think this is the list of *all* the possible pairings:
```
[
[[1,1], [2,2], [3,3]],
[[1,1], [2,3], [3,2]],
[[1,2], [2,1], [3,3]],
[[1,2],... | What you are describing are the permutations of a set. Simply leave the boys in the given order, and iterate through alll permutations of the girls -- this will give you all possible pairings:
```
boys = ["b1", "b2", "b3"]
girls = ["g1", "g2", "g3"]
for girls_perm in itertools.permutations(girls):
for b, g in zip(... |
Invalid syntax in "for item in L" loop | 8,886,730 | 4 | 2012-01-16T21:46:58Z | 8,886,754 | 10 | 2012-01-16T21:49:14Z | [
"python"
] | I have a feeling I'm missing something pretty simple here but, in this one function:
```
def triplets(perimeter):
triplets, n, a, b, c = 0 #number of triplets, a, b, c, sides of a triangle, n is used to calculate a triple
L = primes(int(math.sqrt(perimeter)) #list of primes to divide the perimeter
for i... | You are missing a closing parenthesis on the line before:
```
L = primes(int(math.sqrt(perimeter)) #list of primes to divide the perimeter
# ^ ^ ^ ^^
#nesting count 1 2 3 21
```
See how we don't reach 0 in the "nesting count" below the line? |
Caesar Cipher Function in Python | 8,886,947 | 5 | 2012-01-16T22:05:55Z | 8,886,969 | 12 | 2012-01-16T22:07:58Z | [
"python",
"caesar-cipher"
] | I'm trying to create a simple Caesar Cipher function in Python that shifts letters based on input from the user and creates a final, new string at the end. The only problem is that the final cipher text shows only the last shifted character, not an entire string with all the shifted characters.
Here's my code:
```
pl... | You need to move `cipherText = ""` before the start of the for loop. You're resetting it each time through the loop.
```
def caesar(plainText, shift):
cipherText = ""
for ch in plainText:
if ch.isalpha():
stayInAlphabet = ord(ch) + shift
if stayInAlphabet > ord('z'):
stayInAlphabet -= 26
... |
Caesar Cipher Function in Python | 8,886,947 | 5 | 2012-01-16T22:05:55Z | 8,895,517 | 24 | 2012-01-17T13:35:10Z | [
"python",
"caesar-cipher"
] | I'm trying to create a simple Caesar Cipher function in Python that shifts letters based on input from the user and creates a final, new string at the end. The only problem is that the final cipher text shows only the last shifted character, not an entire string with all the shifted characters.
Here's my code:
```
pl... | I realize that this answer doesn't really answer your question, but I think it's helpful anyway. Here's an alternative way to implementing the caesar cipher with string methods:
```
def caesar(plaintext, shift):
alphabet = string.ascii_lowercase
shifted_alphabet = alphabet[shift:] + alphabet[:shift]
table ... |
About threads and callbacks | 8,887,408 | 2 | 2012-01-16T22:50:46Z | 8,887,579 | 8 | 2012-01-16T23:07:45Z | [
"python",
"multithreading",
"thread-safety"
] | I'm working with Python and threads by some time, but I still have a little doubt about callbacks. Take the following code:
```
import threading
def cb_func(data):
"""The callback function"""
print data
def th_func(callback):
"""The threaded function"""
# do some work here
callback('somedata')
t... | There's an easy way to check, using `current_thread().name`:
```
import threading
def cb_func():
"The callback function."
print 'Callback, in thread %s' % threading.current_thread().name
def th_func(callback):
"The threaded function."
# ...
callback()
thr = threading.Thread(target=th_func, args=... |
How to check whether virtualenv was created with '--no-site-packages'? | 8,887,445 | 12 | 2012-01-16T22:54:20Z | 8,887,511 | 19 | 2012-01-16T23:01:12Z | [
"python",
"django",
"virtualenv",
"pip",
"virtualenvwrapper"
] | Sometimes I get errors that I suspect are the result of my Django app using globally installed Python modules/Django apps instead of those within its virtualenv.
Is there a way to check whether my app's virtualenv was created with '--no-site-packages' without having to delete it, then re-create it as follows?
```
dea... | There's a file in `<env>/lib/pythonX.X/` called `no-global-site-packages.txt` when you create a virtual environment with `--no-site-packages`.
Just tried this with virtualenv 1.7:
```
% virtualenv --no-site-packages env.without
% virtualenv --system-site-packages env.with
% find env.without | sed 's/env.without//' >... |
making square axes plot with log2 scales in matplotlib | 8,887,544 | 8 | 2012-01-16T23:03:54Z | 8,888,110 | 23 | 2012-01-17T00:15:08Z | [
"python",
"numpy",
"scipy",
"matplotlib"
] | I'd like to make a square axis scatter plot with matplotlib. Normally using `set_scale("log")` works great, but it limits me to log10. I'd like to make the plot in log2. I saw the solution here: [How to produce an exponentially scaled axis?](http://stackoverflow.com/questions/4899516/how-to-produce-an-exponentially-sca... | Just specify `basex=2` or `basey=2`.
```
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.set_xscale('log', basex=2)
ax.set_yscale('log', basey=2)
ax.plot(range(1024))
plt.show()
```

For the zero-crossing behavior, what you're referring... |
Import error in twilio | 8,887,927 | 3 | 2012-01-16T23:49:57Z | 8,935,768 | 10 | 2012-01-20T01:35:43Z | [
"python",
"importerror",
"twilio"
] | I am having the same problem as this thread regarding [twilio-python](https://www.twilio.com/docs/python/install):
[twilio.rest missing from twilio python module version 2.0.8?](http://stackoverflow.com/questions/8722585/twilio-rest-missing-from-twilio-python-module-version-2-0-8)
However I have the same problem but ... | I am going to shoot myself. I figured out the problem.
I named a python file in my project `twilio.py`. Since that file was loaded first, then subsequent calls to load twilio would reference that file instead of the twilio library. |
matplotlib problems plotting logged data and setting its x/y bounds | 8,888,240 | 7 | 2012-01-17T00:31:17Z | 8,888,636 | 11 | 2012-01-17T01:29:38Z | [
"python",
"numpy",
"matplotlib"
] | I am using log plots as follows in matplotlib, roughly as follows.
```
plt.scatter(x, y)
# use log scales
plt.gca().set_xscale('log')
plt.gca().set_yscale('log')
# set x,y limits
plt.xlim([-1, 3])
plt.ylim([-1, 3])
```
The first problem is that without x,y limits, matplotlib sets scales such that most of the data i... | @honk has already answered your main question, but as for the others (and your original question), please read a few tutorials or have a look at some of the examples. :)
You're getting very confused because you haven't looked at the documentation for the functions you're using.
> why are the default x/y bounds for th... |
Match a line with multiple regex using Python | 8,888,567 | 4 | 2012-01-17T01:19:27Z | 8,888,615 | 10 | 2012-01-17T01:26:57Z | [
"python",
"regex"
] | Is there a way to see if a line contains words that matches a set of regex pattern?
If I have `[regex1, regex2, regex3]`, and I want to see if a line matches any of those, how would I do this?
Right now, I am using `re.findall(regex1, line)`, but it only matches 1 regex at a time. | You can use the built in functions `any` (or `all` if all regexes have to match) and a Generator expression to cicle through all the regex-objects.
`any (regex.match(line) for regex in [regex1, regex2, regex3])`
(or `any(re.match(regex_str, line) for regex in [regex_str1, regex_str2, regex_str2])` if the regexes are ... |
Chainable operations on lists | 8,888,574 | 3 | 2012-01-17T01:20:27Z | 8,888,609 | 7 | 2012-01-17T01:25:36Z | [
"python"
] | I want to do something like
```
list = [6,4,1,10,8].sort().reverse()
```
or
```
zip([x**2 for x in xrange(5)], [x**3 for x in xrange(5)].reverse()])
```
but this doesn't work because methods on list doesn't return the original object, so they're not chainable.
Do I have to do this using multiple lines or is there ... | ```
reversed(sorted([6,4,1,10,8]))
```
The [`reversed`](http://docs.python.org/library/functions.html#reversed) and [`sorted`](http://docs.python.org/library/functions.html#sorted) builtins have been around since Python 2.4.
Note that you should do `sorted(my_list, reverse=True)` if you are going to reverse the list ... |
How to time execution time of a batch of code in Python? | 8,889,083 | 7 | 2012-01-17T02:47:17Z | 8,889,624 | 23 | 2012-01-17T04:25:43Z | [
"python",
"time"
] | I found this question and answer here on StackOverflow.
[Python - time.clock() vs. time.time() - accuracy?](http://stackoverflow.com/questions/85451/python-time-clock-vs-time-time-accuracy)
Here is some code I'm trying to run:
```
import sys
import time
import timeit
if (len(sys.argv) > 1):
folder_path = sys.argv... | This is how I typically write time measurement code in Python:
```
start_time = time.time()
# ... do stuff
end_time = time.time()
print("Elapsed time was %g seconds" % (end_time - start_time))
```
As mentioned in the post you linked to, `time.clock()` is not appropriate for measuring elapsed time since it reports t... |
How to time execution time of a batch of code in Python? | 8,889,083 | 7 | 2012-01-17T02:47:17Z | 15,136,358 | 9 | 2013-02-28T13:07:34Z | [
"python",
"time"
] | I found this question and answer here on StackOverflow.
[Python - time.clock() vs. time.time() - accuracy?](http://stackoverflow.com/questions/85451/python-time-clock-vs-time-time-accuracy)
Here is some code I'm trying to run:
```
import sys
import time
import timeit
if (len(sys.argv) > 1):
folder_path = sys.argv... | I would use a timing decorator and place the code you want to time into a function.
```
import time
def timeit(f):
def timed(*args, **kw):
ts = time.time()
result = f(*args, **kw)
te = time.time()
print 'func:%r args:[%r, %r] took: %2.4f sec' % \
(f.__name__, args, kw,... |
How do I extend a regular expression to exclude all files in a folder? | 8,889,151 | 10 | 2012-01-17T02:59:34Z | 8,889,234 | 11 | 2012-01-17T03:13:16Z | [
"python",
"regex",
"google-app-engine"
] | In the app.yaml file of my Google App Engine project there is a skip\_files section used to exclude files of given types from being uploaded. How do I extend this regular expression to exclude the entire gaeunit directory from being uploaded?
```
skip_files: |
^(.*/)?(
(app\.yaml)|
(index\.yaml)|
(\..*... | The same way the `nbproject` and `darcs` directories are excluded in the above regular expression. Add this line anywhere before the last line:
```
(gaeunit/.*)|
``` |
If an item may not exist in a list, can we still do if-else to check condition? | 8,889,607 | 2 | 2012-01-17T04:22:55Z | 8,889,623 | 11 | 2012-01-17T04:25:42Z | [
"python"
] | Suppose we have
```
mystr = 'hello.py'
mystr = 'hello'
if not 'py' in mystr.rsplit('.')[1]:
```
The first case is fine, but the second case results in an "out of range" error.
**Goal:**
If .py exists in the string, do nothing. If .py is not part of the filename, do XYZ.
Note : The user input may or may not have a .... | I'd simply write
```
if not mystr.endswith('.py'):
```
(Assuming, of course, that I've understood your intent.) |
Get Plain text from a QLabel with Rich text | 8,890,320 | 6 | 2012-01-17T05:56:34Z | 8,899,580 | 8 | 2012-01-17T18:16:38Z | [
"python",
"qt",
"pyqt",
"pyqt4",
"qlabel"
] | I have a `QLabel` that contains rich text.
I want to extract just the actual (visible) 'text' from the `QLabel`, and none of the code for formatting.
I essentially need a function similiar to the `'.toPlainText'` method of other `Qt Widgets`.
I can not simply call `.text()` and string manipulate away the html tags... | Use a [`QTextDocument`](http://developer.qt.nokia.com/doc/qt-4.8/qtextdocument.html) to do the conversion:
```
doc = QtGui.QTextDocument()
doc.setHtml(label.text())
text = doc.toPlainText()
``` |
different values for class variables in each subclass in python | 8,892,757 | 5 | 2012-01-17T10:07:26Z | 8,892,865 | 7 | 2012-01-17T10:15:38Z | [
"python",
"oop"
] | I have a base class which is never going to be instantiated. There are different subclasses of this base class. Each subclass defines certain class variables where the name is same across all subclasses but the value is going to be different. For example
```
class Base:
def display(self):
print self.logfi... | This should work
```
>>> class Base(object):
... def __init__(self):
... if not hasattr(self, "logfile"):
... raise Exception("not implemented")
...
>>> class d1(Base):
... logfile='logfile1.log'
...
>>> class d2(Base):
... pass
...
>>> d1()
<__main__.d1 object at 0x7d0d0>
>>> d2()
Traceback (most recent ca... |
different values for class variables in each subclass in python | 8,892,757 | 5 | 2012-01-17T10:07:26Z | 8,892,923 | 10 | 2012-01-17T10:20:47Z | [
"python",
"oop"
] | I have a base class which is never going to be instantiated. There are different subclasses of this base class. Each subclass defines certain class variables where the name is same across all subclasses but the value is going to be different. For example
```
class Base:
def display(self):
print self.logfi... | One alternative that doesn't require instantiating the classes for the checking to take place is to create a metaclass:
```
class BaseAttrEnforcer(type):
def __init__(cls, name, bases, d):
if 'loglevel' not in d:
raise ValueError("Class %s doesn't define loglevel attribute" % name)
type... |
Untar archive in Python with errors | 8,893,359 | 4 | 2012-01-17T10:52:01Z | 8,893,499 | 11 | 2012-01-17T11:02:45Z | [
"python"
] | I download a bz2 file using Python. Then I want to unpack the archive using:
```
def unpack_file(dir, file):
cwd = os.getcwd()
os.chdir(dir)
print "Unpacking file %s" % file
cmd = "tar -jxf %s" % file
print cmd
os.system(cmd)
os.chdir(cwd)
```
Unfortunately this ends with error:
```
bzip2... | For the record, python standard library ships with the [tarfile](http://docs.python.org/library/tarfile.html) module which automatically handles tar, tar.bz2, and tar.gz formats.
Additionally, you can do nifty things like get file lists, extract subsets of files or directories or chunk the archive so that you process ... |
Replace whitespaces with comma ignoring whitespaces in quotes | 8,893,367 | 2 | 2012-01-17T10:52:30Z | 8,893,413 | 10 | 2012-01-17T10:55:49Z | [
"python",
"algorithm"
] | Given a string of words separated by whitespace. Need to replace whitespaces with comma ignoring whitespaces in quotes.
```
>>> some_string = 'one two "three four" five "six seven"'
>>> replace_func(some_string)
'one,two,"three four",five,"six seven"'
```
Here is the simple decision:
```
def replace_func(some_str):
... | This can be easily done with the help of [`shlex.split`](http://docs.python.org/library/shlex.html#shlex.split):
```
>>> import shlex
>>> ','.join(shlex.split(some_string))
'one,two,three four,five,six seven'
```
I you need to preserve quotation marks you can do this:
```
>>> ','.join(['"{0}"'.format(fragment) if ' ... |
Replace whitespaces with comma ignoring whitespaces in quotes | 8,893,367 | 2 | 2012-01-17T10:52:30Z | 8,893,493 | 7 | 2012-01-17T11:02:13Z | [
"python",
"algorithm"
] | Given a string of words separated by whitespace. Need to replace whitespaces with comma ignoring whitespaces in quotes.
```
>>> some_string = 'one two "three four" five "six seven"'
>>> replace_func(some_string)
'one,two,"three four",five,"six seven"'
```
Here is the simple decision:
```
def replace_func(some_str):
... | Alternatively, you could try this more simplistic solution with regular expressions:
```
>>> import re
>>> ','.join(re.findall('\"[^\"]*\"|\S+', some_string))
'one,two,"three four",five,"six seven"'
``` |
Workaround to return a list from a ComputedProperty function in NDB | 8,893,886 | 4 | 2012-01-17T11:31:31Z | 8,904,624 | 11 | 2012-01-18T03:00:18Z | [
"python",
"google-app-engine",
"gae-datastore",
"python-2.7",
"app-engine-ndb"
] | I am converting my app to use NDB. I used to have something like this before:
```
@db.ComputedProperty
def someComputedProperty(self, indexed=False):
if not self.someCondition:
return []
src = self.someReferenceProperty
list = src.list1 + src.list2 + src.list3 + src.list4 \
... | You need to set the repeated=True flag for your computed property in NDB. I don't think you can use the cute "@db.ComputedProperty" notation, you'll have to say:
```
def _computeValue(self):
...same as before...
someComputedProperty = ComputedProperty(_computeValue, repeated=True, indexed=False)
``` |
How can I improve ReportLab image quality? | 8,893,928 | 5 | 2012-01-17T11:35:12Z | 10,759,092 | 7 | 2012-05-25T17:46:03Z | [
"python",
"reportlab"
] | I'm building a label printer. It consists of a logo and some text, not tough. I have already spent 3 days trying to get the original SVG logo to draw to screen but the SVG is too complex, using too many gradients, etc.
So I have a high quality bitmapped logo (as a JPG or PNG) and I'm drawing that on a ReportLab canvas... | Having previously worked at the ReportLab company, I can tell you that raster images do not go through any automatic resampling/downscaling while being included in the PDF. The 85\*123 dimensions you are using are not pixels, but points (pt) which are a physical unit like millimetres or inches.
I would suggest printin... |
What available Python modules are there to save-and-load data? | 8,894,075 | 7 | 2012-01-17T11:47:48Z | 8,894,179 | 7 | 2012-01-17T11:55:28Z | [
"python",
"data-storage",
"python-module",
"data-persistence"
] | There are many scattered posts out on StackOverflow, regarding Python modules used to save and load data.
I myself am familiar with [json](http://docs.python.org/library/json.html) and [pickle](http://docs.python.org/library/pickle.html) and I have heard of [pytables](http://www.pytables.org/moin) too. There are proba... | [marshal](http://docs.python.org/library/marshal.html):
* Pros:
+ Can read and write Python values in a binary format. Therefore it's much faster than `pickle` (which is character based).
* Cons:
+ Not all Python object types are supported. Some unsupported types such as subclasses of builtins will appear to mar... |
OpenCV Shows Gray Window | 8,894,451 | 3 | 2012-01-17T12:17:20Z | 8,894,589 | 10 | 2012-01-17T12:27:30Z | [
"python",
"opencv"
] | I'm trying to display an image using OpenCV. I have the following very basic code:
```
import cv2
img = cv2.imread('myimage.png', 0) # Reads a Gray-scale image
img2 = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
cv2.imshow("window", img2)
```
The window is opened properly, with the correct size, but it's gray - there's no... | OK, got it.
Turns out I needed to let OpenCV start handling events, it wasn't handling the WM\_PAINT event. Adding cv2.waitKey() fixed this. |
SQLAlchemy: how to filter date field? | 8,895,208 | 43 | 2012-01-17T13:14:48Z | 8,898,533 | 70 | 2012-01-17T16:54:21Z | [
"python",
"sql",
"database",
"orm",
"sqlalchemy"
] | Here is model:
```
class User(Base):
...
birthday = Column(Date, index=True) #in database it's like '1987-01-17'
...
```
I want to filter between two dates, for example to choose all users in interval 18-30 years.
How to implement it with SQLAlchemy?
I think of:
```
query = DBSession.query(User).filt... | In fact, your query is right except for the typo: your filter is excluding all records: you should change the `<=` for `>=` and vice versa:
```
qry = DBSession.query(User).filter(
and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17'))
# or same:
qry = DBSession.query(User).filter(User.birthday <= ... |
Faster Python MySQL | 8,895,837 | 3 | 2012-01-17T13:57:51Z | 8,895,979 | 10 | 2012-01-17T14:07:50Z | [
"python",
"mysql",
"performance"
] | I use mysql.connector (MySQLdb Python implementation?) to access MySQL. The transfer from a select statement from a cursor isn't that fast.
Is there a way to speed up the code?
Maybe another library? Which? (I have Windows and Python 3.1)
Maybe a row retrieval different from iterating over the cursor? | The default `MySQLdb` cursor fetches the entire query result at once from the server. Conversion of this data to a Python list of tuples can consume a lot of memory and time.
Use [MySQLdb.cursors.SSCursor](http://mysql-python.sourceforge.net/MySQLdb.html) when you want to make a huge query and
pull results from the se... |
Switch in Python | 8,895,864 | 8 | 2012-01-17T13:59:56Z | 8,895,944 | 16 | 2012-01-17T14:05:44Z | [
"python",
"switch-statement"
] | I have tried making a switch like statement in python, instead of having a lot of if statements.
The code looks like this:
```
def findStuff(cds):
L=[]
c=0
for i in range(0, len(cds), 3):
a=differencesTo(cds[i:i+3])
result = {
a[2][0]==1: c=i+1,
a[2][1]==1: c=i+2,
... | (a) I fail to see what is wrong with if...elif...else
(b) I assume that python does not have a switch statement for the same reason that Smalltalk doesn't: it's almost completely redundant, and in the case where you want to switch on types, you can add an appropriate method to your classes; and likewise switching on v... |
How to use python_dateutil 1.5 'parse' function to work with unicode? | 8,896,038 | 9 | 2012-01-17T14:12:24Z | 8,917,539 | 8 | 2012-01-18T21:16:51Z | [
"python",
"datetime",
"internationalization"
] | I need that Python\_dateutil 1.5 [parse()](http://labix.org/python-dateutil#head-a23e8ae0a661d77b89dfb3476f85b26f0b30349c) work with Unicode month names.
If use fuzzy=True it skips month name and produce result with month = 1
When I use it without fuzzy parameter I get the next exception:
```
from dateutil.parser im... | Rik Poggi is right, string 'ÐÑнÑ' cannot be a month for `python-dateutil`. Digging a little into `dateutil/parser.py`, the basic problem is that this module is only internationalised enough for handling Western European Latin-script languages. It is not designed up to be able to handle languages, such as Russian, u... |
exception for non existing parameter in FLASK | 8,896,473 | 10 | 2012-01-17T14:39:38Z | 8,896,542 | 12 | 2012-01-17T14:44:05Z | [
"python",
"flask",
"werkzeug"
] | I have a form that sends parameters.
In my form I have a checkbox.
If my checkbox is not checked then I will not get any parameters.
If in my module I have :
```
var = request.form['mycheckbox']
```
and if my checkbox is not checked (the parameter is not passed)
Then in debug mode I get the error message :
> Bad R... | ```
var = request.form.get('checkbox')
```
This will return `None` if the parameter is not defined. |
exception for non existing parameter in FLASK | 8,896,473 | 10 | 2012-01-17T14:39:38Z | 8,896,780 | 8 | 2012-01-17T14:57:13Z | [
"python",
"flask",
"werkzeug"
] | I have a form that sends parameters.
In my form I have a checkbox.
If my checkbox is not checked then I will not get any parameters.
If in my module I have :
```
var = request.form['mycheckbox']
```
and if my checkbox is not checked (the parameter is not passed)
Then in debug mode I get the error message :
> Bad R... | The reason for this is hidden in the flask documentation here: <http://flask.pocoo.org/docs/api/#flask.Flask.trap_http_exception>
I'm not sure why this behaviour isn't changed for debugging mode, but to get Flask to catch the BadRequestKeyError exceptions from werkzeug, you need to run something like this on your appl... |
Swig python - c++ how to use type int8_t | 8,897,294 | 10 | 2012-01-17T15:31:48Z | 8,897,963 | 14 | 2012-01-17T16:15:02Z | [
"c++",
"python",
"swig",
"ctypes"
] | I have a C function that takes as paramenter an 8 bit integer
```
int8_t foo( int8_t x );
```
I would like to call this function from my python code using a swig interface but int8\_t type do not exists in python.
In order to have this kind of types exists a python module called numpy.
Even using this yet I do not ma... | In your SWIG interface file use:
```
%include "stdint.i"
```
*before* you first use `uint8_t`. SWIG will then apply an appropriate typemap for you. |
Calling NLTK's concordance - how to get text before/after a word that was used? | 8,898,131 | 10 | 2012-01-17T16:25:57Z | 8,898,784 | 17 | 2012-01-17T17:11:18Z | [
"python",
"nltk"
] | I'm would like to find out what text comes after the instance that concordace returns. So for instance, if you look at an example they give in ['Searching Text' section](http://nltk.googlecode.com/svn/trunk/doc/book/ch01.html), they get concordance of word 'monstrous'. How would you get words that come right after an i... | ```
import nltk
import nltk.book as book
text1 = book.text1
c = nltk.ConcordanceIndex(text1.tokens, key = lambda s: s.lower())
print([text1.tokens[offset+1] for offset in c.offsets('monstrous')])
```
yields
```
['size', 'bulk', 'clubs', 'cannibal', 'and', 'fable', 'Pictures', 'pictures', 'stories', 'cabinet', 'size']... |
Convert UTF-8 with BOM to UTF-8 with no BOM in Python | 8,898,294 | 28 | 2012-01-17T16:37:52Z | 8,898,439 | 43 | 2012-01-17T16:47:57Z | [
"python",
"utf-8",
"utf-16",
"byte-order-mark"
] | Two questions here. I have a set of files which are usually UTF-8 with BOM. I'd like to convert them (ideally in place) to UTF-8 with no BOM. It seems like `codecs.StreamRecoder(stream, encode, decode, Reader, Writer, errors)` would handle this. But I don't really see any good examples on usage. Would this be the best ... | Simply use the "utf-8-sig" codec:
```
fp = open("file.txt")
s = fp.read()
u = s.decode("utf-8-sig")
```
That gives you a `unicode` string without the BOM. You can then use
```
s = u.encode("utf-8")
```
to get a normal UTF-8 encoded string back in `s`. If your files are big, then you should avoid reading them all in... |
Concatenate two numpy arrays in the 4th dimension | 8,898,471 | 16 | 2012-01-17T16:50:08Z | 8,898,707 | 9 | 2012-01-17T17:05:39Z | [
"python",
"numpy"
] | I have two numpy arrays with three dimensions (3 x 4 x 5) and I want to concatenate them so the result has four dimensions (3 x 4 x 5 x 2). In Matlab, this can be done with `cat(4, a, b)`, but not in Numpy.
For example:
```
a = ones((3,4,5))
b = ones((3,4,5))
c = concatenate((a,b), axis=3) # error!
```
To clarify, I... | How about the following:
```
c = concatenate((a[:,:,:,None],b[:,:,:,None]), axis=3)
```
This gives a (3 x 4 x 5 x 2) array, which I believe is laid out in the manner you require.
Here, `None` is synonymous to `np.newaxis`: [Numpy: Should I use newaxis or None?](http://stackoverflow.com/questions/944863/numpy-should-... |
Concatenate two numpy arrays in the 4th dimension | 8,898,471 | 16 | 2012-01-17T16:50:08Z | 8,898,725 | 15 | 2012-01-17T17:07:06Z | [
"python",
"numpy"
] | I have two numpy arrays with three dimensions (3 x 4 x 5) and I want to concatenate them so the result has four dimensions (3 x 4 x 5 x 2). In Matlab, this can be done with `cat(4, a, b)`, but not in Numpy.
For example:
```
a = ones((3,4,5))
b = ones((3,4,5))
c = concatenate((a,b), axis=3) # error!
```
To clarify, I... | Here you go:
```
import numpy as np
a = np.ones((3,4,5))
b = np.ones((3,4,5))
c = np.concatenate((a[...,np.newaxis],b[...,np.newaxis]),axis=3)
``` |
Generate random filename-safe and URL-safe string | 8,898,493 | 4 | 2012-01-17T16:51:23Z | 10,177,819 | 9 | 2012-04-16T16:15:59Z | [
"python",
"string",
"random"
] | I've created a system where users upload videos to my server's filesystem and I need a way to generate unique filenames for the video files. Should I be using random.getrandbits? Is there a way to do this with a combination of letters and numbers? | This is what I use:
```
import base64
import uuid
base64.urlsafe_b64encode(uuid.uuid4().bytes)
```
I generate a uuid, but I use the bytes instead of larger hex version or one with dashes. Then I encode it into a URL-safe base-64 string. This is a shorter length string than using hex, but using base64 makes it so tha... |
SHA1 hash differ between openssl and hashlib/pycrypto | 8,898,628 | 6 | 2012-01-17T16:59:58Z | 8,898,657 | 19 | 2012-01-17T17:02:01Z | [
"python",
"openssl",
"pycrypto",
"hashlib"
] | Why does the hash from using openssl differ from the ones I get in python?
```
$ echo "Lorem ipsum" | openssl dgst -sha1 -hex
(stdin)= d0c05753484098c61e86f402a2875e68992b5ca3
$ python
>>> from hashlib import sha1
>>> sha("Lorem ipsum").hexdigest()
'94912be8b3fb47d4161ea50e5948c6296af6ca05'
>>> from Crypto.Hash import... | You're missing the endline that `echo` will append by default:
```
echo "Lorem ipsum" | openssl dgst -sha1 -hex
(stdin)= d0c05753484098c61e86f402a2875e68992b5ca3
```
With the `-n` parameter, it will echo *only* the string that you gave it, for expected result:
```
echo -n "Lorem ipsum" | openssl dgst -sha1 -hex
(std... |
Calling Python in Java? | 8,898,765 | 44 | 2012-01-17T17:10:28Z | 8,899,042 | 50 | 2012-01-17T17:31:21Z | [
"java",
"python",
"jython"
] | I am wondering if it is possible to call python functions from java code using jython, or is it only for calling java code from python? | You can easily call python functions from Java code with Jython. That is as long as your python code itself runs under jython, i.e. doesn't use some c-extensions that aren't supported.
If that works for you, it's certainly the simplest solution you can get. Otherwise you can use `org.python.util.PythonInterpreter` fro... |
Calling Python in Java? | 8,898,765 | 44 | 2012-01-17T17:10:28Z | 26,759,569 | 18 | 2014-11-05T14:26:02Z | [
"java",
"python",
"jython"
] | I am wondering if it is possible to call python functions from java code using jython, or is it only for calling java code from python? | Hey I thought I would enter my answer to this even though its late. I think there are some important things to consider first with how strong you wish to have the linking between java and python.
**Firstly** Do you only want to call functions or do you actually want python code to change the data in your java objects?... |
Pythonic way to iterate over bits of integer | 8,898,807 | 21 | 2012-01-17T17:13:05Z | 8,898,859 | 10 | 2012-01-17T17:16:32Z | [
"python",
"binary",
"iterator"
] | Let's `a=109` or `1101101` in binary. How do I iterate over bits of this number, eg: `[64, 32, 8, 4, 1]` | My approach:
```
def bits(number):
bit = 1
while number >= bit:
if number & bit:
yield bit
bit <<= 1
```
I don't think there is a builtin function for it.
I also wonder if there isn't a better approach to whatever you are doing. There's a good chance you don't really want to iterate ... |
Pythonic way to iterate over bits of integer | 8,898,807 | 21 | 2012-01-17T17:13:05Z | 8,898,977 | 34 | 2012-01-17T17:25:18Z | [
"python",
"binary",
"iterator"
] | Let's `a=109` or `1101101` in binary. How do I iterate over bits of this number, eg: `[64, 32, 8, 4, 1]` | There's a trick for just getting the 1's out of the binary representation without having to iterate over all the intervening 0's:
```
def bits(n):
while n:
b = n & (~n+1)
yield b
n ^= b
>>> for b in bits(109):
print(b)
1
4
8
32
64
``` |
Python : clear a log file | 8,898,997 | 8 | 2012-01-17T17:27:49Z | 8,899,033 | 21 | 2012-01-17T17:30:51Z | [
"python",
"logging",
"clear"
] | I develop a client-server application and I have log in the server, so I use the logging module. I would like to create a command in the server to clear the file.
I have test with os.remove() but after, the log doesn't work.
Do you have an idea?
Thanks. | It might be better to truncate the file instead of removing it. The easiest solution is to reopen the file for writing from your clearing function and close it:
```
with open('yourlog.log', 'w'):
pass
``` |
loop through kwargs in python | 8,899,129 | 8 | 2012-01-17T17:38:21Z | 8,899,451 | 13 | 2012-01-17T18:04:23Z | [
"python"
] | I am trying to write things the python way but not sure how to get it right. In the code below, I want to read obj.subject and place it into var subject, also read obj.body and place it into body. First I want to read the kwargs variables and search for keywords within the string to replace, if none exists then move on... | I think you're looking for something like this:
```
subject = obj.subject
body = obj.body
for key, value in kwargs.iteritems():
subject = subject.replace('[%s]' % key.toupper(), value)
body = body.replace('[%s]' % key.toupper(), value)
return (subject, body, obj.is_html)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.