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 |
|---|---|---|---|---|---|---|---|---|---|
Getting the "str" has no property "_default_manager" on a Django app just on startup | 5,775,178 | 4 | 2011-04-25T04:32:46Z | 5,775,386 | 9 | 2011-04-25T05:12:13Z | [
"python",
"django",
"apache"
] | Right after I restart Apache to pick up the new Django changes, I get the following errors for probably 30 seconds to a minute afterwards:
`ViewDoesNotExist: Tried home_page in module project.app.views. Error was: 'str' object has no attribute '_default_manager'`
The errors go away after a bit, but it's very odd. Any... | I think it's this bug:
<http://code.djangoproject.com/ticket/10405#comment:11>
Seems like a perfect fit considering google searches don't show much else, and that your problem goes away after some time - according to this ticket due to lazy loading of model strings.
The comment suggests adding the following before y... |
Python: Return 2 ints for index in 2D lists given item | 5,775,352 | 6 | 2011-04-25T05:05:37Z | 5,775,397 | 9 | 2011-04-25T05:14:09Z | [
"python",
"nested-lists"
] | I've been tinkering in python this week and I got stuck on something.
If I had a 2D list like this:
myList = [[1,2],[3,4],[5,6]]
and I did this
```
>>>myList.index([3,4])
```
it would return
```
1
```
However, I want the index of something in side one of the lists, like this
```
>>>myList.index(3)
```
and it... | Try this:
```
def index_2d(myList, v):
for i, x in enumerate(myList):
if v in x:
return (i, x.index(v))
```
Usage:
```
>>> index_2d(myList, 3)
(1, 0)
``` |
How do I find the first letter of each word? | 5,775,719 | 9 | 2011-04-25T06:07:27Z | 5,775,745 | 9 | 2011-04-25T06:11:26Z | [
"python"
] | Ok, I'm trying to figure out how to make a inputed phrase such as this in python ....
Self contained underwater breathing apparatus
output this...
SCUBA
Which would be the first letter of each word. Is this something to do with index? and maybe a .upper function? | Here's the quickest way to get it done
```
input = "Self contained underwater breathing apparatus"
output = ""
for i in input.upper().split():
output += i[0]
``` |
How do I find the first letter of each word? | 5,775,719 | 9 | 2011-04-25T06:07:27Z | 5,775,791 | 17 | 2011-04-25T06:18:45Z | [
"python"
] | Ok, I'm trying to figure out how to make a inputed phrase such as this in python ....
Self contained underwater breathing apparatus
output this...
SCUBA
Which would be the first letter of each word. Is this something to do with index? and maybe a .upper function? | This is the pythonic way to do it:
```
output = "".join(item[0].upper() for item in input.split())
# SCUBA
```
There you go. Short and easy to understand.
**LE**:
If you have other delimiters than space, you can split by words, like this:
```
import re
input = "self-contained underwater breathing apparatus"
output ... |
Test Django views that require login using RequestFactory | 5,777,447 | 24 | 2011-04-25T10:23:50Z | 6,321,808 | 42 | 2011-06-12T12:01:25Z | [
"python",
"django",
"unit-testing",
"django-views"
] | I'm new to Django and I'd like to unit test a view that requires the user to be logged in (`@login_requred`). Django kindly provides the `RequestFactory`, which I can theoretically use to call the view directly:
```
factory = RequestFactory()
request = factory.get("/my/home/url")
response = views.home(request)
```
Ho... | When using RequestFactory, you are testing view with exactly known inputs.
That allows isolating tests from the impact of the additional processing performed by various installed middleware components and thus more precisely testing.
You can setup request with any additional data that view function expect, ie:
```
... |
Test Django views that require login using RequestFactory | 5,777,447 | 24 | 2011-04-25T10:23:50Z | 34,190,740 | 7 | 2015-12-09T23:07:16Z | [
"python",
"django",
"unit-testing",
"django-views"
] | I'm new to Django and I'd like to unit test a view that requires the user to be logged in (`@login_requred`). Django kindly provides the `RequestFactory`, which I can theoretically use to call the view directly:
```
factory = RequestFactory()
request = factory.get("/my/home/url")
response = views.home(request)
```
Ho... | As @bmihelac mentioned, RequestFactory is only testing known inputs (which means no middleware is included). For details about the reasoning, read [here](https://code.djangoproject.com/ticket/15736?cversion=0&cnum_hist=1). The accepted solution is great if you want a blank session (and I agree with @dm03514 that Client... |
Is there a way of drawing a caption box in matplotlib | 5,777,576 | 23 | 2011-04-25T10:43:41Z | 5,779,698 | 26 | 2011-04-25T15:01:46Z | [
"python",
"matplotlib"
] | Is there a function for drawing a caption box underneath a figure/graph using matplotlib? I have searched google and haven't found any such function.

something like what is shown in the image would be great. | Use `pyplot.text`. Here is some sample code:
```
from matplotlib import pyplot as plt
import numpy as np
x = np.arange(0,3,.25)
y = np.sin(x)
txt = '''
Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis... |
Is there a good and easy way to visualize high dimensional data? | 5,779,011 | 12 | 2011-04-25T13:50:51Z | 5,779,054 | 14 | 2011-04-25T13:56:08Z | [
"python",
"language-agnostic",
"graph",
"machine-learning"
] | Can someone please tell me if there is a good (easy) way to visualize high dimensional data? My data is currently 21 dimensions but I would like to see how whether it is dense or sparse. Are there techniques to achieve this? | [Parallel coordinates](http://vis.stanford.edu/protovis/ex/cars.html) are a popular method for visualizing high-dimensional data.
What kind of visualization is best for your data in particular will depend on its characteristics-- how correlated are the different dimensions? |
Is there a good and easy way to visualize high dimensional data? | 5,779,011 | 12 | 2011-04-25T13:50:51Z | 5,779,074 | 8 | 2011-04-25T13:58:11Z | [
"python",
"language-agnostic",
"graph",
"machine-learning"
] | Can someone please tell me if there is a good (easy) way to visualize high dimensional data? My data is currently 21 dimensions but I would like to see how whether it is dense or sparse. Are there techniques to achieve this? | [Principal component analysis](http://en.wikipedia.org/wiki/Principal_component_analysis) could be helpful if the dimensions are correlated. |
Is there a good and easy way to visualize high dimensional data? | 5,779,011 | 12 | 2011-04-25T13:50:51Z | 5,780,277 | 7 | 2011-04-25T16:01:00Z | [
"python",
"language-agnostic",
"graph",
"machine-learning"
] | Can someone please tell me if there is a good (easy) way to visualize high dimensional data? My data is currently 21 dimensions but I would like to see how whether it is dense or sparse. Are there techniques to achieve this? | The buzzword I would search for is [multidimensional scaling](http://en.wikipedia.org/wiki/Multidimensional_scaling). It is a technique to develop a projection from the high dimensional space to a lower space (2 or 3 dimensional) in such a way that points which are close in the full space will be close in the projectio... |
How to specify something other than pk or slug for DetailView | 5,780,803 | 6 | 2011-04-25T17:02:33Z | 5,781,112 | 9 | 2011-04-25T17:30:51Z | [
"python",
"django",
"django-views",
"django-1.3"
] | I was wondering if it was possible to use something besides a pk or slug when you are using a DetailView in Django 1.3.
For example, I currently have:
```
url(r'^mymodel/(?P<pk>\d+)/$', MyDetailView.as_view())
```
as my url. Say I wanted something like:
```
url(r'^mymodel/(?P<name>\d+)/$', MyDetailView.as_view())
`... | A slug doesn't have any particular significance in Django. It's just a name for a field that identifies a row. If your slug is called something else, eg `name`, just specify `name` as the `slug_field` attribute in your view subclass.
If you need something more complicated, you can always override `get_object` in the v... |
Matrix problem Python | 5,781,294 | 2 | 2011-04-25T17:50:31Z | 5,781,319 | 9 | 2011-04-25T17:53:00Z | [
"python",
"sum"
] | For example if I have matrix:
```
x=[['1', '7', 'U1'], ['1.5', '8', 'U1'], ['2', '5.5', 'U2']]
```
How can I take all data from x, except the last one. Then I need to sum this elements.
---
This is what I need: `sum=1+7+1.5+8+2+5.5= ??`
Thanks
---
---
## EDIT2:
---
I try:
```
> x=[['1', '7', 'U1'], ['1.5',... | You can take all elements apart from the last one indexing with `[:-1]`.
To take that sum, try `sum(sum(float(el) for el in els[:-1]) for els in x)`.
If you actually have strings in the list, you might need to cast the elements. Also, if there are always 3 elements, this could be a bit faster:
```
sum(float(a) + flo... |
Python: Difference between != and "is not" | 5,782,203 | 6 | 2011-04-25T19:20:08Z | 5,782,243 | 16 | 2011-04-25T19:23:59Z | [
"python",
"syntax",
"list-comprehension"
] | I'm unclear about the difference between the syntax `!=` and `is not`. They appear to do the same thing:
```
>>> s = 'a'
>>> s != 'a'
False
>>> s is not 'a'
False
```
But, when I use `is not` in a list comprehension, it produces a different result than if I use `!=`.
```
>>> s = "hello"
>>> [c for c in s if c is not... | `is` tests for object identity, but `==` tests for object value equality:
```
In [1]: a = 3424
In [2]: b = 3424
In [3]: a is b
Out[3]: False
In [4]: a == b
Out[4]: True
``` |
Problem opening a text file in Python | 5,782,321 | 5 | 2011-04-25T19:31:18Z | 5,782,352 | 11 | 2011-04-25T19:34:32Z | [
"python"
] | This seems like it should be very easy:
```
f = open('C:\Users\john\Desktop\text.txt', 'r')
```
But I am getting this error:
```
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
f = open('C:\Users\john\Desktop\text.txt', 'r')
IOError: [Errno 22] invalid mode ('r') or filename: 'C:\\... | Your file name has backslash characters in it. Backslash is the escape character in Python strings. Either replace them with `'/'` characters or use `r'C:\Users\john\Desktop\text.txt'`.
You might also find the functions in [os.path](http://docs.python.org/library/os.path.html) useful. |
ctypes: construct pointer from arbitrary integer | 5,783,761 | 14 | 2011-04-25T22:03:25Z | 5,784,284 | 23 | 2011-04-25T23:10:21Z | [
"python",
"ctypes",
"pywin32"
] | For low-level purposes, I need to construct a ctypes pointer from an arbitrary address, given as an integer. For instance:
```
INTP = ctypes.POINTER(ctypes.c_int)
p = INTP(0x12345678) # i *know* this is the address
```
But all such attempts result in
```
TypeError: expected c_long instead of int
```
Is there anythi... | You can use `ctypes.cast(addr, type)`. I'll extend your example to acquire an address via a known object, to demonstrate:
```
INTP = ctypes.POINTER(ctypes.c_int)
num = ctypes.c_int(42)
addr = ctypes.addressof(num)
print 'address:', addr, type(addr)
ptr = ctypes.cast(addr, INTP)
print 'pointer:', ptr
print 'value:', pt... |
Using 100% of all cores with Python (multiprocessing) | 5,784,389 | 17 | 2011-04-25T23:30:01Z | 5,784,407 | 19 | 2011-04-25T23:33:30Z | [
"python",
"multithreading",
"multiprocessing"
] | I have two pieces of code that I'm using to learn about multiprocessing in Python 3.1.
My goal is to use 100% of all the available processors.
However, the code snippets here only reach 30% - 50% on all processors.
Is there anyway to 'force' python to use all 100%?
Is the OS (windows 7, 64bit) limiting Python's access... | To use 100% of all cores, do not create and destroy new processes.
Create a few processes per core and link them with a pipeline.
At the OS-level, all pipelined processes run concurrently.
The less you write (and the more you delegate to the OS) the more likely you are to use as many resources as possible.
```
pyth... |
How to perform a sorting according to rules but with repetition of items to solve circular references? | 5,784,945 | 9 | 2011-04-26T01:17:17Z | 5,785,648 | 10 | 2011-04-26T03:40:46Z | [
"python",
"algorithm",
"language-agnostic",
"sorting",
"circular-reference"
] | To explain in a clearer way my question I will start by explaining the real-life case I am facing.
I am building a physical panel with many words on it that can be selectively lit, in order to compose sentences. This is my situation:
1. I know all the sentences that I want to display
2. I want to find out **[one of] ... | If I understand you correctly, this is equivalent to the [shortest common supersequence](http://www.csc.kth.se/~viggo/wwwcompendium/node165.html) problem. This problem is NP-complete, but there exists approximation algorithms. Google [turns up a few papers](http://www.google.com/?q=%22shortest+common+supersequence%22+a... |
Python MySQLdb issues (TypeError: %d format: a number is required, not str) | 5,785,154 | 36 | 2011-04-26T02:01:49Z | 5,785,163 | 78 | 2011-04-26T02:03:56Z | [
"python",
"insertion",
"mysql-python"
] | I am trying to do the following insert operation:
```
cursor.execute("""
insert into tree (id,parent_id,level,description,code,start,end)
values (%d,%d,%d,%s,%s,%f,%f)
""", (1,1,1,'abc','def',1,1)
)
```
The structure of my MYSQL table is:... | The format string is not really a normal Python format string. You must always use `%s` for all fields. |
bad math or bad programming, maybe both? | 5,786,573 | 8 | 2011-04-26T06:03:28Z | 5,788,748 | 8 | 2011-04-26T10:03:46Z | [
"python",
"geometry",
"python-imaging-library"
] | I'm writing a Python program to generate the Luna Free State flag from the famous Heinlein novel [The Moon is a Harsh Mistress](http://en.wikipedia.org/wiki/The_Moon_Is_a_Harsh_Mistress), as a personal project. I've been cribbing heraldry rules and matching mathematical formulas off the web, but something is clearly wr... | Break the rectangle into two triangles. They will be identical.
The Black triangle + Blue Trapezoid is Triangle A.
The Black Triangle on its own is Triangle B
Triangle A and Triangle B are similar triangles so their area is related by the square of the scale factor relating them.
We want the Blue Trapezoid to be one... |
Python underscore as a function parameter | 5,787,277 | 5 | 2011-04-26T07:29:57Z | 5,787,303 | 13 | 2011-04-26T07:32:49Z | [
"python",
"underscores"
] | I have a python specific question. What does a single underscore `_` as a parameter means?
I have a function calling `hexdump(_)`. The \_ was never defined, so I guess it has some special value, I could not find a reference telling me what it means on the net. I would be happy if you could tell me.
With best regards | In Python shells, the underscore (`_`) means the result of the last evaluated expression in the shell:
```
>>> 2+3
5
>>> _
5
```
There's also `_2`, `_3` and so on in IPython but not in the original Python interpreter. It has no special meaning in Python source code as far as I know, so I guess it is defined somewhere... |
MD5 and SHA-2 collisions in Python | 5,787,471 | 7 | 2011-04-26T07:53:25Z | 5,789,493 | 8 | 2011-04-26T11:15:30Z | [
"python",
"hash",
"mp3",
"md5",
"sha"
] | I'm writing a simple MP3 cataloguer to keep track of which MP3's are on my various devices. I was planning on using MD5 or SHA2 keys to identify matching files even if they have been renamed/moved, etc. I'm not trying to match MP3's that are logically equivalent (i.e.: same song but encoded differently). I have about 8... | I sort of have the feeling that you are reading a chunk of data which is smaller than the expected, and this chunk happens to be the same for both files. I don't know why, but try to open the file in binary with 'rb'. read() should read up to end of file, but windows behaves differently. From the docs
> On Windows, 'b... |
Python NLTK: How to tag sentences with the simplified set of part-of-speech tags? | 5,787,673 | 13 | 2011-04-26T08:19:15Z | 5,793,083 | 15 | 2011-04-26T16:03:47Z | [
"python",
"tagging",
"nltk"
] | Chapter 5 of the Python [NLTK book](http://nltk.googlecode.com/svn/trunk/doc/book/ch05.html) gives this example of tagging words in a sentence:
```
>>> text = nltk.word_tokenize("And now for something completely different")
>>> nltk.pos_tag(text)
[('And', 'CC'), ('now', 'RB'), ('for', 'IN'), ('something', 'NN'), ('com... | To simplify tags from the default tagger, you can use `nltk.tag.simplify.simplify_wsj_tag`, like so:
```
>>> import nltk
>>> from nltk.tag.simplify import simplify_wsj_tag
>>> tagged_sent = nltk.pos_tag(tokens)
>>> simplified = [(word, simplify_wsj_tag(tag)) for word, tag in tagged_sent]
``` |
Python NLTK: How to tag sentences with the simplified set of part-of-speech tags? | 5,787,673 | 13 | 2011-04-26T08:19:15Z | 26,980,638 | 14 | 2014-11-17T19:43:17Z | [
"python",
"tagging",
"nltk"
] | Chapter 5 of the Python [NLTK book](http://nltk.googlecode.com/svn/trunk/doc/book/ch05.html) gives this example of tagging words in a sentence:
```
>>> text = nltk.word_tokenize("And now for something completely different")
>>> nltk.pos_tag(text)
[('And', 'CC'), ('now', 'RB'), ('for', 'IN'), ('something', 'NN'), ('com... | Updated, in case anyone runs across the same problem. NLTK has since upgraded to a "universal" tagset, source [here](https://github.com/nltk/nltk/blob/develop/nltk/tag/mapping.py). Once you've tagged your text, use map\_tag to simplify the tags.
```
import nltk
from nltk.tag import pos_tag, map_tag
text = nltk.word_t... |
Reading a CSV file using Python | 5,788,521 | 4 | 2011-04-26T09:39:28Z | 5,788,588 | 12 | 2011-04-26T09:46:31Z | [
"python",
"csv"
] | please tell me what's the problem in this code it's giving an error
```
import csv
with open('some.csv', 'rb') as f:
reader = csv.reader(f)
for row in reader:
print row
``` | Which version of Python are you using?
The `with` statement is new in 2.6 - if you're using 2.5 you need `from __future__ import with_statement`. If you use a Python older than 2.5 then there's no `with` statement, so just write:
```
import csv
f = open('some.csv', 'rb')
reader = csv.reader(f)
for row in reader:
... |
execfile with argument in python shell | 5,788,891 | 43 | 2011-04-26T10:18:11Z | 5,788,946 | 32 | 2011-04-26T10:22:49Z | [
"python",
"interop"
] | I am not familiar with Python Shell.
I would like to run a command in Python Shell to execute a file with an argument.
For example: `execfile("abc.py")` but how to add 2 arguments?
Thanks in advance | `execfile` runs a Python file, but by loading it, not as a script. You can only pass in variable bindings, not arguments.
If you want to run a program from within Python, use [`subprocess.call`](http://docs.python.org/library/subprocess.html#subprocess.call). E.g.
```
subprocess.call(['./abc.py', arg1, arg2])
``` |
execfile with argument in python shell | 5,788,891 | 43 | 2011-04-26T10:18:11Z | 5,789,028 | 9 | 2011-04-26T10:31:17Z | [
"python",
"interop"
] | I am not familiar with Python Shell.
I would like to run a command in Python Shell to execute a file with an argument.
For example: `execfile("abc.py")` but how to add 2 arguments?
Thanks in advance | You're confusing loading a module into the current interpreter process and calling a Python script externally.
The former can be done by `import`ing the file you're interested in. [execfile](http://docs.python.org/library/functions.html#execfile) is similar to importing but it simply evaluates the file rather than cre... |
execfile with argument in python shell | 5,788,891 | 43 | 2011-04-26T10:18:11Z | 5,790,381 | 21 | 2011-04-26T12:35:32Z | [
"python",
"interop"
] | I am not familiar with Python Shell.
I would like to run a command in Python Shell to execute a file with an argument.
For example: `execfile("abc.py")` but how to add 2 arguments?
Thanks in advance | ```
import sys
import subprocess
subprocess.call([sys.executable, 'abc.py', 'argument1', 'argument2'])
``` |
execfile with argument in python shell | 5,788,891 | 43 | 2011-04-26T10:18:11Z | 14,905,087 | 38 | 2013-02-15T23:30:31Z | [
"python",
"interop"
] | I am not familiar with Python Shell.
I would like to run a command in Python Shell to execute a file with an argument.
For example: `execfile("abc.py")` but how to add 2 arguments?
Thanks in advance | try this:
```
import sys
sys.argv = ['arg1', 'arg2']
execfile('abc.py')
```
Note that when `abc.py` finishes, control will be returned to the calling program. Note too that `abc.py` can call `quit()` if indeed finished. |
execfile with argument in python shell | 5,788,891 | 43 | 2011-04-26T10:18:11Z | 18,675,453 | 21 | 2013-09-07T16:29:58Z | [
"python",
"interop"
] | I am not familiar with Python Shell.
I would like to run a command in Python Shell to execute a file with an argument.
For example: `execfile("abc.py")` but how to add 2 arguments?
Thanks in advance | Actually, wouldn't we want to do this?
```
import sys
sys.argv = ['abc.py','arg1', 'arg2']
execfile('abc.py')
``` |
python re match, findall or search and then NLP (what to do with it?) | 5,789,126 | 3 | 2011-04-26T10:41:09Z | 5,789,416 | 12 | 2011-04-26T11:09:23Z | [
"python",
"regex",
"nlp"
] | I am starting to write code that would capture part of sentence "types" and if they match a criteria, start a specific python script that deals with the "type." I am "finding":) that findall kind of works better for what i am doing hence:
```
m = re.compile(r'([0-9] days from now)')
m.match("i think maybe 7 days from ... | The reason why `m.match()` fails is that it expects the match to start at the beginning of the string.
`findall()` makes sense if you expect more than one (non-overlapping) match in your string. Otherwise, use the `search()` method (which will return the first match it finds).
This is all well covered [in the docs](h... |
count number of xml element from linux shell | 5,790,023 | 7 | 2011-04-26T12:05:11Z | 5,790,374 | 11 | 2011-04-26T12:34:53Z | [
"python",
"xml",
"linux",
"perl"
] | My xml looks something like this :
```
<elements>
<elem>
....bunch of other elements
</elem>
</elements>
```
Is there a way to count the number of occurances of `elem` tag in some xml file trough linux shell? like with perl/python or anything that might work as one liner?
I might try something like `grep -c "elem" m... | The `xml_grep` tool does what you want - try the following:
```
xml_grep --count //elem example.xml
```
That utility is in the `xml-twig-tools` package on Debian / Ubuntu, and the [documentation is here](http://search.cpan.org/dist/XML-Twig/tools/xml_grep/xml_grep). |
SSL error while implementing Apple Push Notification | 5,790,627 | 10 | 2011-04-26T12:52:31Z | 6,806,097 | 16 | 2011-07-24T09:46:57Z | [
"python",
"django",
"apple-push-notifications"
] | I am trying to implement Apple Push Notification using python and django.
i am using following library to implement it
<http://leepa.github.com/django-iphone-push/>
Here is my code that create that send the message
```
from django.http import HttpResponse
from django.utils import simplejson
import json
from push.mo... | I had the exact same problem. Turns out it was a simple error - I had a mistake in IPHONE\_SANDBOX\_APN\_PUSH\_CERT and python could not locate my certificate. Once I pointed it to the right location, it started working.
Note that you might want to double-check your certificate first using openssl command line, such a... |
[] and {} vs list() and dict(), which is better? | 5,790,860 | 28 | 2011-04-26T13:11:56Z | 5,790,919 | 14 | 2011-04-26T13:16:03Z | [
"python",
"performance",
"list",
"dictionary"
] | I understand that they are both essentially the same thing, but in terms of style, which is the better (more Pythonic) one to use to create an empty list or dict? | In my opinion `[]` and `{}` are the most pythonic and readable ways to create empty lists/dicts.
Be wary of `set()`'s though, for example:
```
this_set = {5}
some_other_set = {}
```
Can be confusing. The first creates a set with one element, the second creates an empty dict and **not** a set. |
[] and {} vs list() and dict(), which is better? | 5,790,860 | 28 | 2011-04-26T13:11:56Z | 5,790,954 | 59 | 2011-04-26T13:19:04Z | [
"python",
"performance",
"list",
"dictionary"
] | I understand that they are both essentially the same thing, but in terms of style, which is the better (more Pythonic) one to use to create an empty list or dict? | In terms of speed, it's no competition for empty lists/dicts:
```
>>> from timeit import timeit
>>> timeit("[]")
0.040084982867934334
>>> timeit("list()")
0.17704233359267718
>>> timeit("{}")
0.033620194745424214
>>> timeit("dict()")
0.1821558326547077
```
and for non-empty:
```
>>> timeit("[1,2,3]")
0.2431630277033... |
[] and {} vs list() and dict(), which is better? | 5,790,860 | 28 | 2011-04-26T13:11:56Z | 5,791,030 | 8 | 2011-04-26T13:25:43Z | [
"python",
"performance",
"list",
"dictionary"
] | I understand that they are both essentially the same thing, but in terms of style, which is the better (more Pythonic) one to use to create an empty list or dict? | The dict literal might be a *tiny* bit faster as its bytecode is shorter:
```
In [1]: import dis
In [2]: a = lambda: {}
In [3]: b = lambda: dict()
In [4]: dis.dis(a)
1 0 BUILD_MAP 0
3 RETURN_VALUE
In [5]: dis.dis(b)
1 0 LOAD_GLOBAL 0 (dict)
... |
What effects do parentheses have on the 'or' operator in Python? | 5,791,031 | 4 | 2011-04-26T13:26:04Z | 5,791,057 | 12 | 2011-04-26T13:27:30Z | [
"python"
] | Is there a difference between these two statements in python:
```
if tag == ('/event' or '/organization' or '/business'):
```
and
```
if tag == '/event' or '/organization' or '/business':
``` | They are both wrong. What you need is:
```
if tag == '/event' or tag == '/organization' or tag == '/business':
```
or:
```
if tag in ['/event', '/organization', '/business']:
``` |
What effects do parentheses have on the 'or' operator in Python? | 5,791,031 | 4 | 2011-04-26T13:26:04Z | 5,791,078 | 12 | 2011-04-26T13:28:42Z | [
"python"
] | Is there a difference between these two statements in python:
```
if tag == ('/event' or '/organization' or '/business'):
```
and
```
if tag == '/event' or '/organization' or '/business':
``` | The proper solution is
```
if tag in ('/event', '/organization', '/business'):
```
It not only uses the `in` operator which is perfect for this purpose but also uses a tuple (immutable) so the python interpreter can optimize it better than a (mutable) list.
Benchmark showing that tuples are faster than lists:
```
I... |
Legit python if statement? | 5,791,378 | 5 | 2011-04-26T13:52:55Z | 5,791,395 | 9 | 2011-04-26T13:54:51Z | [
"python"
] | I am new to Python and trying to build a practice project that reads some XML. For some reason this if statement is triggered even for blank whitespace lines:
```
if '<' and '>' in line:
```
Any ideas why? | You probably want:
```
if ('<' in line) and ('>' in line):
```
Your version is being interpreted as this:
```
if ('<') and ('>' in line):
```
which is probably not what you meant.
**Use parenthesis to make things super-obvious.** |
Legit python if statement? | 5,791,378 | 5 | 2011-04-26T13:52:55Z | 5,791,406 | 9 | 2011-04-26T13:55:52Z | [
"python"
] | I am new to Python and trying to build a practice project that reads some XML. For some reason this if statement is triggered even for blank whitespace lines:
```
if '<' and '>' in line:
```
Any ideas why? | Your code says (parethesised for clarity):
```
if '<' and ('>' in line):
```
Which evaluates to:
```
if True and ('>' in line):
```
Which in your case evaluates to `true` when you don't intend to. So, try this instead (parenthesis are optional, but added for clarity):
```
if ('<' in line) and ('>' in line):
``` |
How to open all .txt and .log files in the current directory, search, and print the file the search was found | 5,791,480 | 6 | 2011-04-26T14:00:56Z | 5,791,527 | 17 | 2011-04-26T14:04:24Z | [
"python",
"search",
"file-io"
] | I'm trying to search for a string in all text and log files in the current directory. And if it finds a match, print the text or log file where the match was found. Is this possible, and how can I manipulate the code below to accomplish this task?
```
fiLe = open(logfile, "r")
userString = raw_input("Enter a strin... | Something like this:
```
import os
directory = os.path.join("c:\\","path")
for root,dirs,files in os.walk(directory):
for file in files:
if file.endswith(".log") or file.endswith(".txt"):
f=open(file, 'r')
for line in f:
if userstring in line:
print "file... |
easy_install with various versions of python installed, mac osx | 5,792,060 | 11 | 2011-04-26T14:44:13Z | 5,792,150 | 9 | 2011-04-26T14:49:35Z | [
"python",
"osx",
"macports"
] | I have various versions of python on a mac OSX 10.6 machine, some of them installed with macports:
```
> python_select -l
Available versions:
current none python24 python26 python26-apple python27
```
The default or system version is `python26-apple`. I am now using python27, which I selected with
```
> sudo python_... | If you want your "easy\_install" match your updated python version, follow these steps:
Download the corresponding .egg file at <http://pypi.python.org/pypi/setuptools#files>
Run it as if it were a shell script: sh setuptools-0.6c9-py2.7.egg
This will install the new "easy\_install" executable, compatible with your cu... |
Mass variable declaration and assignment in Python | 5,792,559 | 2 | 2011-04-26T15:22:25Z | 5,792,702 | 7 | 2011-04-26T15:32:15Z | [
"python",
"python-2.x"
] | Trying to create a batch of dictionaries:
January = {}
February = {}
March = {}
I would rather do something like:
January, February, March... = {}
which of course doesn't work.
Ultimately, I'm wanting to create a dictionary of these dictionaries:
MONTHS\_DICT = {'01':January,'02':February...}
Its not a ton of code... | ```
January, February, March = {}, {}, {}
```
That's a little bit more concise way to do the initial declaration. |
In matplotlib.pyplot, how to plot two datasets using interleaved bar graphs? | 5,792,728 | 9 | 2011-04-26T15:34:17Z | 5,792,775 | 7 | 2011-04-26T15:39:21Z | [
"python",
"matplotlib"
] | I am going through [Think Stats](http://thinkstats.com) and I would like to compare multiple data sets visually. I can see from the book examples that it is possible to generate an interleaved bar graph with a different color for each data set by using a module provided by the book author, how to obtain the same result... | Call the bar function multiple times, one for each series. You can control the left position of the bars using the left parameter, and you can use this to prevent overlap.
Entirely untested code:
```
pyplot.bar( numpy.arange(10) * 2, data1, color = 'red' )
pyplot.bar( numpy.arange(10) * 2 + 1, data2, color = 'red' )
... |
In matplotlib.pyplot, how to plot two datasets using interleaved bar graphs? | 5,792,728 | 9 | 2011-04-26T15:34:17Z | 6,712,357 | 9 | 2011-07-15T19:44:28Z | [
"python",
"matplotlib"
] | I am going through [Think Stats](http://thinkstats.com) and I would like to compare multiple data sets visually. I can see from the book examples that it is possible to generate an interleaved bar graph with a different color for each data set by using a module provided by the book author, how to obtain the same result... | There's a brilliant example/demo provided in the documentation:
<http://matplotlib.sourceforge.net/examples/api/barchart_demo.html> |
Print Javascript Exceptions In A QWebView To The Console | 5,792,832 | 5 | 2011-04-26T15:42:52Z | 5,793,634 | 14 | 2011-04-26T16:50:47Z | [
"python",
"qt",
"pyqt"
] | I'm using PyQt4 and a QWebView widget to view a webpage, but it appears as though there is a problem with my Javascript. Other browsers seem to run ok, so I would like to know if any exceptions are occurring by printing them to the console.
The code I'm using is below. What do I need to add to do this?
```
from PyQt4... | Create a subclass of `QWebPage` and define the method `javaScriptConsoleMessage()`:
```
import sys
from PyQt4 import QtCore, QtGui, QtWebKit
class WebPage(QtWebKit.QWebPage):
def javaScriptConsoleMessage(self, msg, line, source):
print '%s line %d: %s' % (source, line, msg)
url = 'http://localhost/test.h... |
How to reload my Python source file, when interactively interpreting it with "python -i" | 5,793,149 | 9 | 2011-04-26T16:09:20Z | 5,793,236 | 11 | 2011-04-26T16:16:59Z | [
"python"
] | When writing or debugging a Python program, I really like using the `-i` command line switch to be able to directly inspect my functions without having to run everything from start to finish.
However, whenever I make a change to the code I have to close and restart my interactive session, losing all temporary variable... | This has to do with the way Python caches modules. You need a module object to pass to reload and you need to repeat the import command. Maybe there's a better way, but here's what I generally use:
```
>> import my_prog
>> from my_prog import *
*** Run some code and debug ***
>> reload(my_prog); from my_prog import *
... |
How to reload my Python source file, when interactively interpreting it with "python -i" | 5,793,149 | 9 | 2011-04-26T16:09:20Z | 5,793,240 | 9 | 2011-04-26T16:17:09Z | [
"python"
] | When writing or debugging a Python program, I really like using the `-i` command line switch to be able to directly inspect my functions without having to run everything from start to finish.
However, whenever I make a change to the code I have to close and restart my interactive session, losing all temporary variable... | When you use `from my_prog import *` you're pulling symbols into the interpreter's global scope, so `reload()` can't change those global symbols, only module-level attributes will be changed when the module is recompiled and reloaded.
For example: **myprog.py**:
```
x = 1
```
In interepreter:
```
>>> import myprog
... |
TCP server is closing connections | 5,793,252 | 4 | 2011-04-26T16:18:40Z | 5,793,418 | 10 | 2011-04-26T16:32:54Z | [
"python"
] | I have this code
```
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
_data = self.request.recv(1024)
Utils.log("Received from %s: %s" % (self.client_address, _data))
```
calling it with
```
kamcon_server = ThreadedTCPServer((HOST, 3011), ThreadedTCPRequestHan... | Your `handle()` method is only calling `recv()` once per connection. If you want to handle multiple messages from the client, you need to loop. You should think about your protocol as well, so that you can handle request/response messages larger than 1024 bytes (e.g. parse `_data` and figure out if you have a complete ... |
Python get __doc__ documentation for instance variable | 5,793,306 | 2 | 2011-04-26T16:24:15Z | 5,793,396 | 7 | 2011-04-26T16:31:28Z | [
"python",
"documentation"
] | In python, I know I'm supposed to document instance variables like this:
```
self.x = 22
"""docstring for x"""
#: docstring for x
self.x = 22
self.x = 22 #: docstring for x
```
But I can't seem to find a way to get hold of that documentation in code. `MyClass.x.__doc__` gives me the doc of the actual type that is in... | This is a feature of documentation utilities such as Sphinx and Epydoc, not a standard feature of Python. I don't believe that there is any direct way of getting variable docstrings.
See <http://epydoc.sourceforge.net/manual-docstring.html#variable-docstrings> |
Mechanize and Javascript | 5,793,414 | 23 | 2011-04-26T16:32:32Z | 5,795,036 | 15 | 2011-04-26T18:50:50Z | [
"javascript",
"python",
"browser",
"mechanize"
] | I want to use Mechanize to simulate browsing to a web page with active JavaScript, including DOM Events and AJAX, and so far I've found no way to do that.
Ilooked at some Python client browsers that support JavaScript like Spynner and Zope, and none of them really work for me. Spynner crashes PyQt all the time and Zop... | From <http://wwwsearch.sourceforge.net/mechanize/faq.html#general>
> If you come across this in a page you want to automate, you have four options. Here they are, roughly in order of simplicity.
>
> Figure out what the JavaScript is doing and emulate it in your Python code: for example, by manually adding cookies to y... |
Mechanize and Javascript | 5,793,414 | 23 | 2011-04-26T16:32:32Z | 5,795,622 | 19 | 2011-04-26T19:46:36Z | [
"javascript",
"python",
"browser",
"mechanize"
] | I want to use Mechanize to simulate browsing to a web page with active JavaScript, including DOM Events and AJAX, and so far I've found no way to do that.
Ilooked at some Python client browsers that support JavaScript like Spynner and Zope, and none of them really work for me. Spynner crashes PyQt all the time and Zop... | I've played with this new alternative to Mechanize (which I love) called [Phantom JS](http://www.phantomjs.org/).
It is a full web kit browser like Safari or Chrome but is headless and scriptable. You script it with javascript, not python (as far as I know at least).
There are some example scripts to get you started.... |
How and why does PyCharm alter Python's import logic? | 5,794,502 | 9 | 2011-04-26T18:02:50Z | 5,794,701 | 11 | 2011-04-26T18:21:22Z | [
"python",
"import",
"pythonpath",
"pycharm"
] | I have a PyCharm 1.2.1 on Windows. I have to edit different branches of the same project - somewhat heavy branches, because they live in different folders on disk - say it to be `c:\apps\alpha` and `c:\apps\beta`. For each such folder PYTHONPATH variable should be adjusted to point to appropriate vendor libraries which... | The correct solution is not to try to work around PyCharm's logic, but rather to use the IDE features as they're designed. That means:
* Not use any .cmd scripts for starting up PyCharm
* Remove all the paths specific to "alpha" and "beta" from the list of paths in Settings | Python Interpreters if any are listed ther... |
Python: Programmatically compiling a Python package into pyc or pyo files | 5,795,147 | 6 | 2011-04-26T19:00:43Z | 5,795,261 | 9 | 2011-04-26T19:10:54Z | [
"python",
"compilation",
"pyc"
] | This is for my test suite.
I have an automatically-generated Python package in a temporary folder. It's all `.py` files. I want to programmatically compile these into (a) `.pyc` and (b) `.pyo` files. (One test will do `.pyc`, another will do `.pyo`.) This should be done with the active interpreter, of course. I do not... | In your Python lib directory, there will be a script called `compileall.py` (e.g., `/usr/lib/python2.6/compileall.py`).
In your code, spawn (e.g., by using `os.spawnl`) an invocation of `compileall.py` pointed at the directory containing your generated code. If you invoke it using `python -O` it will generate `.pyo` f... |
multiply numpy array of scalars by array of vectors | 5,795,700 | 5 | 2011-04-26T19:54:14Z | 5,796,158 | 8 | 2011-04-26T20:37:51Z | [
"python",
"numpy"
] | I have a numpy array of vectors that I need to multiply by an array of scalars. For example:
```
>>> import numpy
>>> x = numpy.array([0.1, 0.2])
>>> y = numpy.array([[1.1,2.2,3.3],[4.4,5.5,6.6]])
```
I can multiply individual elements like this:
```
>>> x[0]*y[0]
array([ 0.11, 0.22, 0.33])
```
but when I try and... | ```
I[1]: x = np.array([0.1, 0.2])
I[2]: y = np.array([[1.1,2.2,3.3],[4.4,5.5,6.6]])
I[3]: y*x[:,np.newaxis]
O[3]:
array([[ 0.11, 0.22, 0.33],
[ 0.88, 1.1 , 1.32]])
``` |
Store NumPy Row and Column Headers | 5,795,748 | 13 | 2011-04-26T19:59:00Z | 5,796,100 | 21 | 2011-04-26T20:32:06Z | [
"python",
"numpy"
] | I have a numpy 2 dimensional numpy array that contains the daily stock prices for multiple stocks. For example
```
daily_prices = np.array([
[4,3,3,1],
[5,4,3,6],
[6,3,2,7],
[3,9,7,4],
[8,4,6,3],
[8,3,3,9]])
```
where each row is a different date, and each column is a different sto... | Use a [structured array](http://docs.scipy.org/doc/numpy/user/basics.rec.html#module-numpy.doc.structured_arrays):
```
import numpy as np
daily_prices = np.array(
[
(4,3,3,1),
(5,4,3,6),
(6,3,2,7),
(3,9,7,4),
(8,4,6,3),
(8,3,3,9)],
dtype=[('MSFT','float'),('CSCO... |
Python convert decimal to hex | 5,796,238 | 11 | 2011-04-26T20:45:15Z | 5,796,257 | 16 | 2011-04-26T20:47:12Z | [
"python",
"function",
"decimal",
"hex"
] | I have a function here that converts decimal to hex but it prints it in reverse order. How would I fix it?
```
def ChangeHex(n):
if (n < 0):
print(0)
elif (n<=1):
print(n)
else:
x =(n%16)
if (x < 10):
print(x),
if (x == 10):
print("A"),
... | This isn't exactly what you asked for but you can use the "hex" function in python:
```
>>> hex(15)
'0xf'
``` |
Python convert decimal to hex | 5,796,238 | 11 | 2011-04-26T20:45:15Z | 5,796,264 | 11 | 2011-04-26T20:47:37Z | [
"python",
"function",
"decimal",
"hex"
] | I have a function here that converts decimal to hex but it prints it in reverse order. How would I fix it?
```
def ChangeHex(n):
if (n < 0):
print(0)
elif (n<=1):
print(n)
else:
x =(n%16)
if (x < 10):
print(x),
if (x == 10):
print("A"),
... | If you want to code this yourself instead of using the built-in function `hex()`, you can simply do the recursive call before you print the current digit:
```
def ChangeHex(n):
if (n < 0):
print(0)
elif (n<=1):
print n,
else:
ChangeHex( n / 16 )
x =(n%16)
if (x < 10)... |
Python convert decimal to hex | 5,796,238 | 11 | 2011-04-26T20:45:15Z | 5,797,518 | 15 | 2011-04-26T23:08:27Z | [
"python",
"function",
"decimal",
"hex"
] | I have a function here that converts decimal to hex but it prints it in reverse order. How would I fix it?
```
def ChangeHex(n):
if (n < 0):
print(0)
elif (n<=1):
print(n)
else:
x =(n%16)
if (x < 10):
print(x),
if (x == 10):
print("A"),
... | I think this solution is elegant:
```
def toHex(dec):
x = (dec % 16)
digits = "0123456789ABCDEF"
rest = dec / 16
if (rest == 0):
return digits[x]
return toHex(rest) + digits[x]
numbers = [0, 11, 16, 32, 33, 41, 45, 678, 574893]
print [toHex(x) for x in numbers]
print [hex(x) for x in numbe... |
Python convert decimal to hex | 5,796,238 | 11 | 2011-04-26T20:45:15Z | 13,595,210 | 41 | 2012-11-27T23:37:39Z | [
"python",
"function",
"decimal",
"hex"
] | I have a function here that converts decimal to hex but it prints it in reverse order. How would I fix it?
```
def ChangeHex(n):
if (n < 0):
print(0)
elif (n<=1):
print(n)
else:
x =(n%16)
if (x < 10):
print(x),
if (x == 10):
print("A"),
... | What about this:
```
hex(dec).split('x')[1]
```
Example:
```
>>> d = 30
>>> hex(d).split('x')[1]
'1e'
```
~Rich |
Python convert decimal to hex | 5,796,238 | 11 | 2011-04-26T20:45:15Z | 20,806,018 | 10 | 2013-12-27T18:40:46Z | [
"python",
"function",
"decimal",
"hex"
] | I have a function here that converts decimal to hex but it prints it in reverse order. How would I fix it?
```
def ChangeHex(n):
if (n < 0):
print(0)
elif (n<=1):
print(n)
else:
x =(n%16)
if (x < 10):
print(x),
if (x == 10):
print("A"),
... | I use
```
"0x%X" % n
```
where `n` is the decimal number to convert. |
Python convert decimal to hex | 5,796,238 | 11 | 2011-04-26T20:45:15Z | 27,144,564 | 7 | 2014-11-26T08:39:18Z | [
"python",
"function",
"decimal",
"hex"
] | I have a function here that converts decimal to hex but it prints it in reverse order. How would I fix it?
```
def ChangeHex(n):
if (n < 0):
print(0)
elif (n<=1):
print(n)
else:
x =(n%16)
if (x < 10):
print(x),
if (x == 10):
print("A"),
... | If without `'0x'` prefix:
```
'{0:x}'.format(int(dec))
```
else use built-in `hex()` funtion. |
Python reverse-stride slicing | 5,798,136 | 20 | 2011-04-27T00:50:56Z | 5,798,144 | 24 | 2011-04-27T00:52:42Z | [
"python",
"string",
"slice"
] | A specific example of my question is, "How can I get '3210' in this example?"
```
>>> foo = '0123456'
>>> foo[0:4]
'0123'
>>> foo[::-1]
'6543210'
>>> foo[4:0:-1] # I was shooting for '3210' but made a fencepost error, that's fine, but...
'4321'
>>> foo[3:-1:-1] # How can I get '3210'?
''
>>> foo[3:0:-1]
'321'
```
It ... | Simply exclude the end range index...
```
>>> foo[3::-1]
'3210'
```
Ironically, about the only option I think you didn't try. |
Python reverse-stride slicing | 5,798,136 | 20 | 2011-04-27T00:50:56Z | 5,799,215 | 7 | 2011-04-27T04:06:43Z | [
"python",
"string",
"slice"
] | A specific example of my question is, "How can I get '3210' in this example?"
```
>>> foo = '0123456'
>>> foo[0:4]
'0123'
>>> foo[::-1]
'6543210'
>>> foo[4:0:-1] # I was shooting for '3210' but made a fencepost error, that's fine, but...
'4321'
>>> foo[3:-1:-1] # How can I get '3210'?
''
>>> foo[3:0:-1]
'321'
```
It ... | If you're looking for something a little more human-readable than extended slice notation:
```
>>> foo = '0123456'
>>> ''.join(reversed(foo[0:4]))
'3210'
``` |
Using numpy.argmax() on multidimensional arrays | 5,798,364 | 9 | 2011-04-27T01:31:55Z | 5,802,380 | 11 | 2011-04-27T10:05:02Z | [
"python",
"indexing",
"numpy",
"closest"
] | I have a 4 dimensional array, i.e., `data.shape = (20,30,33,288)`. I am finding the index of the closest array to n using
```
index = abs(data - n).argmin(axis = 1), so
index.shape = (20,33,288) with the indices varying.
```
I would like to use `data[index] = "values"` with `values.shape = (20,33,288)`, but `data[ind... | You should be able to access the maximum values indexed by `index` using `numpy.indices()`:
```
x, z, t = numpy.indices(index.shape)
data[x, index, z, t]
``` |
Running Cumulative sum of 1d NumPy Array | 5,798,675 | 12 | 2011-04-27T02:26:00Z | 5,798,697 | 26 | 2011-04-27T02:29:53Z | [
"python",
"numpy"
] | I have a numpy array like
`x=np.array([1,2,3,4])`
I want to create another numpy array y which is the cumulative sum of x, so that
`y=np.array([1,3,6,10])`
What is a good num-Pythonic way to do this? | ```
y = np.cumsum(x)
```
See <http://docs.scipy.org/doc/numpy/reference/generated/numpy.cumsum.html> |
Running Cumulative sum of 1d NumPy Array | 5,798,675 | 12 | 2011-04-27T02:26:00Z | 5,799,082 | 7 | 2011-04-27T03:42:58Z | [
"python",
"numpy"
] | I have a numpy array like
`x=np.array([1,2,3,4])`
I want to create another numpy array y which is the cumulative sum of x, so that
`y=np.array([1,3,6,10])`
What is a good num-Pythonic way to do this? | Another option is:
```
y = np.add.accumulate(x)
```
which is often times faster than `np.cumsum` even though the documentation says they are equivalent. |
PyParsing OR statement | 5,798,994 | 2 | 2011-04-27T03:25:49Z | 5,802,665 | 14 | 2011-04-27T10:32:14Z | [
"python",
"logging",
"amazon-s3",
"pyparsing"
] | This is going to end up being really simple, but I'm trying to match one of the two patterns:
```
"GET /ligonier-broadcast-media/mp3/rym20110421.mp3 HTTP/1.1"
```
or
```
-
```
I've tried something like this:
```
key = Word(alphas + nums + "/" + "-" + "_" + "." + "?" + "=" + "%" + "&")
uri = Or("-" | Group(
... | In general, the Or, And, MatchFirst, and Each classes are very rarely used overtly in pyparsing. The recommended style is to use their analogous operator overloads. In your case, you are using both forms, and it is just getting in your way.
Here is your expression, after a little cleaning up:
```
key = Word(alphanums... |
How to see if file is older than 3 months in Python? | 5,799,070 | 4 | 2011-04-27T03:41:09Z | 5,799,092 | 13 | 2011-04-27T03:45:36Z | [
"python",
"time"
] | I'm curious about manipulating time in Python. I can get the (last modified) age of a file using the `os.path.getmtime()` function as such:
```
import os.path, time
os.path.getmtime(oldLoc)
```
I need to run some kind of test to see whether this time is within the last three months or not, but I'm thoroughly con... | ```
time.time() - os.path.getmtime(oldLoc) > (3 * 30 * 24 * 60 * 60)
``` |
How to see if file is older than 3 months in Python? | 5,799,070 | 4 | 2011-04-27T03:41:09Z | 5,799,209 | 12 | 2011-04-27T04:05:37Z | [
"python",
"time"
] | I'm curious about manipulating time in Python. I can get the (last modified) age of a file using the `os.path.getmtime()` function as such:
```
import os.path, time
os.path.getmtime(oldLoc)
```
I need to run some kind of test to see whether this time is within the last three months or not, but I'm thoroughly con... | You can use a bit of datetime arthimetic here for the sake of clarity.
```
>>> import datetime
>>> today = datetime.datetime.today()
>>> modified_date = datetime.datetime.fromtimestamp(os.path.getmtime('yourfile'))
>>> duration = today - modified_date
>>> duration.days > 90 # approximation again. there is no direct su... |
Why are Python's datetime ISO-functions logically incorrect and buggy? | 5,799,149 | 3 | 2011-04-27T03:55:31Z | 5,799,193 | 17 | 2011-04-27T04:02:59Z | [
"python",
"iso8601"
] | I'm kind of stunned that the python `datetime` `.isoformat()` function doesn't return correct information. The function correctly returns an ISO 8601-formatted string when a timezone is provided to the fromtimestamp() method. However, the timezone is ignored in the calculation of the resultant. Observe:
```
13:29 msim... | Make sure you are using "timezone aware" `datetime` objects, not "naive" objects.
In order to make a timezone "aware" `datetime` object you need to be sure to provide the timezone when you create it.
More details are here:
<http://docs.python.org/library/datetime.html>
Also, ISO 8601 does *not* require timezone, and... |
How to get status code by using selenium.py (python code) | 5,799,228 | 5 | 2011-04-27T04:08:50Z | 19,246,280 | 7 | 2013-10-08T11:16:58Z | [
"python",
"selenium"
] | I am writing a selenium script by python, but I think I don't see any information about:
**How to get http status code from selenium Python code**.
Or I missing something. If anyone found that, please feel free to post. | I'v been surfing the net for about 3 hours and I found not a single way to do that with web-driver. I'v not ever worked with selenium directly. The only suggestion that came in my mind is to use module "requests" like this:
```
import requests
from selenium import webdriver
driver = webdriver.get("url")
r = requests.... |
How to get status code by using selenium.py (python code) | 5,799,228 | 5 | 2011-04-27T04:08:50Z | 25,162,599 | 8 | 2014-08-06T14:09:15Z | [
"python",
"selenium"
] | I am writing a selenium script by python, but I think I don't see any information about:
**How to get http status code from selenium Python code**.
Or I missing something. If anyone found that, please feel free to post. | ## It's Not Possible.
Unfortunately, Selenium does not provide this information by design. There is [a very lengthy](https://code.google.com/p/selenium/issues/detail?id=141) discussion about this, but the short of it is that:
1. Selenium is a browser emulation tool, not necessarily a testing tool.
2. Selenium perform... |
Python OCR Module in Linux? | 5,799,946 | 18 | 2011-04-27T05:51:45Z | 5,799,989 | 14 | 2011-04-27T05:56:37Z | [
"python",
"ocr"
] | I want to find a easy-to-use OCR python module in linux, I have found pytesser <http://code.google.com/p/pytesser/>, but it contains a .exe executable file.
I tried changed the code to use wine, and it really works, but it's too slow and really not a good idea.
Is there any Linux alternatives that as easy-to-use as i... | You can just wrap `tesseract` in a function:
```
import os
import tempfile
import subprocess
def ocr(path):
temp = tempfile.NamedTemporaryFile(delete=False)
process = subprocess.Popen(['tesseract', path, temp.name], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
process.communicate()
with open(te... |
Python OCR Module in Linux? | 5,799,946 | 18 | 2011-04-27T05:51:45Z | 5,800,663 | 10 | 2011-04-27T07:14:11Z | [
"python",
"ocr"
] | I want to find a easy-to-use OCR python module in linux, I have found pytesser <http://code.google.com/p/pytesser/>, but it contains a .exe executable file.
I tried changed the code to use wine, and it really works, but it's too slow and really not a good idea.
Is there any Linux alternatives that as easy-to-use as i... | In addition to Blender's answer, that just executs Tesseract executable, I would like to add that there exist other alternatives for OCR that can also be called as external process.
ABBYY comand line OCR utility: <http://ocr4linux.com/en:start>
It is not free, so worth to consider only if Tesseract accuracy is not go... |
Django/Apache/mod_wsgi not using virtualenv's Python binary | 5,800,608 | 6 | 2011-04-27T07:07:14Z | 5,801,217 | 8 | 2011-04-27T08:21:31Z | [
"python",
"django",
"apache",
"mod-wsgi",
"wsgi"
] | I have a virtualenv at /opt/webapps/ff/ with its own Python installation. I have WSGIPythonHome set to /opt/webapps/ff in my Apache config file (and this is definitely getting used in some capacity, because if I set it to a slightly different existing directory and restart Apache I get a 504). But if I e.g. `assert Fal... | These are the instructions I used which seem to be working well.
<http://code.google.com/p/modwsgi/wiki/VirtualEnvironments>
> Using 'site.addsitedir()' is a bit
> different to simply adding the
> directory to 'sys.path' as the
> function will open up any '.pth' files
> located in the directory and process
> them. Th... |
python sqlite "create table if not exists" problem | 5,801,170 | 15 | 2011-04-27T08:16:13Z | 5,802,921 | 23 | 2011-04-27T10:57:17Z | [
"python",
"sqlite3"
] | I'm having an issue using sqlite to create a table only if it doesn't exist. Basically, I have a table that I'm dropping and remaking once in a long while. However, if the table already existed (before I drop and remake it), then I get the following error when trying to insert for the first time:
```
Traceback (most r... | I can duplicate the issue with the following simplified script:
```
import sqlite3
location = 'data'
table_name = 'table_name'
conn = sqlite3.connect(location)
c = conn.cursor()
sql = 'create table if not exists ' + table_name + ' (id integer)'
c.execute(sql)
sql = 'drop table ' + table_name
c.execute(sql)
sql = ... |
Non-consuming regular expression split in Python | 5,801,945 | 7 | 2011-04-27T09:27:13Z | 5,801,963 | 11 | 2011-04-27T09:29:25Z | [
"python",
"regex"
] | How can a string be split on a separator expression while leaving that separator on the preceding string?
```
>>> text = "This is an example. Is it made up of more than once sentence? Yes, it is."
>>> re.split("[\.\?!] ", text)
['This is an example', 'Is it made up of more than one sentence', 'Yes, it is.']
```
I wou... | ```
>>> re.split("(?<=[\.\?!]) ", text)
['This is an example.', 'Is it made up of more than once sentence?', 'Yes, it is.']
```
The crucial thing is the use of a *look-behind* assertion with `?<=`. |
How to check if a datetime object is localized with pytz? | 5,802,108 | 25 | 2011-04-27T09:42:59Z | 5,802,203 | 22 | 2011-04-27T09:51:43Z | [
"python",
"datetime",
"timezone",
"pytz"
] | I want to store a datetime object with a localized UTC timezone. The method that stores the datetime object can be given a non-localized datetime (naive) object or an object that already has been localized. How do I determine if localization is needed?
Code with missing if condition:
```
class MyClass:
def set_date... | if you want to check if a datetime object 'd' is localized, check the d.tzinfo, if it is None, no localization. |
How to check if a datetime object is localized with pytz? | 5,802,108 | 25 | 2011-04-27T09:42:59Z | 27,596,917 | 27 | 2014-12-22T05:14:58Z | [
"python",
"datetime",
"timezone",
"pytz"
] | I want to store a datetime object with a localized UTC timezone. The method that stores the datetime object can be given a non-localized datetime (naive) object or an object that already has been localized. How do I determine if localization is needed?
Code with missing if condition:
```
class MyClass:
def set_date... | > How do I determine if localization is needed?
From [`datetime` docs](https://docs.python.org/3/library/datetime.html#datetime.timezone):
* a datetime object `d` is aware iff:
```
d.tzinfo is not None and d.tzinfo.utcoffset(d) is not None
```
* `d` is naive iff:
```
d.tzinfo is None or d.tzinfo.utcoffset... |
python temporary files | 5,802,684 | 3 | 2011-04-27T10:33:36Z | 5,802,748 | 10 | 2011-04-27T10:39:30Z | [
"python",
"temporary-files"
] | I have this code:
```
import tempfile
def tmp_me():
tmp = tempfile.NamedTemporaryFile()
tmp1 = tempfile.NamedTemporaryFile()
lst = [tmp.name, tmp1.name]
return lst
def exit_dialog():
lst = tmp_me()
print lst
import filecmp
eq = filecmp.cmp(lst[0],lst[1])
print eq
exit_dialog()
```... | Error 2 is that the file is not found (ERROR\_FILE\_NOT\_FOUND).
`NamedTemporaryFile` has the `delete` parameter which is by default set to `True`. Are you sure that the file is not being immediately deleted at the return of your `tmp_me` method?
You could try using:
```
tempfile.NamedTemporaryFile(delete=False)
``` |
python temporary files | 5,802,684 | 3 | 2011-04-27T10:33:36Z | 5,802,826 | 8 | 2011-04-27T10:47:26Z | [
"python",
"temporary-files"
] | I have this code:
```
import tempfile
def tmp_me():
tmp = tempfile.NamedTemporaryFile()
tmp1 = tempfile.NamedTemporaryFile()
lst = [tmp.name, tmp1.name]
return lst
def exit_dialog():
lst = tmp_me()
print lst
import filecmp
eq = filecmp.cmp(lst[0],lst[1])
print eq
exit_dialog()
```... | Have `temp_me` return the list of the two temp files, instead of just their names (so they don't get garbage collected), and pull the names out in `exit_dialog`. |
How to create a legend for 3D bar in matplotlib? | 5,803,015 | 17 | 2011-04-27T11:03:45Z | 5,807,175 | 18 | 2011-04-27T16:09:32Z | [
"python",
"graph",
"numpy",
"matplotlib"
] | Given `ax = plt.subplot()`:
`ax.bar()[0]` can be passed to `plt.legend()`.
However, `ax.bar3d()` returns `None`. How do I create legend for displayed bars?
UPDATE:
Passing legend="stuff" to `ax.bar3d()` and than calling `ax.legend()` raises
```
/usr/lib/python2.6/site-packages/matplotlib/axes.py:4368: UserWarning:... | You need to use a [proxy artist](http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist) where legends are not supported.
This code:
```
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x, y ... |
Improve speed of reading and converting from binary file with python | 5,804,052 | 8 | 2011-04-27T12:24:56Z | 5,804,497 | 7 | 2011-04-27T12:59:01Z | [
"python",
"performance",
"file-io"
] | I know there have been some questions regarding file reading, binary data handling and integer conversion using struct() before, so I come here to ask about a piece of code I have that I think is taking too much time to run. The file being read is a multichannel datasample recording (short integers), with intercalated ... | If the files are only 20-30M, why not read the entire file, decode the nums in a single call to `unpack` and then distribute them among your channels by iterating over the array:
```
data = open('data.bin', 'rb').read()
values = struct.unpack('%dh' % len(data)/2, data)
del data
# iterate over channels, and assign from... |
Improve speed of reading and converting from binary file with python | 5,804,052 | 8 | 2011-04-27T12:24:56Z | 5,805,696 | 9 | 2011-04-27T14:25:15Z | [
"python",
"performance",
"file-io"
] | I know there have been some questions regarding file reading, binary data handling and integer conversion using struct() before, so I come here to ask about a piece of code I have that I think is taking too much time to run. The file being read is a multichannel datasample recording (short integers), with intercalated ... | You could use [`array`](http://docs.python.org/library/array.html) to read your data:
```
import array
import os
fn = 'data.bin'
a = array.array('h')
a.fromfile(open(fn, 'rb'), os.path.getsize(fn)/a.itemsize)
```
It is 40x times faster than `struct.unpack` from [@samplebias's answer](http://stackoverflow.com/questio... |
How to insert the contents of one list into another | 5,805,892 | 16 | 2011-04-27T14:39:15Z | 5,805,910 | 43 | 2011-04-27T14:41:03Z | [
"list",
"python"
] | I am trying to combine the contents of two lists, in order to later perform processing on the entire data set. I initially looked at the built in `insert` function, but it inserts as a list, rather than the contents of the list.
I can slice and append the lists, but is there a cleaner / more Pythonic way of doing what... | You can do the following using the slice syntax on the left hand side of an assignment:
```
>>> array = ['the', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
>>> array[1:1] = ['quick', 'brown']
>>> array
['the', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']
```
That's about as Pythonic as it gets! |
How to insert the contents of one list into another | 5,805,892 | 16 | 2011-04-27T14:39:15Z | 5,806,005 | 18 | 2011-04-27T14:47:36Z | [
"list",
"python"
] | I am trying to combine the contents of two lists, in order to later perform processing on the entire data set. I initially looked at the built in `insert` function, but it inserts as a list, rather than the contents of the list.
I can slice and append the lists, but is there a cleaner / more Pythonic way of doing what... | The `extend` method of list object does this, but at the end of the original list.
```
addition.extend(array)
``` |
Discontinuous slice in python list | 5,805,914 | 20 | 2011-04-27T14:41:14Z | 5,806,104 | 11 | 2011-04-27T14:53:21Z | [
"python",
"performance",
"list",
"slice"
] | I'm looking for an efficient way of achieving this, which I think is a slicing-like operation:
```
>>> mylist = range(100)
>>>magicslicer(mylist, 10, 20)
[0,1,2,3,4,5,6,7,8,9,30,31,32,33,34,35,36,37,38,39,60,61,62,63......,97,98,99]
```
the idea is: the slicing gets 10 elements, then *skips* 20 elements, then gets ne... | Maybe the best way is the straight-forward approach:
```
def magicslicer(seq, take, skip):
return [x for start in range(0, len(seq), take + skip)
for x in seq[start:start + take]]
```
I don't think you can avoid the loops.
**Edit**: Since this is tagged "performance", here a comparison with the mod... |
Discontinuous slice in python list | 5,805,914 | 20 | 2011-04-27T14:41:14Z | 5,814,136 | 18 | 2011-04-28T05:43:39Z | [
"python",
"performance",
"list",
"slice"
] | I'm looking for an efficient way of achieving this, which I think is a slicing-like operation:
```
>>> mylist = range(100)
>>>magicslicer(mylist, 10, 20)
[0,1,2,3,4,5,6,7,8,9,30,31,32,33,34,35,36,37,38,39,60,61,62,63......,97,98,99]
```
the idea is: the slicing gets 10 elements, then *skips* 20 elements, then gets ne... | `itertools.compress` (new in 2.7/3.1) nicely supports use cases like this one, especially when combined with `itertools.cycle`:
```
from itertools import cycle, compress
seq = range(100)
criteria = cycle([True]*10 + [False]*20) # Use whatever pattern you like
>>> list(compress(seq, criteria))
[0, 1, 2, 3, 4, 5, 6, 7, ... |
Python: how to convert from Windows 1251 to Unicode? | 5,806,980 | 7 | 2011-04-27T15:55:02Z | 5,807,248 | 9 | 2011-04-27T16:15:26Z | [
"python",
"unicode",
"encoding"
] | I'm trying to convert file content from Windows-1251 (Cyrillic) to Unicode with Python. I found this function, but it doesn't work.
```
#!/usr/bin/env python
import os
import sys
import shutil
def convert_to_utf8(filename):
# gather the encodings you think that the file may be
# encoded inside a tuple
encodings = ('... | ```
import codecs
f = codecs.open(filename, 'r', 'cp1251')
u = f.read() # now the contents have been transformed to a Unicode string
out = codecs.open(output, 'w', 'utf-8')
out.write(u) # and now the contents have been output as UTF-8
```
Is this what you intend to do? |
python+numpy: efficient way to take the min/max n values and indices from a matrix | 5,807,047 | 8 | 2011-04-27T15:59:28Z | 5,807,227 | 7 | 2011-04-27T16:14:00Z | [
"python",
"optimization",
"performance",
"numpy"
] | What's an efficient way, given a numpy matrix (2-d array), to return the min/max `n` values (along with their indices) in the array? Currently I have:
```
def n_max(arr, n):
res = [(0,(0,0))]*n
for y in xrange(len(arr)):
for x in xrange(len(arr[y])):
val = float(arr[y,x])
el = (... | Since there is no heap implementation in NumPy, probably your best guess is to sort the whole array and take the last `n` elements:
```
def n_max(arr, n):
indices = arr.ravel().argsort()[-n:]
indices = (numpy.unravel_index(i, arr.shape) for i in indices)
return [(arr[i], i) for i in indices]
```
(This wil... |
How to get coordinates of address from Python | 5,807,195 | 5 | 2011-04-27T16:11:25Z | 5,807,213 | 10 | 2011-04-27T16:13:00Z | [
"python",
"django",
"google-maps"
] | I need to geocode an address to a latitude, longitude pair to display on Google Maps, but I need to do this server-side in Django. I could only find reference to the Javascript V3 API. How do I do it from Python? | I would suggest using [Py-Googlemaps](http://py-googlemaps.sourceforge.net/). To use it is easy:
```
from googlemaps import GoogleMaps
gmaps = GoogleMaps(API_KEY)
lat, lng = gmaps.address_to_latlng(address)
``` |
Python - Example of urllib2 asynchronous / threaded request using HTTPS | 5,808,138 | 11 | 2011-04-27T17:31:03Z | 5,808,510 | 7 | 2011-04-27T18:03:18Z | [
"python",
"multithreading",
"urllib2"
] | I'm having a heck of a time getting asynchronous / threaded HTTPS requests to work using Python's urllib2.
Does anyone out there have a basic example that implements urllib2.Request, urllib2.build\_opener and a subclass of urllib2.HTTPSHandler?
Thanks! | The code below does 7 http requests asynchronously at the same time.
It does not use threads, instead it uses asynchronous networking with the [twisted](http://twistedmatrix.com/) library.
```
from twisted.web import client
from twisted.internet import reactor, defer
urls = [
'http://www.python.org',
'http://stack... |
Custom dictionary lookup in Python | 5,808,970 | 12 | 2011-04-27T18:46:30Z | 5,809,035 | 17 | 2011-04-27T18:52:49Z | [
"dictionary",
"python"
] | if I have a dictionary like this
```
>>> d = {10: 3, 100: 2, 1000: 1}
```
I can type something like:
```
>>> d.get(10), d.get(100), d.get(1000)
(3, 2, 1)
```
Though I want that if the given key is not found, the value corresponding to the nearest key respect the given key is returned:
```
>>> d.get(20), d.get(60),... | You can derive from `dict` to change the behaviour of the `get()` method:
```
class ClosestDict(dict):
def get(self, key):
key = min(self.iterkeys(), key=lambda x: abs(x - key))
return dict.get(self, key)
d = ClosestDict({10: 3, 100: 2, 1000: 1})
print (d.get(20), d.get(60), d.get(200))
```
print... |
Line continuation for list comprehensions or generator expressions in python | 5,809,059 | 55 | 2011-04-27T18:55:12Z | 5,809,080 | 81 | 2011-04-27T18:56:41Z | [
"python",
"coding-style",
"list-comprehension",
"pep8"
] | How are you supposed to break up a very long list comprehension?
```
[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]
```
I have also seen somewhere that people that dislike using '\' to break up lines,
but never understood why. What is the reason behind this? | ```
[x
for
x
in
(1,2,3)
]
```
works fine, so you can pretty much do as you please. I'd personally prefer
```
[something_that_is_pretty_long
for something_that_is_pretty_long
in somethings_that_are_pretty_long]
```
The reason why `\` isn't appreciated very much is that it appears at the *end* of a line, wher... |
Line continuation for list comprehensions or generator expressions in python | 5,809,059 | 55 | 2011-04-27T18:55:12Z | 5,809,097 | 11 | 2011-04-27T18:58:15Z | [
"python",
"coding-style",
"list-comprehension",
"pep8"
] | How are you supposed to break up a very long list comprehension?
```
[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]
```
I have also seen somewhere that people that dislike using '\' to break up lines,
but never understood why. What is the reason behind this? | I'm not opposed to:
```
variable = [something_that_is_pretty_long
for something_that_is_pretty_long
in somethings_that_are_pretty_long]
```
You don't need `\` in this case. In general, I think people avoid `\` because it's slightly ugly, but also can give problems if it's not the very last thi... |
Line continuation for list comprehensions or generator expressions in python | 5,809,059 | 55 | 2011-04-27T18:55:12Z | 9,335,822 | 10 | 2012-02-17T21:41:41Z | [
"python",
"coding-style",
"list-comprehension",
"pep8"
] | How are you supposed to break up a very long list comprehension?
```
[something_that_is_pretty_long for something_that_is_pretty_long in somethings_that_are_pretty_long]
```
I have also seen somewhere that people that dislike using '\' to break up lines,
but never understood why. What is the reason behind this? | You can also make use of multiple indentations in cases where you're dealing with a list of several data structures.
```
new_list = [
{
'attribute 1': a_very_long_item.attribute1,
'attribute 2': a_very_long_item.attribute2,
'list_attribute': [
{
'dict_key_1': att... |
Monitoring Celery, what should I use? | 5,809,408 | 7 | 2011-04-27T19:22:16Z | 5,809,687 | 17 | 2011-04-27T19:47:04Z | [
"python",
"django",
"monitoring",
"celery"
] | I'm using Django, Celery, and Django-Celery. I'd like to monitor the state/results of my tasks, but I'm a little confused on how to do that.
Do I use `./manage.py celeryev`, `./manage.py celerymon`, `./manage.py celerycam`? Do I run `sudo /etc/init.d/celeryevcam start`? | Run:
```
./manage.py celeryd -E
./manage.py celerycam
```
The first starts a worker with events enabled.
Now you can find task results in the django admin interface. Ensure you have djcelery in your INSTALLED\_APPS. If you want to see task state use also celerymon. |
New to Python programming, could somebody please explain the fault with this program? | 5,810,235 | 3 | 2011-04-27T20:34:54Z | 5,810,278 | 8 | 2011-04-27T20:37:59Z | [
"python"
] | I am very new to Python programming, I am writing a simple fighting game at the moment (text based) that is extremely simple as I'm just learning the basics at the moment.
I have placed the code for my game below (it is not finished), my problem is that every time I run the program, when you enter which character you'd... | `__init__()` shadows the `attack()` method on the object. Use a different name. |
New to Python programming, could somebody please explain the fault with this program? | 5,810,235 | 3 | 2011-04-27T20:34:54Z | 5,810,299 | 9 | 2011-04-27T20:40:20Z | [
"python"
] | I am very new to Python programming, I am writing a simple fighting game at the moment (text based) that is extremely simple as I'm just learning the basics at the moment.
I have placed the code for my game below (it is not finished), my problem is that every time I run the program, when you enter which character you'd... | `first_player.attack` is a number because of `self.attack = random.randint(30,40)`. I suspect that you want that named differently so that it doesn't overwrite your `attack` method. |
Django for social networking | 5,810,540 | 16 | 2011-04-27T21:02:03Z | 5,848,881 | 22 | 2011-05-01T14:06:48Z | [
"python",
"django"
] | I know this is a relatively broad question, but is Django robust enough to build a social network on? I am concerned mainly with performance/speed. For example, for a site with a small user base (<10,000 users), is it possible to create a Django-backed site that would perform at a speed similar to Facebook?
What are i... | "What are its potential weaknesses, and things that need to be focused on in order to make it as fast as possible?"
The one thing you might be worried about further down the road is that depending on how you create your models and connect them to one another, you may run into an issue where a single page generates man... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.