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 |
|---|---|---|---|---|---|---|---|---|---|
Recognising tone of the audio | 1,797,631 | 14 | 2009-11-25T15:19:55Z | 1,798,363 | 18 | 2009-11-25T16:58:22Z | [
"python",
"audio"
] | I have a guitar and I need my pc to be able to tell what note is being played, recognizing the tone. Is it possible to do it in python, also is it possible with pygame? Being able of doing it in pygame would be very helpful. | I once wrote a utility that does exactly that - it analyses what sounds are being played.
You can look at the code [here](https://web.archive.org/web/20120112041203/http://trac.assembla.com/guitarist/browser/src/soundAnalyzer/AudioRecorder.py) (or you can download the whole project. its integrated with Frets On Fire, ... |
Fabric error No handlers could be found for logger "paramiko.transport" | 1,797,925 | 5 | 2009-11-25T15:59:42Z | 1,822,345 | 9 | 2009-11-30T20:57:55Z | [
"python",
"fabric"
] | I'm not sure why I'm getting this error that's terminating my connection. I updated paramiko-1.7.6 from 1.7.5 via easy\_install.
I'm trying to setup Fabric to upload my Django app to my server. The error seems to be happening when I attempt to make a backup of the existing app directory:
```
def backup_current_instal... | It turns out that this error was a result of me not configuring **env.password** as a simple string.
Both **env.user** and **env.password** should be simple strings, not Lists.
[Documentation](http://docs.fabfile.org/0.9.0/usage/env.html#user) |
Artificial Inteligence library in python | 1,798,091 | 19 | 2009-11-25T16:19:27Z | 1,798,169 | 19 | 2009-11-25T16:29:05Z | [
"python",
"artificial-intelligence",
"genetic-algorithm",
"simulated-annealing",
"hill-climbing"
] | I was wondering if there are any python AI libraries similar to [aima-python](http://code.google.com/p/aima-python/) ~~but for a more recent version of python...~~ and how they are in comparison to aima-python.
I was particularly interested in search algorithms such as hill-climbing, simulated annealing, tabu search ... | There are a bunch of Python AI libraries, including [PyBrain](http://pybrain.org/), [OpenCV](http://opencv.willowgarage.com/wiki/), [PyML](http://pyml.sourceforge.net/), and [PyEvolve](http://pyevolve.sourceforge.net/). Here are a few useful guides, [one](http://www.depthfirstsearch.net/blog/2008/09/22/opencv-and-pytho... |
Artificial Inteligence library in python | 1,798,091 | 19 | 2009-11-25T16:19:27Z | 1,805,523 | 7 | 2009-11-26T20:29:27Z | [
"python",
"artificial-intelligence",
"genetic-algorithm",
"simulated-annealing",
"hill-climbing"
] | I was wondering if there are any python AI libraries similar to [aima-python](http://code.google.com/p/aima-python/) ~~but for a more recent version of python...~~ and how they are in comparison to aima-python.
I was particularly interested in search algorithms such as hill-climbing, simulated annealing, tabu search ... | [Pyevolve](http://pyevolve.sourceforge.net/) is a Genetic Algorithms/ Genetic programming Python library. |
Artificial Inteligence library in python | 1,798,091 | 19 | 2009-11-25T16:19:27Z | 3,691,321 | 10 | 2010-09-11T14:23:18Z | [
"python",
"artificial-intelligence",
"genetic-algorithm",
"simulated-annealing",
"hill-climbing"
] | I was wondering if there are any python AI libraries similar to [aima-python](http://code.google.com/p/aima-python/) ~~but for a more recent version of python...~~ and how they are in comparison to aima-python.
I was particularly interested in search algorithms such as hill-climbing, simulated annealing, tabu search ... | Although it is not strictly AI, the [scikit-learn](http://scikit-learn.sourceforge.net/) has a lot of machine learning algorithms that can come in handy. Two important details are that it is BSD-licensed, and that it focuses on having fast and numerically-efficient algorithms. |
Overcoming Python's limitations regarding instance methods | 1,798,450 | 8 | 2009-11-25T17:13:40Z | 1,798,869 | 13 | 2009-11-25T18:08:59Z | [
"python",
"oop",
"copy",
"instance-method"
] | It seems that Python has some limitations regarding instance methods.
1. Instance methods can't be copied.
2. Instance methods can't be pickled.
This is problematic for me, because I work on a very object-oriented [project](http://garlicsim.org) in which I reference instance methods, and there's use of both deepcopyi... | You might be able to do this using [`copy_reg.pickle`](http://docs.python.org/library/copy%5Freg.html#copy%5Freg.pickle). In Python 2.6:
```
import copy_reg
import types
def reduce_method(m):
return (getattr, (m.__self__, m.__func__.__name__))
copy_reg.pickle(types.MethodType, reduce_method)
```
This does not s... |
Python Remove last 3 characters of a string | 1,798,465 | 56 | 2009-11-25T17:14:52Z | 1,798,490 | 60 | 2009-11-25T17:17:44Z | [
"python",
"string"
] | I'm trying to remove the last 3 characters from a string in python, I don't know what these characters are so I can't use `rstrip`, I also need to remove any white space and convert to upper-case
an example would be:
```
foo = "Bs12 3ab"
foo.replace(" ", "").rstrip(foo[-3:]).upper()
```
This works and gives me BS12 ... | It doesn't work as you expect because strip is character based. You need to do this instead:
```
foo = foo.replace(' ', '')[:-3].upper()
``` |
Python Remove last 3 characters of a string | 1,798,465 | 56 | 2009-11-25T17:14:52Z | 1,798,537 | 95 | 2009-11-25T17:23:17Z | [
"python",
"string"
] | I'm trying to remove the last 3 characters from a string in python, I don't know what these characters are so I can't use `rstrip`, I also need to remove any white space and convert to upper-case
an example would be:
```
foo = "Bs12 3ab"
foo.replace(" ", "").rstrip(foo[-3:]).upper()
```
This works and gives me BS12 ... | Removing any and all whitespace:
```
foo = ''.join(foo.split())
```
Removing last three characters:
```
foo = foo[:-3]
```
Converting to capital letters:
```
foo = foo.upper()
```
All of that code in one line:
```
foo = ''.join(foo.split())[:-3].upper()
``` |
python : list index out of range error | 1,798,796 | 18 | 2009-11-25T17:57:54Z | 1,798,807 | 33 | 2009-11-25T17:59:39Z | [
"python",
"list"
] | I have written a simple python program
```
l=[1,2,3,0,0,1]
for i in range(0,len(l)):
if l[i]==0:
l.pop(i)
```
This gives me error 'list index out of range' on line `if l[i]==0:`
After debugging I could figure out that `i` is getting incremented and list is getting reduced.
However, I have loop te... | You are reducing the length of your list `l` as you iterate over it, so as you approach the end of your indices in the range statement, some of those indices are no longer valid.
It *looks* like what you want to do is:
```
l = [x for x in l if x != 0]
```
which will return a copy of `l` without any of the elements t... |
python : list index out of range error | 1,798,796 | 18 | 2009-11-25T17:57:54Z | 1,798,825 | 11 | 2009-11-25T18:01:32Z | [
"python",
"list"
] | I have written a simple python program
```
l=[1,2,3,0,0,1]
for i in range(0,len(l)):
if l[i]==0:
l.pop(i)
```
This gives me error 'list index out of range' on line `if l[i]==0:`
After debugging I could figure out that `i` is getting incremented and list is getting reduced.
However, I have loop te... | The expression `len(l)` is evaluated only one time, at the moment the `range()` builtin is evaluated. The range object constructed at that time does not change; it can't possibly know anything about the object `l`.
P.S. `l` is a lousy name for a value! It looks like the numeral 1, or the capital letter I. |
Download file using partial download (HTTP) | 1,798,879 | 20 | 2009-11-25T18:10:02Z | 1,798,945 | 37 | 2009-11-25T18:18:55Z | [
"python",
"http",
"partial"
] | Is there a way to download huge and still growing file over HTTP using the partial-download feature?
It seems that this code downloads file from scratch every time it executed:
```
import urllib
urllib.urlretrieve ("http://www.example.com/huge-growing-file", "huge-growing-file")
```
I'd like:
1. To fetch just the n... | It is possible to do partial download using the range header, the following will request a selected range of bytes:
```
req = urllib2.Request('http://www.python.org/')
req.headers['Range'] = 'bytes=%s-%s' % (start, end)
f = urllib2.urlopen(req)
```
For example:
```
>>> req = urllib2.Request('http://www.python.org/')... |
replace values in an array | 1,800,187 | 12 | 2009-11-25T21:46:50Z | 1,800,214 | 26 | 2009-11-25T21:53:53Z | [
"python",
"numpy"
] | as a replacement value for another within an operation with arrays, or how to search within an array and replace a value by another
for example:
```
array ([[NaN, 1., 1., 1., 1., 1., 1.]
[1., NaN, 1., 1., 1., 1., 1.]
[1., 1., NaN, 1., 1., 1., 1.]
[1., 1., 1., NaN, 1., 1., 1.]
[1., 1., 1., ... | You could do this:
```
import numpy as np
x=np.array([[np.NaN, 1., 1., 1., 1., 1., 1.],[1., np.NaN, 1., 1., 1., 1., 1.],[1., 1., np.NaN, 1., 1., 1., 1.], [1., 1., 1., np.NaN, 1., 1., 1.], [1., 1., 1., 1., np.NaN, 1., 1.],[1., 1., 1., 1., 1., np.NaN, 1.], [1., 1., 1., 1., 1., 1., np.NaN]])
x[np.isnan(x)]=0
```
`np.isn... |
replace values in an array | 1,800,187 | 12 | 2009-11-25T21:46:50Z | 7,796,623 | 14 | 2011-10-17T16:21:49Z | [
"python",
"numpy"
] | as a replacement value for another within an operation with arrays, or how to search within an array and replace a value by another
for example:
```
array ([[NaN, 1., 1., 1., 1., 1., 1.]
[1., NaN, 1., 1., 1., 1., 1.]
[1., 1., NaN, 1., 1., 1., 1.]
[1., 1., 1., NaN, 1., 1., 1.]
[1., 1., 1., ... | these days there is the special function:
```
a = numpy.nan_to_num(a)
``` |
How can I get part of regex match as a variable in python? | 1,800,817 | 7 | 2009-11-26T00:07:14Z | 1,800,858 | 13 | 2009-11-26T00:13:48Z | [
"python",
"regex",
"perl"
] | In Perl it is possible to do something like this (I hope the syntax is right...):
```
$string =~ m/lalala(I want this part)lalala/;
$whatIWant = $1;
```
I want to do the same in Python and get the text inside the parenthesis in a string like $1. | See: [Python regex match objects](https://docs.python.org/2/library/re.html#match-objects)
```
>>> import re
>>> p = re.compile("lalala(I want this part)lalala")
>>> p.match("lalalaI want this partlalala").group(1)
'I want this part'
``` |
How can I get part of regex match as a variable in python? | 1,800,817 | 7 | 2009-11-26T00:07:14Z | 1,800,862 | 7 | 2009-11-26T00:14:59Z | [
"python",
"regex",
"perl"
] | In Perl it is possible to do something like this (I hope the syntax is right...):
```
$string =~ m/lalala(I want this part)lalala/;
$whatIWant = $1;
```
I want to do the same in Python and get the text inside the parenthesis in a string like $1. | ```
import re
astr = 'lalalabeeplalala'
match = re.search('lalala(.*)lalala', astr)
whatIWant = match.group(1) if match else None
print(whatIWant)
```
A small note: in Perl, when you write
```
$string =~ m/lalala(.*)lalala/;
```
the regexp can match anywhere in the string. The equivalent is accomplished with the `re... |
How can I get part of regex match as a variable in python? | 1,800,817 | 7 | 2009-11-26T00:07:14Z | 1,800,907 | 9 | 2009-11-26T00:24:18Z | [
"python",
"regex",
"perl"
] | In Perl it is possible to do something like this (I hope the syntax is right...):
```
$string =~ m/lalala(I want this part)lalala/;
$whatIWant = $1;
```
I want to do the same in Python and get the text inside the parenthesis in a string like $1. | If you want to get parts by name you can also do this:
```
>>> m = re.match(r"(?P<first_name>\w+) (?P<last_name>\w+)", "Malcom Reynolds")
>>> m.groupdict()
{'first_name': 'Malcom', 'last_name': 'Reynolds'}
```
The example was taken from the [re docs](http://docs.python.org/library/re.html#re.MatchObject.groupdict) |
How does wsgi handle multiple request headers with the same name? | 1,801,124 | 10 | 2009-11-26T01:41:31Z | 1,801,191 | 9 | 2009-11-26T02:09:47Z | [
"python",
"http",
"wsgi"
] | In WSGI headers are represented in the environ as 'HTTP\_XXX' values. For example the value `Cookie:` header is stored at the `HTTP_COOKIE` key of the environ.
How are multiple request headers with the same header name represented? | Multiple cookies are combined into a single header, separated by semicolons.
Multiple headers are allowed by [the HTTP spec](http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2), but only for certain kinds of headers, and it is always permissible to combine those headers into one (though using commas, not sem... |
Is smtplib pure python or implemented in C? | 1,801,271 | 5 | 2009-11-26T02:40:31Z | 1,801,282 | 8 | 2009-11-26T02:44:35Z | [
"python",
"c",
"smtplib"
] | Is smtplib pure python or implemented in C? | ```
In [32]: import smtplib
In [33]: smtplib
Out[33]: <module 'smtplib' from '/usr/lib/python2.6/smtplib.pyc'>
```
Therefore, smtplib is written in python. |
django embedding user id into URL template best practice | 1,801,350 | 4 | 2009-11-26T03:14:16Z | 1,801,387 | 9 | 2009-11-26T03:29:53Z | [
"python",
"django"
] | I'm building a navigation menu in my django app, and one of the options is "My Account". There are different roles I have for users, but in order for them all to view their profile, I use a generic URL such as <http://mysite/user/>/profile.
What's a Django best practice for building this url using templates?
Is it si... | Look into named URLs, you can find the official django documentation [here](http://docs.djangoproject.com/en/dev/topics/http/urls/#url).
Basically you can name your URLs in your URL conf as such:
```
url(r'^user/(?P<user_id>\d+)/profile/$', 'yourapp.views.view', name='user_url')
```
And then in any template, you can... |
Algorithm - How to delete duplicate elements in a list efficiently? | 1,801,459 | 9 | 2009-11-26T03:59:32Z | 1,801,471 | 27 | 2009-11-26T04:02:07Z | [
"java",
"c++",
"python",
"algorithm",
"haskell"
] | There is a **list L**. It contains elements of **arbitrary type each**.
How to delete all duplicate elements in such list efficiently? **ORDER must be preserved**
Just an algorithm is required, so no import any external library is allowed.
### Related questions
* [In Python, what is the fastest algorithm for removin... | Assuming order matters:
* Create an empty set S and an empty list M.
* Scan the list L one element at a time.
* If the element is in the set S, skip it.
* Otherwise, add it to M and to S.
* Repeat for all elements in L.
* Return M.
In Python:
```
>>> L = [2, 1, 4, 3, 5, 1, 2, 1, 1, 6, 5]
>>> S = set()
>>> M = []
>>>... |
Algorithm - How to delete duplicate elements in a list efficiently? | 1,801,459 | 9 | 2009-11-26T03:59:32Z | 1,801,475 | 17 | 2009-11-26T04:03:21Z | [
"java",
"c++",
"python",
"algorithm",
"haskell"
] | There is a **list L**. It contains elements of **arbitrary type each**.
How to delete all duplicate elements in such list efficiently? **ORDER must be preserved**
Just an algorithm is required, so no import any external library is allowed.
### Related questions
* [In Python, what is the fastest algorithm for removin... | ## Special Case: Hashing and Equality
Firstly, we need to determine something about the assumptions, namely the existence of an equals and has function relationship. What do I mean by this? I mean that for the set of source objects S, given any two objects x1 and x2 that are elements of S there exists a (hash) functio... |
Algorithm - How to delete duplicate elements in a list efficiently? | 1,801,459 | 9 | 2009-11-26T03:59:32Z | 1,801,477 | 7 | 2009-11-26T04:04:21Z | [
"java",
"c++",
"python",
"algorithm",
"haskell"
] | There is a **list L**. It contains elements of **arbitrary type each**.
How to delete all duplicate elements in such list efficiently? **ORDER must be preserved**
Just an algorithm is required, so no import any external library is allowed.
### Related questions
* [In Python, what is the fastest algorithm for removin... | If the order does not matter, you might want to try this algorithm written in Python:
```
>>> array = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6]
>>> unique = set(array)
>>> list(unique)
[1, 2, 3, 4, 5, 6]
``` |
Algorithm - How to delete duplicate elements in a list efficiently? | 1,801,459 | 9 | 2009-11-26T03:59:32Z | 1,801,575 | 7 | 2009-11-26T04:45:39Z | [
"java",
"c++",
"python",
"algorithm",
"haskell"
] | There is a **list L**. It contains elements of **arbitrary type each**.
How to delete all duplicate elements in such list efficiently? **ORDER must be preserved**
Just an algorithm is required, so no import any external library is allowed.
### Related questions
* [In Python, what is the fastest algorithm for removin... | in haskell this would be covered by the `nub` and `nubBy` functions
```
nub :: Eq a => [a] -> [a]
nub [] = []
nub (x:xs) = x : nub (filter (/= x) xs)
nubBy :: (a -> a -> Bool) -> [a] -> [a]
nubBy f [] = []
nubBy f (x:xs) = x : nub (filter (not.f x) xs)
```
`nubBy` relaxes the dependence on the `Eq` typeclass, instea... |
Convert a Python list with strings all to lowercase or uppercase | 1,801,668 | 85 | 2009-11-26T05:15:52Z | 1,801,676 | 165 | 2009-11-26T05:19:47Z | [
"python",
"list"
] | I have a python list variable that contains strings. Is there a python function that can convert all the strings in one pass to lowercase and vice versa, uppercase? | It can be done with list comprehensions
```
>>> [x.lower() for x in ["A","B","C"]]
['a', 'b', 'c']
>>> [x.upper() for x in ["a","b","c"]]
['A', 'B', 'C']
```
or with map function
```
>>> map(lambda x:x.lower(),["A","B","C"])
['a', 'b', 'c']
>>> map(lambda x:x.upper(),["a","b","c"])
['A', 'B', 'C']
``` |
Convert a Python list with strings all to lowercase or uppercase | 1,801,668 | 85 | 2009-11-26T05:15:52Z | 1,801,683 | 7 | 2009-11-26T05:23:03Z | [
"python",
"list"
] | I have a python list variable that contains strings. Is there a python function that can convert all the strings in one pass to lowercase and vice versa, uppercase? | List comprehensions is how I'd do it. This snippet below shows how to convert a list to all upper case then back to lower:
```
$ python
Python 2.5.2 (r252:60911, Dec 2 2008, 09:26:14)
[GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin
Type "help", "copyright", "credits" or "license" for more informati... |
Convert a Python list with strings all to lowercase or uppercase | 1,801,668 | 85 | 2009-11-26T05:15:52Z | 1,801,690 | 12 | 2009-11-26T05:24:40Z | [
"python",
"list"
] | I have a python list variable that contains strings. Is there a python function that can convert all the strings in one pass to lowercase and vice versa, uppercase? | ```
>>> map(str.lower,["A","B","C"])
['a', 'b', 'c']
``` |
Convert a Python list with strings all to lowercase or uppercase | 1,801,668 | 85 | 2009-11-26T05:15:52Z | 1,801,780 | 30 | 2009-11-26T05:54:36Z | [
"python",
"list"
] | I have a python list variable that contains strings. Is there a python function that can convert all the strings in one pass to lowercase and vice versa, uppercase? | Besides being easier to read (for many people), list comprehensions win the speed race, too:
```
$ python2.6 -m timeit '[x.lower() for x in ["A","B","C"]]'
1000000 loops, best of 3: 1.03 usec per loop
$ python2.6 -m timeit '[x.upper() for x in ["a","b","c"]]'
1000000 loops, best of 3: 1.04 usec per loop
$ python2.6 -... |
The Pythonic way of organizing modules and packages | 1,801,878 | 30 | 2009-11-26T06:28:00Z | 1,801,992 | 30 | 2009-11-26T07:02:23Z | [
"python",
"module",
"package",
"project-organization"
] | I come from a background where I normally create one file per class. I organize common classes under directories as well. This practice is intuitive to me and it has been proven to be effective in C++, PHP, JavaSript, etc.
I am having trouble bringing this metaphor into Python: files are not just files anymore, but th... | Think in terms of a "logical unit of packaging" -- which may be a single class, but more often will be a set of classes that closely cooperate. Classes (or module-level functions -- don't "do Java in Python" by always using static methods when module-level functions are also available as a choice!-) can be grouped base... |
The Pythonic way of organizing modules and packages | 1,801,878 | 30 | 2009-11-26T06:28:00Z | 1,802,001 | 8 | 2009-11-26T07:06:51Z | [
"python",
"module",
"package",
"project-organization"
] | I come from a background where I normally create one file per class. I organize common classes under directories as well. This practice is intuitive to me and it has been proven to be effective in C++, PHP, JavaSript, etc.
I am having trouble bringing this metaphor into Python: files are not just files anymore, but th... | If you are coming from a c++ point of view, you could view python modules akin to a .so or .dll. Yeah they look like source files, because python is scripted, but they are actually loadable libraries of specific functionality.
Another metaphor that may help is you might look python modules as namespaces. |
What is paste script? | 1,802,282 | 16 | 2009-11-26T08:26:37Z | 1,802,440 | 11 | 2009-11-26T09:02:40Z | [
"python",
"paste",
"paster"
] | I'm trying to understand what paste script and paster are. The website is far from clear.
I used paster to generate pre-made layouts for projects, but I don't get the big picture.
As far as I understand, and from the wikipedia entry, it says it's a framework for web frameworks, but that seems reductive. `paster create... | Paste got several components:
* Paste Core: various modules to aid in creating wsgi web apps or frameworks ([module index](http://pythonpaste.org/modindex.html)). Includes stuff like request and response objects. From the web site: "The future of these pieces is to split them into independent packages, and refactor th... |
How to identify whether a variable is a class or an object | 1,802,480 | 3 | 2009-11-26T09:11:14Z | 1,802,533 | 11 | 2009-11-26T09:19:56Z | [
"python"
] | I am working at a bit lower level writing a small framework for creating test fixtures for my project in Python. In this I want to find out whether a particular variable is an instance of a certain class or a class itself and if it is a class, I want to know if it is a subclass of a certain class defined by my framewor... | Use the [inspect module](http://docs.python.org/library/inspect.html#module-inspect).
> The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects. For example, it can help you examine the con... |
NameError: name 'self' is not defined | 1,802,971 | 88 | 2009-11-26T10:47:54Z | 1,802,980 | 84 | 2009-11-26T10:50:14Z | [
"python",
"oop"
] | Why such structure
```
class A:
def __init__(self, a):
self.a = a
def p(self, b=self.a):
print b
```
gives an error `NameError: name 'self' is not defined`? | Default argument values are evaluated at function define-time, but `self` is an argument only available at function call time. Thus arguments in the argument list cannot refer each other.
It's a common pattern to default an argument to `None` and add a test for that in code:
```
def p(self, b=None):
if b is None:... |
NameError: name 'self' is not defined | 1,802,971 | 88 | 2009-11-26T10:47:54Z | 1,804,892 | 11 | 2009-11-26T17:28:10Z | [
"python",
"oop"
] | Why such structure
```
class A:
def __init__(self, a):
self.a = a
def p(self, b=self.a):
print b
```
gives an error `NameError: name 'self' is not defined`? | For cases where you also wish to have the option of setting 'b' to None:
```
def p(self, **kwargs):
b = kwargs.get('b', self.a)
print b
``` |
Initialize project layout in python? | 1,803,292 | 11 | 2009-11-26T12:02:10Z | 1,803,321 | 10 | 2009-11-26T12:07:14Z | [
"python"
] | Suppose a programmer has the following problem: he wants to start a new python project. He needs a basic layout of boilerplate stuff, like test directory, source directory, setuptools script etc.. How does he create all this stuff and layout with a single command ?
For example, paster (as suggested in one of the answe... | You need something that supports templating to pull this off. The most used in the python community is pastescript.
```
easy_install pastescript # A one-time install
paster create
```
If you've already decided on the name of the package, than it's just:
```
paster create mypackage
```
If you want to customize the t... |
Pythonic way to select first variable that evaluates to True | 1,803,302 | 5 | 2009-11-26T12:03:49Z | 1,803,349 | 19 | 2009-11-26T12:14:49Z | [
"python"
] | I have some variables and I want to select the first one that evaluates to True, or else return a default value.
For instance I have `a`, `b`, and `c`. My existing code:
```
result = a if a else (b if b else (c if c else default))
```
Another approach I was considering:
```
result = ([v for v in (a, b, c) if v] + [... | Did you mean returning first value for what `bool(value)==True`? Then you can just rely on the fact that [boolean operators return last evaluated argument](http://docs.python.org/reference/expressions.html#boolean-operations):
```
result = a or b or c or default
``` |
Pythonic way to select first variable that evaluates to True | 1,803,302 | 5 | 2009-11-26T12:03:49Z | 1,803,350 | 17 | 2009-11-26T12:15:03Z | [
"python"
] | I have some variables and I want to select the first one that evaluates to True, or else return a default value.
For instance I have `a`, `b`, and `c`. My existing code:
```
result = a if a else (b if b else (c if c else default))
```
Another approach I was considering:
```
result = ([v for v in (a, b, c) if v] + [... | If one variable is not "defined", you can't access its name. So any reference to 'a' raises a NameError Exception.
In the other hand, if you have something like:
```
a = None
b = None
c = 3
```
you can do
```
default = 1
r = a or b or c or default
# r value is 3
``` |
Python: Can you make this __eq__ easy to understand? | 1,803,710 | 4 | 2009-11-26T13:37:55Z | 1,803,739 | 9 | 2009-11-26T13:42:49Z | [
"python",
"equality"
] | I have another question for you.
I have a python class with a list 'metainfo'. This list contains variable names that my class *might* contain. I wrote a `__eq__` method that returns True if the both `self` and `other` have the same variables from `metainfo` and those variables have the same value.
Here is my impleme... | I would add a docstring which explains what it compares, as you did in your question. |
Python: Can you make this __eq__ easy to understand? | 1,803,710 | 4 | 2009-11-26T13:37:55Z | 1,803,752 | 9 | 2009-11-26T13:45:52Z | [
"python",
"equality"
] | I have another question for you.
I have a python class with a list 'metainfo'. This list contains variable names that my class *might* contain. I wrote a `__eq__` method that returns True if the both `self` and `other` have the same variables from `metainfo` and those variables have the same value.
Here is my impleme... | Use [`getattr`](http://docs.python.org/3.1/library/functions.html#getattr)'s third argument to set distinct default values:
```
def __eq__(self, other):
return all(getattr(self, a, Ellipsis) == getattr(other, a, Ellipsis)
for a in self.metainfo)
```
As the default value, set something that will nev... |
Error codes returned by urllib/urllib2 and the actual page | 1,803,741 | 4 | 2009-11-26T13:43:32Z | 1,803,773 | 7 | 2009-11-26T13:49:57Z | [
"python",
"error-handling"
] | the normal behavior of urllib/urllib2 is if an error code is sent in the header of the response (i.e 404) an Exception is raised.
How do you look for specific errors i.e (40x, or 50x) based on the different errors, do different things. Also, how do you read the actual data being returned HTML/JSON etc (The data usuall... | urllib2 raises a [`HTTPError`](http://docs.python.org/library/urllib2.html#urllib2.HTTPError) when HTTP errors happen. You can get to the response code using `code` on the exception object. You can get the response data using `read()`:
```
>>> req = urllib2.Request('http://www.python.org/fish.html')
>>> try:
>>> u... |
Why is (python|ruby) interpreted? | 1,805,148 | 17 | 2009-11-26T18:47:29Z | 1,805,172 | 31 | 2009-11-26T18:54:11Z | [
"python",
"ruby",
"compiler-construction"
] | What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains. So... | Several reasons:
* faster development loop, *write-test* vs *write-compile-link-test*
* easier to arrange for dynamic behavior (reflection, metaprogramming)
* makes the whole system portable (just recompile the underlying C code and you are good to go on a new platform)
Think of what would happen if the system was *n... |
Why is (python|ruby) interpreted? | 1,805,148 | 17 | 2009-11-26T18:47:29Z | 1,805,243 | 15 | 2009-11-26T19:09:53Z | [
"python",
"ruby",
"compiler-construction"
] | What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains. So... | Exactly like (in the typical implementation of) Java or C#, Python gets first compiled into some form of bytecode, depending on the implementation (CPython uses a specialized form of its own, Jython uses JVM just like a typical Java, IronPython uses CLR just like a typical C#, and so forth) -- that bytecode then gets f... |
Why is (python|ruby) interpreted? | 1,805,148 | 17 | 2009-11-26T18:47:29Z | 1,805,899 | 8 | 2009-11-26T22:16:13Z | [
"python",
"ruby",
"compiler-construction"
] | What are the technical reasons why languages like Python and Ruby are interpreted (out of the box) instead of compiled? It seems to me like it should not be too hard for people knowledgeable in this domain to make these languages not be interpreted like they are today, and we would see significant performance gains. So... | Merely replacing an interpreter with a compiler won't give you as big a performance boost as you might think for a language like Python. When most time is actually spend doing symbolic lookups of object members in dictionaries, it doesn't really matter if the call to the function performing such lookup is interpreted, ... |
How would you represent a MineSweeper grid in Python? | 1,805,480 | 3 | 2009-11-26T20:17:31Z | 1,805,540 | 8 | 2009-11-26T20:35:31Z | [
"python",
"data-structures"
] | What datastructure would you use in Python to represent the internal state of a MineSweeper grid?
Each x,y position will hold a numerical value which represents its current cell state (unexplored, mine, flag, ?).
Should I use nested lists? This seems like the closest thing to a 2D array and it is what I would probabl... | Use a nested list. It's easy to set up:
```
field = [([None] * height) for x in range(width)]
field[x][y] = "*"
```
The clearest thing would probably be a new class:
```
class MineField(object):
class _SingleField(object):
mine = False
flagged = False
covered = True
width = None
... |
How can I use SQLITE with DJANGO on WIndows 7 | 1,805,852 | 2 | 2009-11-26T21:57:31Z | 1,805,904 | 9 | 2009-11-26T22:17:36Z | [
"python",
"windows",
"django",
"sqlite",
"windows-7"
] | I am following the tutorial on the DJango site, which I previsouly did using Windows XP and everything went fine, but on Windows 7 I get the following error:
```
sqlite3.OperationalError: unable to open database file
```
I use the following:
```
python manage.py sql Blog
```
Does any one have any ideas what might b... | I know this question has already an accepted answer, but I think you missed something. You should use raw strings when your strings contain backslashes:
```
DATABASE_NAME = r'C:\Software\Sqlite\databases\blog.db'
```
This is what happens if you don't use a raw string:
```
>>> print 'C:\Software\Sqlite\databases\blog... |
Python asynchronous callbacks and generators | 1,805,958 | 10 | 2009-11-26T22:32:10Z | 1,985,400 | 10 | 2009-12-31T13:27:09Z | [
"python",
"asynchronous",
"generator"
] | I'm trying to convert a synchronous library to use an internal asynchronous IO framework. I have several methods that look like this:
```
def foo:
....
sync_call_1() # synchronous blocking call
....
sync_call_2() # synchronous blocking call
....
return bar
```
For each of the synchronous functions (`s... | **UPDATE**: take this with a grain of salt, as I'm out of touch with modern python async developments, including [gevent](http://www.gevent.org/) and [asyncio](https://www.python.org/dev/peps/pep-3156/) and don't actually have serious experience with async code.
---
There are 3 common approaches to thread-less async ... |
Calculate percent at runtime | 1,806,143 | 6 | 2009-11-26T23:40:58Z | 1,806,166 | 17 | 2009-11-26T23:50:21Z | [
"c#",
"java",
"python",
"algorithm",
"language-agnostic"
] | I have this problem where I have to "audit" a percent of my transtactions.
If percent is 100 I have to audit them all, if is 0 I have to skip them all and if 50% I have to review the half etc.
The problem ( or the opportunity ) is that I have to perform the check at runtime.
What I tried was:
```
audit = 100/percen... | Why not do it randomly. For each transaction, pick a random number between 0 and 100. If that number is less than your "percent", then audit the transaction. If the number is greater than your "percent", then don't. I don't know if this satisfies your requirements, but over an extended period of time, you will have the... |
Scrapy BaseSpider: How does it work? | 1,806,235 | 5 | 2009-11-27T00:15:37Z | 1,807,439 | 16 | 2009-11-27T08:35:34Z | [
"python",
"web-crawler",
"scrapy"
] | This is the BaseSpider example from the Scrapy tutorial:
```
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from dmoz.items import DmozItem
class DmozSpider(BaseSpider):
domain_name = "dmoz.org"
start_urls = [
"http://www.dmoz.org/Computers/Programming/Languages/Pytho... | Probably you meant `item = FirmItem()` instead of `item = FirmItem`? |
mechanize python click a button | 1,806,238 | 12 | 2009-11-27T00:16:30Z | 1,806,266 | 21 | 2009-11-27T00:30:53Z | [
"python",
"button",
"mechanize"
] | I have a form with `<input type="button" name="submit" />` button and would like to be able to click it.
I have tried `mech.form.click("submit")` but that gives the following error:
`ControlNotFoundError: no control matching kind 'clickable', id 'submit'`
`mech.submit()` also doesn't work since its type is button an... | clicking a `type="button"` in a **pure html** form does nothing. For it to do anything, there must be *javascript* involved.
And `mechanize` doesn't run *javascript*.
So your options are:
* Read the javascript yourself and simulate with `mechanize` what it would be doing
* Use [`spidermonkey`](http://pypi.python.org... |
Convert fraction to float? | 1,806,278 | 10 | 2009-11-27T00:36:10Z | 1,806,309 | 21 | 2009-11-27T00:50:46Z | [
"python",
"parsing"
] | Kind of [like this question](http://stackoverflow.com/questions/95727/how-to-convert-floats-to-human-readable-fractions), but in reverse.
Given a string like `1`, `1/2`, or `1 2/3`, what's the best way to convert it into a float? I'm thinking about using regexes on a case-by-case basis, but perhaps someone knows of a ... | maybe something like this (2.6+)
```
from fractions import Fraction
float(sum(Fraction(s) for s in '1 2/3'.split()))
``` |
Navigation menu using Django templates | 1,806,472 | 5 | 2009-11-27T02:11:22Z | 1,806,532 | 7 | 2009-11-27T02:43:48Z | [
"python",
"django"
] | Trying to work with a trivial navigation menu using django templates, I'm having trouble setting the current class on a particular menu item. Here's my base template:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.or... | I don't think you can replace a block from an included template. My suggestion is that you need to rethink the logic of your templates. IMHO it should be something like this:
base.html
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmln... |
Initialize a list of objects in Python | 1,807,026 | 7 | 2009-11-27T06:05:17Z | 1,807,043 | 18 | 2009-11-27T06:10:10Z | [
"python",
"arrays",
"list",
"initialization"
] | I'm a looking to initialize an array/list of objects that are not empty -- the class constructor generates data. In C++ and Java I would do something like this:
```
Object lst = new Object[100];
```
I've dug around, but is there a Pythonic way to get this done?
This doesn't work like I thought it would (I get 100 re... | There isn't a way to implicitly call an `Object()` constructor for each element of an array like there is in C++ (recall that in Java, each element of a new array is initialised to `null` for reference types).
I would say that your list comprehension method is the most Pythonic:
```
lst = [Object() for i in range(100... |
Initialize a list of objects in Python | 1,807,026 | 7 | 2009-11-27T06:05:17Z | 1,807,374 | 9 | 2009-11-27T08:15:59Z | [
"python",
"arrays",
"list",
"initialization"
] | I'm a looking to initialize an array/list of objects that are not empty -- the class constructor generates data. In C++ and Java I would do something like this:
```
Object lst = new Object[100];
```
I've dug around, but is there a Pythonic way to get this done?
This doesn't work like I thought it would (I get 100 re... | You should note that Python's equvalent for Java code
(creating array of 100 **null** references to Object):
```
Object arr = new Object[100];
```
or C++ code:
```
Object **arr = new Object*[100];
```
is:
```
arr = [None]*100
```
not:
```
arr = [Object() for _ in range(100)]
```
The second would be the same as ... |
Open a second window in PyQt | 1,807,299 | 6 | 2009-11-27T07:50:08Z | 2,371,959 | 12 | 2010-03-03T14:18:07Z | [
"python",
"dialog",
"pyqt"
] | I'm trying to use pyqt to show a custom QDialog window when a button on a QMainWindow is clicked. I keep getting the following error:
```
$ python main.py
DEBUG: Launch edit window
Traceback (most recent call last):
File "/home/james/Dropbox/Database/qt/ui_med.py", line 23, in launchEditWindow
dialog = Ui_Dialo... | I've done like this in the past, and i can tell it works.
assuming your button is called "Button"
```
class Main(QtGui.QMainWindow):
''' some stuff '''
def on_Button_clicked(self, checked=None):
if checked==None: return
dialog = QDialog()
dialog.ui = Ui_MyDialog()
dialog.ui.setu... |
Running twistd as root, modules aren't found | 1,807,484 | 4 | 2009-11-27T08:45:17Z | 1,810,060 | 7 | 2009-11-27T18:14:54Z | [
"python",
"twisted"
] | I have a simple web server written in Twisted, and I'm trying to start it up daemonized with **twistd**. Everything works fine with `reactor.run()` but when I use `twistd -y` (as root), none of my packages which are in direct child directories get found. I'm running twistd as root, since the server runs on port 80. The... | General UNIX wisdom is that searching the working directory for things to execute when root is a bad idea. The argument goes that it opens the door to trojans. In not going out of its way to add the working directory to the Python module import search path when running as root, twistd is basically trying to follow this... |
How to efficiently use MySQLDB SScursor? | 1,808,150 | 21 | 2009-11-27T11:12:38Z | 1,808,414 | 23 | 2009-11-27T12:13:11Z | [
"python",
"mysql",
"optimization",
"cursor"
] | I have to deal with a large result set (could be hundreds thousands of rows, sometimes more).
They unfortunately need to be retrieved all at once (on start up).
I'm trying to do that by using as less memory as possible.
By looking on SO I've found that using `SSCursor` might be what I'm looking for, but I still do... | I am in agreement with Otto Allmendinger's answer, but to make explicit Denis Otkidach's comment, here is how you can iterate over the results without using Otto's fetch() function:
```
import MySQLdb.cursors
connection=MySQLdb.connect(
host="thehost",user="theuser",
passwd="thepassword",db="thedb",
cursor... |
Python doctest: Skip entire block? | 1,809,037 | 7 | 2009-11-27T14:17:13Z | 7,622,355 | 8 | 2011-10-01T19:09:20Z | [
"python",
"doctest"
] | I've got a Python module with docstrings in class methods, and a real-world example in the module docstring. The distinction is that the method-docstrings have been carefully crafted to be utterly repeatable tests, while the real-world example is just a copy'n'paste of the history from a Linux shell - which happened to... | Wrap the example in a function and then skip the function call:
```
"""
>>> def example():
>>> from packagename import module
>>> module.show_real_world_usage()
>>> example() # doctest: +SKIP
'Hello world!'
"""
``` |
Truncating unicode so it fits a maximum size when encoded for wire transfer | 1,809,531 | 22 | 2009-11-27T16:04:58Z | 1,809,570 | 8 | 2009-11-27T16:12:30Z | [
"python",
"json",
"unicode",
"truncate"
] | Given a Unicode string and these requirements:
* The string be encoded into some byte-sequence format (e.g. UTF-8 or JSON unicode escape)
* The encoded string has a maximum length
For example, the iPhone push service requires JSON encoding with a maximum total packet size of 256 bytes.
**What is the best way to trun... | One of UTF-8's properties is that it is easy to resync, that is find the unicode character boundaries easily in the encoded bytestream. All you need to do is to cut the encoded string at max length, then walk backwards from the end removing any bytes that are > 127 -- those are part of, or the start of a multibyte char... |
Truncating unicode so it fits a maximum size when encoded for wire transfer | 1,809,531 | 22 | 2009-11-27T16:04:58Z | 1,820,949 | 19 | 2009-11-30T16:45:24Z | [
"python",
"json",
"unicode",
"truncate"
] | Given a Unicode string and these requirements:
* The string be encoded into some byte-sequence format (e.g. UTF-8 or JSON unicode escape)
* The encoded string has a maximum length
For example, the iPhone push service requires JSON encoding with a maximum total packet size of 256 bytes.
**What is the best way to trun... | ```
def unicode_truncate(s, length, encoding='utf-8'):
encoded = s.encode(encoding)[:length]
return encoded.decode(encoding, 'ignore')
```
Here is an example for unicode string where each character is represented with 2 bytes in UTF-8:
```
>>> unicode_truncate(u'абвгд', 5)
u'\u0430\u0431'
``` |
Why say x = x in Python? | 1,809,805 | 4 | 2009-11-27T17:09:05Z | 1,809,824 | 14 | 2009-11-27T17:13:34Z | [
"python",
"identity",
"equals"
] | In [this file](http://matplotlib.svn.sourceforge.net/viewvc/matplotlib/trunk/matplotlib/lib/matplotlib/mlab.py?revision=6648&view=markup&pathrev=6648), in the function `cross_from_below(x, threshold)`, there is a line that says `threshold = threshold`. What's the point of this line? Does this do something differently t... | There is no point to that assignment. It's probably just left over and should be removed. The next function is nearly identical, and doesn't have it. |
Why say x = x in Python? | 1,809,805 | 4 | 2009-11-27T17:09:05Z | 1,809,832 | 8 | 2009-11-27T17:16:12Z | [
"python",
"identity",
"equals"
] | In [this file](http://matplotlib.svn.sourceforge.net/viewvc/matplotlib/trunk/matplotlib/lib/matplotlib/mlab.py?revision=6648&view=markup&pathrev=6648), in the function `cross_from_below(x, threshold)`, there is a line that says `threshold = threshold`. What's the point of this line? Does this do something differently t... | No, in the specific example you quote, that line is (harmless but) redundant -- indeed the very next function (cross threshold from above rather than from below) is almost identical (save of course for the direction of the comparisons), lacks that extra assignment, yet works just the same way.
The one and only case wh... |
Scrapy SgmlLinkExtractor question | 1,809,817 | 8 | 2009-11-27T17:12:10Z | 1,818,537 | 9 | 2009-11-30T08:33:50Z | [
"python",
"web-crawler",
"scrapy"
] | I am trying to make the SgmlLinkExtractor to work.
This is the signature:
```
SgmlLinkExtractor(allow=(), deny=(), allow_domains=(), deny_domains=(), restrict_xpaths(), tags=('a', 'area'), attrs=('href'), canonicalize=True, unique=True, process_value=None)
```
I am just using `allow=()`
So, I enter
```
rules = (Ru... | You are overriding the "parse" method it appears. "parse", is a private method in CrawlSpider used to follow links. |
Hide stderr output in unit tests | 1,809,958 | 12 | 2009-11-27T17:47:10Z | 1,809,963 | 12 | 2009-11-27T17:49:56Z | [
"python",
"unit-testing"
] | I'm writing a few unit tests of some code which uses sys.stderr.write to report errors in input. This is as it should be, but this clobbers the unit test output. Is there any way to tell Python to not output error messages for single commands, Ã la `2> /dev/null`? | You could create a dummy file object that did nothing with its output, and set stderr to that:
```
class NullWriter:
def write(self, s):
pass
sys.stderr = NullWriter()
```
If you only want to quiet stderr for a specific duration, you can use a `with` statement like so:
```
class Quieter:
def __enter... |
Hide stderr output in unit tests | 1,809,958 | 12 | 2009-11-27T17:47:10Z | 1,810,086 | 21 | 2009-11-27T18:20:45Z | [
"python",
"unit-testing"
] | I'm writing a few unit tests of some code which uses sys.stderr.write to report errors in input. This is as it should be, but this clobbers the unit test output. Is there any way to tell Python to not output error messages for single commands, Ã la `2> /dev/null`? | I suggest writing a context manager:
```
import contextlib
import sys
@contextlib.contextmanager
def nostderr():
savestderr = sys.stderr
class Devnull(object):
def write(self, _): pass
def flush(self): pass
sys.stderr = Devnull()
try:
yield
finally:
sys.stderr = sav... |
Parsing a string which represents a list of tuples | 1,810,109 | 11 | 2009-11-27T18:25:46Z | 1,810,121 | 19 | 2009-11-27T18:29:06Z | [
"python",
"data-structures",
"string",
"eval",
"tuples"
] | I have strings which look like this one:
```
"(8, 12.25), (13, 15), (16.75, 18.5)"
```
and I would like to convert each of them into a python data structure. Preferably a list (or tuple) of tuples containing a pair of float values.
I could do that with `eval("(8, 12.25), (13, 15), (16.75, 18.5)")` which gives me a t... | ```
>>> import ast
>>> print ast.literal_eval("(8, 12.25), (13, 15), (16.75, 18.5)")
((8, 12.25), (13, 15), (16.75, 18.5))
``` |
Handling the different results from parsedatetime | 1,810,432 | 3 | 2009-11-27T19:52:20Z | 5,903,760 | 15 | 2011-05-05T20:36:23Z | [
"python"
] | I'm trying to learn python after spending the last 15 or so years working only in Perl and only occasionally.
I can't understand how to handle the two different kinds of results from the parse method of Calendar.parse() from parsedatetime
Given this script:
```
#!/usr/bin/python
import parsedatetime.parsedatetime a... | I know this is an old question but I ran into this yesterday and the answer here is incomplete (it will fail in the case that parse() returns a datetime).
From the parsedatetime docs:
parse() returns a tuple ( result, type ) where type specifies one of:
```
0 = not parsed at all
1 = parsed as a date (of type s... |
How to set the current working directory in Python? | 1,810,743 | 201 | 2009-11-27T21:53:48Z | 1,810,760 | 274 | 2009-11-27T21:59:59Z | [
"python",
"current-working-directory"
] | How to set the current working directory in Python? | Try [`os.chdir`](http://docs.python.org/library/os.html#os.chdir)
> ```
> os.chdir(path)
> ```
>
> Â Â Â Â Â Â Â Â Change the current working directory to path. Availability: Unix, Windows. |
How to set the current working directory in Python? | 1,810,743 | 201 | 2009-11-27T21:53:48Z | 1,810,762 | 67 | 2009-11-27T22:00:09Z | [
"python",
"current-working-directory"
] | How to set the current working directory in Python? | Perhaps this is what you are looking for:
```
import os
os.chdir(default_path)
``` |
Django: How to filter User's that belong to a specific group | 1,810,891 | 21 | 2009-11-27T22:51:30Z | 1,810,985 | 31 | 2009-11-27T23:26:38Z | [
"python",
"django"
] | I'm looking to narrow a query set for a form field that has a foreignkey to the User's table down to the group that a user belongs to.
The groups have been previously associated by me. The model might have something like the following:
```
myuser = models.ForeignKey(User)
```
And my ModelForm is very bare bones:... | You'll want to use [Django's convention for joining across relationships](http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships) to join to the group table in your query set.
Firstly, I recommend giving your relationship a `related_name`. This makes the code more readable than what Dj... |
Standard library - higher-precision floating point? | 1,811,010 | 4 | 2009-11-27T23:37:42Z | 1,811,026 | 8 | 2009-11-27T23:45:27Z | [
"python",
"floating-point"
] | So, I'm having some precision issues in Python.
I would like to calculate functions like this:
```
P(x,y) = exp(-x)/(exp(-x) + exp(-y))
```
Where x and y might be >1000. Python's math.exp(-1000) (in 2.6 at least!) doesn't have enough floating point precision to handle this.
1. this form looks like logistic / logit ... | you could divide the top and bottom by `exp(-x)`
```
P(x,y) = 1/(1 + exp(x-y))
``` |
Standard library - higher-precision floating point? | 1,811,010 | 4 | 2009-11-27T23:37:42Z | 1,811,052 | 8 | 2009-11-27T23:57:18Z | [
"python",
"floating-point"
] | So, I'm having some precision issues in Python.
I would like to calculate functions like this:
```
P(x,y) = exp(-x)/(exp(-x) + exp(-y))
```
Where x and y might be >1000. Python's math.exp(-1000) (in 2.6 at least!) doesn't have enough floating point precision to handle this.
1. this form looks like logistic / logit ... | ```
>>> import decimal
>>> decimal.Decimal(-1000).exp()
Decimal('5.075958897549456765291809480E-435')
>>> decimal.getcontext().prec = 60
>>> decimal.Decimal(-1000).exp()
Decimal('5.07595889754945676529180947957433691930559928289283736183239E-435')
``` |
How can I track python imports | 1,811,095 | 16 | 2009-11-28T00:15:35Z | 1,811,099 | 8 | 2009-11-28T00:19:32Z | [
"python",
"import"
] | I have cyclical import issues adding some new code to a very large app, and I'm trying to determine which files are the most likely causes for this. It there any way to track which files import which files? I did a bit of looking and found the python trace command, but it's just showing a bunch of activity in the main ... | Try using `python -v` to run your program. It will trace the sequence of imports.
Another option is [pylint](http://pypi.python.org/pypi/pylint), which will alert you to all sorts of issues, including cyclic imports. |
How can I track python imports | 1,811,095 | 16 | 2009-11-28T00:15:35Z | 1,811,161 | 10 | 2009-11-28T00:43:35Z | [
"python",
"import"
] | I have cyclical import issues adding some new code to a very large app, and I'm trying to determine which files are the most likely causes for this. It there any way to track which files import which files? I did a bit of looking and found the python trace command, but it's just showing a bunch of activity in the main ... | You could use one of these scripts to make python module dependency graphs:
* <http://furius.ca/snakefood/>
* <http://www.tarind.com/depgraph.html>
* <http://code.activestate.com/recipes/535136/> |
How can I track python imports | 1,811,095 | 16 | 2009-11-28T00:15:35Z | 1,811,165 | 13 | 2009-11-28T00:45:33Z | [
"python",
"import"
] | I have cyclical import issues adding some new code to a very large app, and I'm trying to determine which files are the most likely causes for this. It there any way to track which files import which files? I did a bit of looking and found the python trace command, but it's just showing a bunch of activity in the main ... | Here's a simple (and slightly rudimentary;-) way to trace "who's trying to import what" in terms of module names:
```
import inspect
import __builtin__
savimp = __builtin__.__import__
def newimp(name, *x):
caller = inspect.currentframe().f_back
print name, caller.f_globals.get('__name__')
return savimp(name, *x... |
Scrapy SgmlLinkExtractor is ignoring allowed links | 1,811,132 | 10 | 2009-11-28T00:34:23Z | 2,074,821 | 11 | 2010-01-15T21:12:54Z | [
"python",
"web-crawler",
"scrapy"
] | Please take a look at [this spider example](http://doc.scrapy.org/topics/spiders.html#crawlspider-example) in Scrapy documentation. The explanation is:
> This spider would start crawling example.comâs home page, collecting category links, and item links, parsing the latter with the parse\_item method. For each item ... | The `parse` function is actually implemented and used in the CrawlSpider class, and you're unintentionally overriding it. If you change the name to something else, like `parse_item`, then the Rule should work. |
Why does my python script randomly get killed? | 1,811,173 | 11 | 2009-11-28T00:47:23Z | 1,811,200 | 16 | 2009-11-28T00:58:11Z | [
"python",
"mysql",
"url"
] | Basically, i have a list of 30,000 URLs.
The script goes through the URLs and downloads them (with a 3 second delay in between).
And then it stores the HTML in a database.
And it loops and loops...
Why does it randomly get "Killed."? I didn't touch anything.
Edit: this happens on 3 of my linux machines.
The machines... | Looks like you might be running out of memory -- might easily happen on a long-running program if you have a "leak" (e.g., due to accumulating circular references). Does Rackspace offer any easily usable tools to keep track of a process's memory, so you can confirm if this is the case? Otherwise, this kind of thing is ... |
Why does my python script randomly get killed? | 1,811,173 | 11 | 2009-11-28T00:47:23Z | 1,811,219 | 9 | 2009-11-28T01:11:42Z | [
"python",
"mysql",
"url"
] | Basically, i have a list of 30,000 URLs.
The script goes through the URLs and downloads them (with a 3 second delay in between).
And then it stores the HTML in a database.
And it loops and loops...
Why does it randomly get "Killed."? I didn't touch anything.
Edit: this happens on 3 of my linux machines.
The machines... | In cases like this, you should check the log files.
I use Debian and Ubuntu, so the main log file for me is: `/var/log/syslog`
If you use Red Hat, I think that log is: `/var/log/messages`
If something happens that is as exceptional as the kernel killing your process, there *will* be a log event explaining it.
I sus... |
running an outside program (executable) in python? | 1,811,691 | 30 | 2009-11-28T05:36:50Z | 1,811,745 | 18 | 2009-11-28T06:08:35Z | [
"python",
"executable"
] | I just started working on python and I have been trying to run an outside executable form python.
I have an executable for a program written in Fortran. Lets say the name for the executable is flow.exe. And my executable is lacated in C:\Documents and Settings\flow\_model
I tried both os.system and popen commands but s... | Those whitespaces can really be a bother:-(. Try `os.chdir('C:/Documents\ and\ Settings/')` followed by relative paths for `os.system`, `subprocess` methods, or whatever...
If best-effort attempts to bypass the whitespaces-in-path hurdle keep failing, then my next best suggestion is to **avoid** having blanks in your ... |
running an outside program (executable) in python? | 1,811,691 | 30 | 2009-11-28T05:36:50Z | 1,812,050 | 10 | 2009-11-28T09:08:45Z | [
"python",
"executable"
] | I just started working on python and I have been trying to run an outside executable form python.
I have an executable for a program written in Fortran. Lets say the name for the executable is flow.exe. And my executable is lacated in C:\Documents and Settings\flow\_model
I tried both os.system and popen commands but s... | your usage is correct, i bet that your external program, flow.exe, needs to be executed in its directory because it accesses some external files stored there.
so you might try:
```
import sys, string, os, arcgisscripting
os.chdir( 'c:\\documents and settings\\flow_model' )
os.system( '"C:\\Documents and Settings\\flo... |
running an outside program (executable) in python? | 1,811,691 | 30 | 2009-11-28T05:36:50Z | 13,296,949 | 15 | 2012-11-08T20:09:48Z | [
"python",
"executable"
] | I just started working on python and I have been trying to run an outside executable form python.
I have an executable for a program written in Fortran. Lets say the name for the executable is flow.exe. And my executable is lacated in C:\Documents and Settings\flow\_model
I tried both os.system and popen commands but s... | If Using Python 2.7 or higher you can use the following:
```
import subprocess
```
* `subprocess.call(args, *, stdin=None, stdout=None, stderr=None, shell=False)`
Runs the command described by args. Waits for command to complete, then returns the returncode attribute.
* `subprocess.check_call(args, *, stdin=None, s... |
Is it possible to unpack a tuple without using variables? | 1,812,020 | 10 | 2009-11-28T08:54:12Z | 1,812,030 | 14 | 2009-11-28T09:00:00Z | [
"python",
"tuples",
"iterable-unpacking"
] | I'm using the os.path.split() function on a path in my program to get the filename and pathname of a file then passing them into another method, but my current solution seems rather ugly:
```
path = os.path.split(somefile)
some_class(path[0], path[1])
```
Is it possible to unpack the path tuple in a cleaner way withi... | Yes, Python has [argument list unpacking](http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists). Try this:
```
some_class(*os.path.split(somefile))
``` |
How to safely write to a file? | 1,812,115 | 14 | 2009-11-28T09:46:38Z | 1,812,421 | 11 | 2009-11-28T12:28:01Z | [
"python",
"windows",
"file"
] | Imagine you have a library for working with some sort of XML file or configuration file. The library reads the whole file into memory and provides methods for editing the content. When you are done manipulating the content you can call a `write` to save the content back to file. The question is how to do this in a safe... | If you want to be POSIXly correct and save you have to:
1. Write to temporary file
2. Flush and [`fsync`](http://docs.python.org/library/os.html#os.fsync) the file (or `fdatasync`)
3. Rename over the original file
Note that calling fsync has unpredictable effects on performance -- Linux on ext3 may stall for disk I/O... |
How to safely write to a file? | 1,812,115 | 14 | 2009-11-28T09:46:38Z | 1,812,604 | 13 | 2009-11-28T14:18:28Z | [
"python",
"windows",
"file"
] | Imagine you have a library for working with some sort of XML file or configuration file. The library reads the whole file into memory and provides methods for editing the content. When you are done manipulating the content you can call a `write` to save the content back to file. The question is how to do this in a safe... | If you see Python's documentation, it clearly mentions that os.rename() is an atomic operation. So in your case, writing data to a temporary file and then renaming it to the original file would be quite safe.
Another way could work like this:
* let original file be abc.xml
* create abc.xml.tmp and write new data to i... |
Making a Python script Object-Oriented | 1,813,117 | 15 | 2009-11-28T17:19:36Z | 1,813,167 | 39 | 2009-11-28T17:36:11Z | [
"python",
"oop"
] | I'm writing an application in Python that is going to have a lot of different functions, so logically I thought it would be best to split up my script into different modules. Currently my script reads in a text file that contains code which has been converted into tokens and spellings. The script then reconstructs the ... | To speed up your existing code measurably, add `def main():` before the assignment to `tokenList`, indent everything after that 4 spaces, and at the end put the usual idiom
```
if __name__ == '__main__':
main()
```
(The guard is not actually necessary, but it's a good habit to have nevertheless since, for scripts w... |
Python: execfile from other file's working directory? | 1,813,282 | 7 | 2009-11-28T18:22:46Z | 1,813,338 | 7 | 2009-11-28T18:40:42Z | [
"python",
"working-directory",
"execfile"
] | I have some code that loads a default configuration file and then allows users to supply their own Python files as additional supplemental configuration or overrides of the defaults:
```
# foo.py
def load(cfg_path=None):
# load default configuration
exec(default_config)
# load user-specific configuration... | [os.chdir](http://docs.python.org/library/os.html?highlight=os#os.chdir) lets you change the working directory as you wish (you can extract the working directory of `cfg_path` with `os.path.dirname`); be sure to first get the current directory with [os.getcwd](http://docs.python.org/library/os.html?highlight=os#os.getc... |
Why should I use WSGI? | 1,813,394 | 12 | 2009-11-28T18:54:51Z | 1,813,470 | 7 | 2009-11-28T19:15:41Z | [
"python",
"wsgi"
] | Been using mod\_python for a while, I read more and more articles about how good WSGI is, without really understanding why.
So why should I switch to it? What are the benefits? Is it hard, and is the learning curve worth it? | For developing sophisticated web applications in Python, you would probably use a more comprehensive web development framework like DJango, Zope, Turbogears etc. As an application developer, you don't have to worry about WSGI much. All you have to be aware about is that these frameworks support WSGI. The WSGI allows se... |
Why should I use WSGI? | 1,813,394 | 12 | 2009-11-28T18:54:51Z | 1,813,471 | 9 | 2009-11-28T19:16:34Z | [
"python",
"wsgi"
] | Been using mod\_python for a while, I read more and more articles about how good WSGI is, without really understanding why.
So why should I switch to it? What are the benefits? Is it hard, and is the learning curve worth it? | mod\_wsgi vs. mod\_python:
* mod\_wsgi is a little faster (internally there's more C, less Python)
* mod\_wsgi processes can be isolated from Apache, which improves security/stability with lower memory use[1]
* mod\_python gives you access to some of Apache's internals
WSGI in general:
* lots of reusable middleware ... |
Django, how to generate an admin panel without models? | 1,813,637 | 4 | 2009-11-28T20:08:02Z | 1,813,797 | 7 | 2009-11-28T21:11:35Z | [
"python",
"django",
"django-admin",
"ice"
] | I'm building a rather large project, that basically consists of this:
Server 1:
Ice based services.
Glacier2 for session handling.
Firewall allowing access to Glacier2.
Server 2:
Web interface (read, public) for Ice services via Glacier2.
Admin interface for Ice services via Glacier 2.
The point I'm concerned with i... | I think there might be a simpler way than writing custom ORMS to get the admin integration you want. I used it in an app that allows managing Webfaction email accounts via their Control Panel API.
Take a look at models.py, admin.py and urls.py here: [django-webfaction](http://code.google.com/p/django-webfaction/)
To ... |
How to deal with "None" DB values in Django queries | 1,813,653 | 6 | 2009-11-28T20:13:00Z | 1,813,768 | 8 | 2009-11-28T20:59:16Z | [
"python",
"django"
] | I have the following filter query which is doing an SQL OR statement:
```
results = Stores.objects.filter(Q(title__icontains=prefs.address1) | Q(title__icontains=prefs.address2))
```
This works fine but if the prefs.address1 and prefs.address2 values (which come from another model) are blank in mySQL, Django complain... | You could do this which is easily generalisable to more queries
```
query = Q()
for search in (prefs.address1, prefs.address2):
if search:
query |= Q(title__icontains=search)
results = Stores.objects.filter(query)
``` |
Intersection between bezier curve and a line segment | 1,813,719 | 13 | 2009-11-28T20:34:11Z | 1,813,744 | 7 | 2009-11-28T20:45:51Z | [
"python",
"math",
"geometry",
"pygame",
"spline"
] | I am writing a game in Python (with pygame) that requires me to generate random but nice-looking "sea" for each new game. After a long search I settled on an algorithm that involves Bezier curves as defined in [padlib.py](http://www.pygame.org/project-Pygame+Advance+Graphics+Library-660-.html). I now need to figure out... | As a rough outline, rotate and translate the system so that the line segment lies on the X axis. Now the y coordinate is a cubic function of the parameter t. Find the 'zeros' (the analytic formulae will be found in good math texts or wikipedia). Now evaluate the x coordinates corresponding to those zero points and test... |
Running a process in pythonw with Popen without a console | 1,813,872 | 9 | 2009-11-28T21:50:26Z | 1,813,893 | 17 | 2009-11-28T21:58:35Z | [
"python",
"user-interface",
"console",
"popen",
"pythonw"
] | I have a program with a GUI that runs an external program through a Popen call:
```
p = subprocess.Popen("<commands>" , stdout=subprocess.PIPE , stderr=subprocess.PIPE , cwd=os.getcwd())
p.communicate()
```
But a console pops up, regardless of what I do (I've also tried passing it NUL for the file handle). Is there a... | From [here](http://code.activestate.com/recipes/409002/):
```
import subprocess
def launchWithoutConsole(command, args):
"""Launches 'command' windowless and waits until finished"""
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
return subprocess.Popen([c... |
Simple way to convert a string to a dictionary | 1,814,400 | 6 | 2009-11-29T02:03:17Z | 1,814,489 | 9 | 2009-11-29T02:49:37Z | [
"python",
"string",
"dictionary"
] | What is the simplest way to convert a string of keyword=values to a dictionary, for example the following string:
```
name="John Smith", age=34, height=173.2, location="US", avatar=":,=)"
```
to the following python dictionary:
```
{'name':'John Smith', 'age':34, 'height':173.2, 'location':'US', 'avatar':':,=)'}
```... | This works for me:
```
# get all the items
matches = re.findall(r'\w+=".+?"', s) + re.findall(r'\w+=[\d.]+',s)
# partition each match at '='
matches = [m.group().split('=', 1) for m in matches]
# use results to make a dict
d = dict(matches)
``` |
Why can't I join this tuple in Python? | 1,815,316 | 30 | 2009-11-29T11:41:34Z | 1,815,318 | 7 | 2009-11-29T11:43:37Z | [
"python",
"list",
"tuples"
] | ```
e = ('ham', 5, 1, 'bird')
logfile.write(','.join(e))
```
I have to join it so that I can write it into a text file. | join() only works with strings, not with integers. Use ','.join(str(i) for i in e). |
Why can't I join this tuple in Python? | 1,815,316 | 30 | 2009-11-29T11:41:34Z | 1,815,319 | 62 | 2009-11-29T11:43:47Z | [
"python",
"list",
"tuples"
] | ```
e = ('ham', 5, 1, 'bird')
logfile.write(','.join(e))
```
I have to join it so that I can write it into a text file. | `join` only takes lists of strings, so convert them first
```
>>> e = ('ham', 5, 1, 'bird')
>>> ','.join(map(str,e))
'ham,5,1,bird'
```
Or maybe more pythonic
```
>>> ','.join(str(i) for i in e)
'ham,5,1,bird'
``` |
Why can't I sort this list? | 1,815,528 | 3 | 2009-11-29T13:19:59Z | 1,815,541 | 7 | 2009-11-29T13:24:08Z | [
"python",
"list",
"tuples"
] | ```
statlist = [('abc',5,1), ('bzs',66,1), ... ]
sorted(statlist, key=lambda x: int(x[1]))
```
I want to sort it by the integer largest to smallest. In this case, 5 and 66. But it doesn't seem to be working. | The `sorted` function returns a *new* list so you will need to assign the results of the function like this:
```
new_list = sorted(statlist, key=lambda x: int(x[1]))
``` |
Why can't I sort this list? | 1,815,528 | 3 | 2009-11-29T13:19:59Z | 1,815,552 | 7 | 2009-11-29T13:27:22Z | [
"python",
"list",
"tuples"
] | ```
statlist = [('abc',5,1), ('bzs',66,1), ... ]
sorted(statlist, key=lambda x: int(x[1]))
```
I want to sort it by the integer largest to smallest. In this case, 5 and 66. But it doesn't seem to be working. | Use the `.sort` method for in place sorting:
```
statlist = [('abc',5,1), ('bzs',66,1), ... ]
statlist.sort(key=lambda x: int(x[1]))
```
If you do want to use `sorted`, then reassign the variable:
```
statlist = [('abc',5,1), ('bzs',66,1), ... ]
statlist = sorted(statlist, key=lambda x: int(x[1]))
```
For descendin... |
What's an easy way to implement a --quiet option in a python script | 1,815,760 | 12 | 2009-11-29T15:08:47Z | 1,815,773 | 27 | 2009-11-29T15:13:45Z | [
"python"
] | Am working on a command line python script - throughout the script, I have a lot of information I am `print`-ing to the terminal window so that I may follow along with what is happening.
Using `OptionParser` I want to add a `--quiet` option so I can silence all the output. I am looking for a pythonic way to go about i... | You could use [`logging`](http://docs.python.org/library/logging.html) and assign those things that should not be printed if `QUIET` a different log level.
**Edit:** [THC4K's answer](http://stackoverflow.com/questions/1815760/whats-an-easy-way-to-implement-a-quiet-option-in-a-python-script/1815802#1815802) shows an ex... |
What's an easy way to implement a --quiet option in a python script | 1,815,760 | 12 | 2009-11-29T15:08:47Z | 1,815,802 | 11 | 2009-11-29T15:27:21Z | [
"python"
] | Am working on a command line python script - throughout the script, I have a lot of information I am `print`-ing to the terminal window so that I may follow along with what is happening.
Using `OptionParser` I want to add a `--quiet` option so I can silence all the output. I am looking for a pythonic way to go about i... | can silence **all** the output by running it as `python myscript.py > /dev/null`
change the output streams in the script:
```
if QUIET:
sys.stdout = open(os.devnull,'a')
sys.stderr = open(os.devnull,'a')
print something
```
use a different print function
```
from __future__ import print_function
if QUIET:
... |
How to create a generator/iterator with the Python C API? | 1,815,812 | 35 | 2009-11-29T15:30:12Z | 1,816,961 | 51 | 2009-11-29T22:10:50Z | [
"python",
"c",
"iterator",
"generator",
"python-c-api"
] | How do I replicate the following Python code with the Python C API?
```
class Sequence():
def __init__(self, max):
self.max = max
def data(self):
i = 0
while i < self.max:
yield i
i += 1
```
So far, I have this:
```
#include <Python/Python.h>
#include <Python/s... | Below is a simple implementation of module `spam` with one function `myiter(int)` returning iterator:
```
import spam
for i in spam.myiter(10):
print i
```
prints numbers from 0 to 9.
It is simpler then your case but shows main points: defining object with standard `__iter__()` and `next()` methods, and implemen... |
How to get the html source of a specific element with selenium? | 1,816,232 | 7 | 2009-11-29T18:05:20Z | 1,816,718 | 8 | 2009-11-29T20:48:21Z | [
"python",
"selenium"
] | The page I'm looking at contains :
```
<div id='1'> <p> text 1 <h1> text 2 </h1> text 3 <p> text 4 </p> </p> </div>
```
I want to get all the text in the div, except for the text that is in the `<h>`.
(I want to get "text 1","text 3" and "text 4")
There may be a few `<h>` elements, or none at all.
And there may be a ... | The following code will give you the HTML in the div element:
```
sel = selenium('localhost', 4444, browser, my_url)
html = sel.get_eval("this.browserbot.getCurrentWindow().document.getElementById('1').innerHTML")
```
then you can use BeautifulSoup to parse it and extract what you really want.
I hope it helps |
Reloading a changed python file in emacs python shell | 1,816,388 | 6 | 2009-11-29T18:49:50Z | 1,816,438 | 15 | 2009-11-29T19:06:08Z | [
"python",
"emacs"
] | In the emacs Python shell (I'm running 2.\* Python) I am importing a .py file I'm working with and testing the code. If I change the code however I'm not sure how to import it again.
From my reading so far it seems that
```
reload(modulename)
```
should work, but it doesn't seem to.
Perhaps just shutting down the p... | While `reload()` does work, it doesn't change references to classes, functions, and other objects, so it's easy to see an old version. A most consistent solution is to replace `reload()` with either `exec` (which means not using `import` in the first place) or restarting the interpreter entirely.
If you do want to con... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.