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
using __init__.py
2,361,124
59
2010-03-02T05:36:24Z
2,361,131
22
2010-03-02T05:42:02Z
[ "python", "module", "initialization", "packages" ]
I am having difficulty understanding the usage scenarios or design goals of python's `__init__.py` files in my projects. Assume that I have 'model' directory (refers as a package) which contains the following files 1. `__init__.py` 2. `meta.py` 3. `solrmodel.py` 4. `mongomodel.py` 5. `samodel.py` I found two ways of...
The contents of `__init__.py` are imported when you import a module within the package. You're overlooking a third scenario, which is to put the common parts in a separate module and then have the other modules import that, leaving `__init__.py` for things that will be used outside the package. This is the practice I ...
using __init__.py
2,361,124
59
2010-03-02T05:36:24Z
2,361,278
46
2010-03-02T06:26:05Z
[ "python", "module", "initialization", "packages" ]
I am having difficulty understanding the usage scenarios or design goals of python's `__init__.py` files in my projects. Assume that I have 'model' directory (refers as a package) which contains the following files 1. `__init__.py` 2. `meta.py` 3. `solrmodel.py` 4. `mongomodel.py` 5. `samodel.py` I found two ways of...
The vast majority of the `__init__.py` files I write are empty, because many packages don't have anything to initialize. One example in which I may want initialization is when at package-load time I want to read in a bunch of data once and for all (from files, a DB, or the web, say) -- in which case it's **much** nice...
What is the best way to get the first item from an iterable matching a condition?
2,361,426
95
2010-03-02T07:11:29Z
2,361,495
9
2010-03-02T07:27:51Z
[ "python", "coding-style", "iterator" ]
In Python, I would like to get the first item from a list matching a condition. For example, the following function is adequate: ``` def first(the_iterable, condition = lambda x: True): for i in the_iterable: if condition(i): return i ``` This function could be used something like this: ``` >...
Similar to using `ifilter`, you could use a generator expression: ``` >>> (x for x in xrange(10) if x > 5).next() 6 ``` In either case, you probably want to catch `StopIteration` though, in case no elements satisfy your condition. Technically speaking, I suppose you could do something like this: ``` >>> foo = None ...
What is the best way to get the first item from an iterable matching a condition?
2,361,426
95
2010-03-02T07:11:29Z
2,364,277
149
2010-03-02T15:29:26Z
[ "python", "coding-style", "iterator" ]
In Python, I would like to get the first item from a list matching a condition. For example, the following function is adequate: ``` def first(the_iterable, condition = lambda x: True): for i in the_iterable: if condition(i): return i ``` This function could be used something like this: ``` >...
In Python 2.6 or better: * `next(x for x in the_iterable if x > 3)` if you want `StopIteration` to be raised if no matching element is found, * `next( (x for x in the_iterable if x>3), default_value)` if you want `default_value` (e.g. `None`) to be returned instead. Note that you need an extra pair of parent...
Detecting consecutive integers in a list
2,361,945
25
2010-03-02T09:10:14Z
2,361,991
48
2010-03-02T09:17:00Z
[ "python", "algorithm", "list" ]
I have a list containing data as such: ``` [1, 2, 3, 4, 7, 8, 10, 11, 12, 13, 14] ``` I'd like to print out the ranges of consecutive integers: ``` 1-4, 7-8, 10-14 ``` Is there a built-in/fast/efficient way of doing this?
From [the docs](https://docs.python.org/2.6/library/itertools.html#examples): ``` >>> from itertools import groupby >>> from operator import itemgetter >>> data = [ 1, 4,5,6, 10, 15,16,17,18, 22, 25,26,27,28] >>> for k, g in groupby(enumerate(data), lambda (i, x): i-x): ... print map(itemgetter(1), g) ... [1] [4, ...
Match start and end of file in python with regex
2,362,471
4
2010-03-02T10:37:57Z
2,363,282
7
2010-03-02T13:14:35Z
[ "python", "regex" ]
I'm having a hard time finding the regex for the start and end of a file in python. How would I accomplish this ?
Read the whole file into a string, then \A matches only the beginning of a string, and \Z matches only the end of a string. With re.MULTILINE, '^' matches the beginning of the string **and** the just after a newline, and '$' matches the end of the string **and** just before a newline. See the Python documentation for [...
returning out of for-loop
2,363,602
8
2010-03-02T14:05:40Z
2,363,643
14
2010-03-02T14:11:06Z
[ "python", "for-loop", "while-loop" ]
I'm pretty new at python and I was wondering if this: ``` def func(self, foo): for foo in self.list: if foo.boolfunc(): return True return False ``` is good practice. Can I return out of a loop like the above or should i use a while-loop, like so? ``` def func(self, foo): found = false whi...
There's nothing wrong with your example, but it's better to write ``` def func(self, foo): return any(foo.boolfunc() for foo in self.list) ```
returning out of for-loop
2,363,602
8
2010-03-02T14:05:40Z
2,363,807
8
2010-03-02T14:34:14Z
[ "python", "for-loop", "while-loop" ]
I'm pretty new at python and I was wondering if this: ``` def func(self, foo): for foo in self.list: if foo.boolfunc(): return True return False ``` is good practice. Can I return out of a loop like the above or should i use a while-loop, like so? ``` def func(self, foo): found = false whi...
It should be mentioned that in Python, [for loops can have an else clause](http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops). The else clause is only executed when the loop terminates through exhaustion of the list. So you could write: ``` def func(self): fo...
append new row to old csv file python
2,363,731
44
2010-03-02T14:23:33Z
2,363,742
80
2010-03-02T14:25:51Z
[ "python", "csv", "append", "writer" ]
I am trying to add a new row to my old csv file. Basically, it gets updated each time I run the Python script. Right now I am storing the old csv rows values in a list and then deleting the csv file and creating it again with the new list value. Wanted to know are there any better ways of doing this.
``` fd = open('document.csv','a') fd.write(myCsvRow) fd.close() ``` Opening a file with the `'a'` parameter allows you to append to the end of the file instead of simply overwriting the existing content. Try that.
append new row to old csv file python
2,363,731
44
2010-03-02T14:23:33Z
37,654,233
8
2016-06-06T09:46:15Z
[ "python", "csv", "append", "writer" ]
I am trying to add a new row to my old csv file. Basically, it gets updated each time I run the Python script. Right now I am storing the old csv rows values in a list and then deleting the csv file and creating it again with the new list value. Wanted to know are there any better ways of doing this.
I prefer this solution using the `csv` module from the standard library and the `open` method to avoid leaving the file open. The key point is using `'a'` for appending when you open the file. ``` import csv fields=['first','second','third'] with open(r'name', 'a') as f: writer = csv.writer(f) ...
Avoiding nesting two for loops
2,364,382
2
2010-03-02T15:42:40Z
2,364,411
8
2010-03-02T15:46:48Z
[ "python", "for-loop" ]
Please have a look at the code below: ``` import string from collections import defaultdict first_complex=open( "residue_a_chain_a_b_backup.txt", "r" ) first_complex_lines=first_complex.readlines() first_complex_lines=map( string.strip, first_complex_lines ) first_complex.close() second_complex=open( "residue_a_ch...
You want to convert `list_2` to a set, and check for membership: ``` list_1 = ['a', 'big', 'list'] list_2 = ['another', 'big', 'list'] target_set = set(list_2) for a in list_1: if a in target_set: print a ``` Outputs: ``` big list ``` A set gives you the advantage of O(1) access time to determine mem...
Google App Engine: Trouble with Datastore Query
2,364,531
3
2010-03-02T16:01:48Z
2,364,698
9
2010-03-02T16:19:55Z
[ "python", "google-app-engine", "gae-datastore" ]
This query works: ``` item = db.GqlQuery("SELECT * FROM Item WHERE CSIN = 13")[0] ``` although if there are no results returned, it blows up in my face. (How can I get around this? A `for` loop seems dubious when I want at max one iteration.) This query does not work: ``` item = db.GqlQuery("SELECT * FROM Item WHER...
You're trying to get an item from a list (or a list-like object) that is empty. What you're doing is sort of comparable to the following: ``` >>> results = [] # an empty list >>> item = results[0] # Raises an IndexError, because there is nothing in the list ``` What you need to do instead is: ``` item = db.GqlQuery(...
Matplotlib runs out of memory when plotting in a loop
2,364,945
11
2010-03-02T16:50:50Z
2,365,782
11
2010-03-02T18:48:41Z
[ "python", "numpy", "matplotlib" ]
I have a fairly simple plotting routine that looks like this: ``` from __future__ import division import datetime import matplotlib matplotlib.use('Agg') from matplotlib.pyplot import figure, plot, show, legend, close, savefig, rcParams import numpy from globalconstants import * def plotColumns(columnNumbers, t, ...
Is each loop supposed to generate a new figure? I don't see you closing it or creating a new figure instance from loop to loop. This call will clear the current figure after you save it at the end of the loop: pyplot.clf() I'd refactor, though, and make your code more OO and create a new figure instance on each loop...
Matplotlib runs out of memory when plotting in a loop
2,364,945
11
2010-03-02T16:50:50Z
7,889,179
17
2011-10-25T12:21:21Z
[ "python", "numpy", "matplotlib" ]
I have a fairly simple plotting routine that looks like this: ``` from __future__ import division import datetime import matplotlib matplotlib.use('Agg') from matplotlib.pyplot import figure, plot, show, legend, close, savefig, rcParams import numpy from globalconstants import * def plotColumns(columnNumbers, t, ...
I've also run into this error. what seems to have fixed it is ``` while True: fig = pyplot.figure() ax = fig.add_subplot(111) ax.plot(x,y) ax.legend(legendStrings, loc = 'best') fig.savefig('himom.png') #new bit here pylab.close(fig) #where f is the figure ``` running my loop stably now wi...
Python: Convert Unicode to ASCII without errors
2,365,411
103
2010-03-02T17:52:42Z
2,365,444
137
2010-03-02T17:56:45Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
My code just scrapes a web page, then converts it to Unicode. ``` html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) ``` But I get a `UnicodeDecodeError`: --- ``` Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/Google...
``` >>> u'aあä'.encode('ascii', 'ignore') 'a' ``` **EDIT:** Decode the string you get back, using either the charset in the the appropriate `meta` tag in the response or in the `Content-Type` header, then encode.
Python: Convert Unicode to ASCII without errors
2,365,411
103
2010-03-02T17:52:42Z
2,367,868
21
2010-03-03T00:02:07Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
My code just scrapes a web page, then converts it to Unicode. ``` html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) ``` But I get a `UnicodeDecodeError`: --- ``` Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/Google...
I use this helper function throughout all of my projects. If it can't convert the unicode, it ignores it. This ties into a django library, but with a little research you could bypass it. ``` from django.utils import encoding def convert_unicode_to_string(x): """ >>> convert_unicode_to_string(u'ni\xf1era') ...
Python: Convert Unicode to ASCII without errors
2,365,411
103
2010-03-02T17:52:42Z
2,368,248
72
2010-03-03T01:42:13Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
My code just scrapes a web page, then converts it to Unicode. ``` html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) ``` But I get a `UnicodeDecodeError`: --- ``` Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/Google...
Can we get the actual value used for `link`? In addition, we usually encounter this problem here when we are trying to `.encode()` an already encoded byte string. So you might try to decode it first as in ``` html = urllib.urlopen(link).read() unicode_str = html.decode(<source encoding>) encoded_str = unicode_str.enc...
Python: Convert Unicode to ASCII without errors
2,365,411
103
2010-03-02T17:52:42Z
7,782,177
78
2011-10-16T03:31:36Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
My code just scrapes a web page, then converts it to Unicode. ``` html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) ``` But I get a `UnicodeDecodeError`: --- ``` Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/Google...
As an extension to Ignacio Vazquez-Abrams' answer ``` >>> u'aあä'.encode('ascii', 'ignore') 'a' ``` It is sometimes desirable to remove accents from characters and print the base form. This can be accomplished with ``` >>> import unicodedata >>> unicodedata.normalize('NFKD', u'aあä').encode('ascii', 'ignore') 'a...
Python: Convert Unicode to ASCII without errors
2,365,411
103
2010-03-02T17:52:42Z
35,536,228
18
2016-02-21T12:38:51Z
[ "python", "unicode", "utf-8", "character-encoding", "ascii" ]
My code just scrapes a web page, then converts it to Unicode. ``` html = urllib.urlopen(link).read() html.encode("utf8","ignore") self.response.out.write(html) ``` But I get a `UnicodeDecodeError`: --- ``` Traceback (most recent call last): File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/Google...
Use **[unidecode](https://pypi.python.org/pypi/Unidecode)** - it even converts weird characters to ascii instantly, and even converts Chinese to phonetic ascii. ``` $ pip install unidecode ``` then: ``` >>> from unidecode import unidecode >>> unidecode(u'北京') 'Bei Jing' >>> unidecode(u'Škoda') 'Skoda' ```
Designing to easily migrate to Google App Engine
2,365,647
6
2010-03-02T18:29:21Z
2,365,730
7
2010-03-02T18:42:43Z
[ "python", "google-app-engine", "relational-database", "web2py", "non-relational-database" ]
I am going to start designing a web app shortly, and while I have lots of experience doing it in the SQL world, I have no idea what I need to take into consideration for doing so with the goal of migrating to GAE in the very near future. Alternatively, I could design the app for GAE from the start, and so in that case...
Just out of top of my head: * It's really ONLY a key->value store, don't be fooled by things like [GQL](http://code.google.com/intl/pl-PL/appengine/docs/python/datastore/gqlreference.html) (which is just a subset of SQL SELECT) * No JOINs - often you have to denormalize or forget * More or less frequent timeouts * (Ve...
Decorating python class methods, how do I pass the instance to the decorator?
2,365,701
44
2010-03-02T18:38:03Z
2,365,771
62
2010-03-02T18:47:35Z
[ "python" ]
This is python 2.5, it's [GAE](https://developers.google.com/appengine/docs/python/) too not that it matters. I have the following code, I'm decorating the foo() method in bar, using the dec\_check class as a decorator. ``` class dec_check(object): def __init__(self, f): self.func = f def __call__(self): ...
You need to make the decorator into a [descriptor](http://users.rcn.com/python/download/Descriptor.htm) -- either by ensuring its (meta)class has a `__get__` method, or, **way** simpler, by using a decorator *function* instead of a decorator *class* (since functions are already descriptors). E.g.: ``` def dec_check(f)...
Decorating python class methods, how do I pass the instance to the decorator?
2,365,701
44
2010-03-02T18:38:03Z
3,296,318
36
2010-07-21T04:28:13Z
[ "python" ]
This is python 2.5, it's [GAE](https://developers.google.com/appengine/docs/python/) too not that it matters. I have the following code, I'm decorating the foo() method in bar, using the dec\_check class as a decorator. ``` class dec_check(object): def __init__(self, f): self.func = f def __call__(self): ...
Alex's answer suffices when a function is sufficient. However When you need a class you can make it work by adding the following method to the decorator class. ``` def __get__(self, obj, objtype): """Support instance methods.""" import functools return functools.partial(self.__call__, obj) ``` To understa...
Jinja2 in Google App Engine
2,365,774
12
2010-03-02T18:47:40Z
2,369,184
12
2010-03-03T06:25:49Z
[ "python", "google-app-engine", "caching", "jinja2" ]
I have started using [Jinja2](http://jinja.pocoo.org/2/documentation/) as my templating engine on Google App Engine (in Python). My question is this: Will bytecode caching work in production? It is working very well on the development server, but I read somewhere that bytecode caching depends on the `marshal` module, ...
Rodrigo Moraes created some special loaders for Jinja2 under GAE, see [here](http://groups.google.com/group/google-appengine-python/browse_thread/thread/04d4bf3dd615ed1e/2907cdeff922710c). It's not bytecode caching but it precompiles all templates to Python so you avoid the Jinja2 parsing overhead. Note that (from [th...
Jinja2 in Google App Engine
2,365,774
12
2010-03-02T18:47:40Z
9,003,292
9
2012-01-25T13:11:27Z
[ "python", "google-app-engine", "caching", "jinja2" ]
I have started using [Jinja2](http://jinja.pocoo.org/2/documentation/) as my templating engine on Google App Engine (in Python). My question is this: Will bytecode caching work in production? It is working very well on the development server, but I read somewhere that bytecode caching depends on the `marshal` module, ...
Jinja2 is now included in GAE. Apparently you need to migrate your app to Python 2.7. In app.yaml add ``` libraries: - name: jinja2 version: "2.6" ``` Here is the source of this information: <http://blog.notdot.net/2011/11/Migrating-to-Python-2-7-part-2-Webapp-and-templates>
haskell vs python typing
2,365,783
2
2010-03-02T18:48:54Z
2,365,869
7
2010-03-02T19:01:37Z
[ "python", "dynamic", "haskell", "static", "types" ]
I am looking for example where things in python would be easier to program just because it is dynamically typed? I want to compare it with Haskell type system because its static typing doesn't get in the way like c# or java. Can I program in Haskell as I can in python without static typing being a hindrance? PS: I am...
> Can I program in Haskell as I can in python without static typing being a hindrance Yes. To elaborate, I would say the main gotcha will be the use of existential types in Haskell for heterogeneous data structures (regular data structures holding lists of variously typed elements). This often catches OO people used ...
merging Python dictionaries
2,365,921
19
2010-03-02T19:08:53Z
2,365,976
19
2010-03-02T19:16:33Z
[ "python", "list", "dictionary", "merge" ]
I am trying to merge the following python dictionaries as follow: ``` dict1= {'paul':100, 'john':80, 'ted':34, 'herve':10} dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'} output = {'paul':[100,'a'], 'john':[80, 'b'], 'ted':[34,'c'], 'peter':[None, 'd'], 'herve':[10, None]} ``` Is there an efficient way to d...
``` output = dict((k, [dict1[k], dict2.get(k)]) for k in dict1) output.update((k, [None, dict2[k]]) for k in dict2 if k not in dict1) ```
merging Python dictionaries
2,365,921
19
2010-03-02T19:08:53Z
2,365,991
13
2010-03-02T19:18:11Z
[ "python", "list", "dictionary", "merge" ]
I am trying to merge the following python dictionaries as follow: ``` dict1= {'paul':100, 'john':80, 'ted':34, 'herve':10} dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'} output = {'paul':[100,'a'], 'john':[80, 'b'], 'ted':[34,'c'], 'peter':[None, 'd'], 'herve':[10, None]} ``` Is there an efficient way to d...
This will work: ``` dict((k, [dict1.get(k), dict2.get(k)]) for k in set(dict1.keys() + dict2.keys())) ``` Output: ``` {'john': [80, 'b'], 'paul': [100, 'a'], 'peter': [None, 'd'], 'ted': [34, 'c'], 'herve': [10, None]} ```
merging Python dictionaries
2,365,921
19
2010-03-02T19:08:53Z
2,366,681
7
2010-03-02T20:56:24Z
[ "python", "list", "dictionary", "merge" ]
I am trying to merge the following python dictionaries as follow: ``` dict1= {'paul':100, 'john':80, 'ted':34, 'herve':10} dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'} output = {'paul':[100,'a'], 'john':[80, 'b'], 'ted':[34,'c'], 'peter':[None, 'd'], 'herve':[10, None]} ``` Is there an efficient way to d...
In **Python2.7** or **Python3.1** you can easily generalise to work with any number of dictionaries using a combination of list, set and dict comprehensions! ``` >>> dict1 = {'paul':100, 'john':80, 'ted':34, 'herve':10} >>> dict2 = {'paul':'a', 'john':'b', 'ted':'c', 'peter':'d'} >>> dicts = dict1,dict2 >>> {k:[d.get(...
Can a Python decorator of an instance method access the class?
2,366,713
61
2010-03-02T20:59:47Z
2,367,605
41
2010-03-02T23:10:56Z
[ "python", "decorator" ]
Hi I have something roughly like the following. Basically I need to access the class of an instance method from a decorator used upon the instance method in its definition. ``` def decorator(view): # do something that requires view's class print view.im_class return view class ModelA(object): @decorat...
If you are using Python 2.6 or later you could use a class decorator, perhaps something like this (warning: untested code). ``` def class_decorator(cls): for name, method in cls.__dict__.iteritems(): if hasattr(method, "use_class"): # do something with the method and class print name...
Can a Python decorator of an instance method access the class?
2,366,713
61
2010-03-02T20:59:47Z
6,683,238
11
2011-07-13T17:46:46Z
[ "python", "decorator" ]
Hi I have something roughly like the following. Basically I need to access the class of an instance method from a decorator used upon the instance method in its definition. ``` def decorator(view): # do something that requires view's class print view.im_class return view class ModelA(object): @decorat...
As others have pointed out, the class hasn't been created at the time the decorator is called. **However**, it's possible to annotate the function object with the decorator parameters, then re-decorate the function in the metaclass's `__new__` method. You'll need to access the function's `__dict__` attribute directly, ...
Is there a way to create a python object that will be not sortable?
2,367,119
8
2010-03-02T21:55:28Z
2,367,139
7
2010-03-02T21:58:48Z
[ "python" ]
Is there a possibility to create any python object that will be not sortable? So that will be an exception when trying to sort a list of that objects? I created a very simple class, didn't define any comparison methods, but still instances of this class are comparable and thus sortable. Maybe, my class inherits compari...
You could define a `__cmp__` method on the class and always raise an exception when it is called. That might do the trick. Out of curiosity, why?
Django - Get Foreign key objects in single query?
2,367,747
5
2010-03-02T23:34:23Z
2,367,782
8
2010-03-02T23:42:21Z
[ "python", "django", "foreign-key-relationship" ]
I'm finding django foreign keys a bit confusing, is there any way to do the view below, using a single query? ``` # Model class Programme(models.Model): name = models.CharField(max_length = 64) class Actor(models.Model): programme = models.ForeignKey(Programme) name = models.CharField(max_length = 64) #...
You query `Programme` and assign to `programme`, but you never use the result anywhere. Just remove that line.
Installing easy_install... to get to installing lxml
2,368,008
21
2010-03-03T00:31:19Z
2,368,892
23
2010-03-03T05:04:57Z
[ "python", "lxml", "easy-install" ]
I've come to grips with the fact that ElementTree isn't going to do what I want it to do. I've checked out the documentation for lxml, and it appears that it will serve my purposes. To get lxml, I need to get easy\_install. So I downloaded it from [here](http://pypi.python.org/pypi/setuptools#cygwin-mac-os-x-linux-othe...
First off we don't use easy\_install anymore. We use [pip](https://pip.pypa.io/). Please use pip instead. To get to your particular troubles, as the comments point out, you're missing GCC. On OS X, [Xcode](http://developer.apple.com/tools/xcode/) Command Line Tools provides GCC, as well as many other programs necessar...
Installing easy_install... to get to installing lxml
2,368,008
21
2010-03-03T00:31:19Z
4,026,935
13
2010-10-26T18:46:54Z
[ "python", "lxml", "easy-install" ]
I've come to grips with the fact that ElementTree isn't going to do what I want it to do. I've checked out the documentation for lxml, and it appears that it will serve my purposes. To get lxml, I need to get easy\_install. So I downloaded it from [here](http://pypi.python.org/pypi/setuptools#cygwin-mac-os-x-linux-othe...
Ensure you have libxml2-dev and libxslt1-dev installed ``` apt-get install libxml2-dev apt-get install libxslt1-dev ``` Then your installation should build properly.
Installing easy_install... to get to installing lxml
2,368,008
21
2010-03-03T00:31:19Z
4,205,580
10
2010-11-17T14:51:00Z
[ "python", "lxml", "easy-install" ]
I've come to grips with the fact that ElementTree isn't going to do what I want it to do. I've checked out the documentation for lxml, and it appears that it will serve my purposes. To get lxml, I need to get easy\_install. So I downloaded it from [here](http://pypi.python.org/pypi/setuptools#cygwin-mac-os-x-linux-othe...
try: `sudo apt-get install python-lxml`
2D integrals in SciPy
2,368,337
10
2010-03-03T02:17:10Z
2,368,412
11
2010-03-03T02:43:16Z
[ "python", "integration", "wolfram-mathematica", "scipy", "multidimensional-array" ]
I am trying to integrate a multivariable function in [SciPy](http://en.wikipedia.org/wiki/SciPy) over a 2D area. What would be the equivalent of the following [Mathematica](http://en.wikipedia.org/wiki/Mathematica) code? ``` In[1]:= F[x_, y_] := Cos[x] + Cos[y] In[2]:= Integrate[F[x, y], {x, -\[Pi], \[Pi]}, {y, -\[P...
I think it would work something like this: ``` def func(x,y): return cos(x) + cos(y) def func2(y, a, b): return integrate.quad(func, a, b, args=(y,))[0] print integrate.quad(func2, -pi/2, pi/2, args=(-pi/2, pi/2))[0] ``` [Wolfram|Alpha agrees](http://www.wolframalpha.com/input/?i=int+cos%28x%29%2Bcos%28y%29...
2D integrals in SciPy
2,368,337
10
2010-03-03T02:17:10Z
2,374,686
8
2010-03-03T20:27:55Z
[ "python", "integration", "wolfram-mathematica", "scipy", "multidimensional-array" ]
I am trying to integrate a multivariable function in [SciPy](http://en.wikipedia.org/wiki/SciPy) over a 2D area. What would be the equivalent of the following [Mathematica](http://en.wikipedia.org/wiki/Mathematica) code? ``` In[1]:= F[x_, y_] := Cos[x] + Cos[y] In[2]:= Integrate[F[x, y], {x, -\[Pi], \[Pi]}, {y, -\[P...
If you want to do symbolic integration, have a look at sympy ([code.google.com/p/sympy](http://code.google.com/p/sympy/)): ``` import sympy as s x, y = s.symbols('x, y') expr = s.cos(x) + s.sin(y) expr.integrate((x, -s.pi, s.pi), (y, -s.pi, s.pi)) ```
I want my Python script to detect the version and quit gracefully in case of a mismatch
2,368,574
3
2010-03-03T03:34:36Z
2,368,590
7
2010-03-03T03:41:10Z
[ "python", "version" ]
I'd like to make it as general as possible - e.g. handle as many versions as possible. Since version 3 is not backwards compatible with version 2, I want to make sure that I use the right print statement. Please let me know if you have questions and feel free to share related knowledge having to do with dynamic logic...
In order to get around syntax errors you would have to use conditional imports, if you want to mix syntax between versions 2 and 3. ``` # just psuedocode if version is x: import lib_x # contains version x implementation else: import lib_y # contains version y compatible implementation ``` It is not advisable to...
I want my Python script to detect the version and quit gracefully in case of a mismatch
2,368,574
3
2010-03-03T03:34:36Z
2,368,609
7
2010-03-03T03:48:45Z
[ "python", "version" ]
I'd like to make it as general as possible - e.g. handle as many versions as possible. Since version 3 is not backwards compatible with version 2, I want to make sure that I use the right print statement. Please let me know if you have questions and feel free to share related knowledge having to do with dynamic logic...
The `sys` module also contains the version info (first available in version 2.0): ``` import sys if sys.version_info[0] == 2: print("You are using Python 2.x") elif sys.version_info[0] == 3: print("You are using Python 3.x") ```
List fields present in a table
2,368,948
7
2010-03-03T05:18:59Z
2,368,971
10
2010-03-03T05:26:31Z
[ "python", "django" ]
Is there any way to to list out the fields present in a table in django models ``` class Profile(models.Model): user = models.ForeignKey(User, unique=True) name = models.ForeignKey(School) emp = models.ForeignKey(User, unique=True) ``` How to list out the filed names from the table Profile,(just like des...
`Profile._meta.fields` will get you a list of fields. The `name` property of the field object contains the name of the field. `Profile._meta.get_fields_with_model()` will return a list of 2-tuples of `(field, model)`, with `model` being `None` if the field is in `Profile`.
Bad file descriptor error
2,368,967
11
2010-03-03T05:23:06Z
2,368,969
26
2010-03-03T05:24:28Z
[ "python", "file" ]
If I try executing the following code ``` f = file('test','rb') fout = file('test.out','wb') for i in range(10): a = f.read(1) fout.write(a) f.close() f = fout f.seek(4) print f.read(4) ``` Where `'test'` is any arbitrary file, I get: ``` Traceback (most recent call last): File "testbad.py", line 12, in...
you've only opened the file `fout` for writing, not reading. To open for both use ``` fout = file('test.out','r+b') ```
How to delete all blank lines in the file with the help of python?
2,369,440
7
2010-03-03T07:29:14Z
2,369,474
10
2010-03-03T07:39:05Z
[ "python" ]
For example, we have some file like that: > first line > second line > > > third line And in result we have to get: > first line > second line > third line Use ONLY python
``` import fileinput for line in fileinput.FileInput("file",inplace=1): if line.rstrip(): print line ```
How to delete all blank lines in the file with the help of python?
2,369,440
7
2010-03-03T07:29:14Z
2,369,538
9
2010-03-03T07:55:21Z
[ "python" ]
For example, we have some file like that: > first line > second line > > > third line And in result we have to get: > first line > second line > third line Use ONLY python
The `with` statement is excellent for automatically opening and closing files. ``` with open('myfile','rw') as file: for line in file: if line.strip(): file.write(line) ```
Generate a heatmap in MatPlotLib using a scatter data set
2,369,492
92
2010-03-03T07:42:17Z
2,371,812
83
2010-03-03T13:55:43Z
[ "python", "matplotlib" ]
I have a set of X,Y data points (about 10k) that are easy to plot as a scatter plot but that I would like to represent as a heatmap. I looked through the examples in MatPlotLib and they all seem to already start with heatmap cell values to generate the image. Is there a method that converts a bunch of x,y, all differ...
In *Matplotlib* lexicon, i think you want a **hexbin** plot. If you're not familiar with this type of plot, it's just a *bivariate histogram* in which the xy-plane is tessellated by a regular grid of hexagons. So from a histogram, you can just count the number of points falling in each hexagon, discretiize the plotti...
Generate a heatmap in MatPlotLib using a scatter data set
2,369,492
92
2010-03-03T07:42:17Z
2,461,029
101
2010-03-17T09:25:51Z
[ "python", "matplotlib" ]
I have a set of X,Y data points (about 10k) that are easy to plot as a scatter plot but that I would like to represent as a heatmap. I looked through the examples in MatPlotLib and they all seem to already start with heatmap cell values to generate the image. Is there a method that converts a bunch of x,y, all differ...
If you don't want hexagons, you can use numpy's `histogram2d` function: ``` import numpy as np import numpy.random import matplotlib.pyplot as plt # Generate some test data x = np.random.randn(8873) y = np.random.randn(8873) heatmap, xedges, yedges = np.histogram2d(x, y, bins=50) extent = [xedges[0], xedges[-1], yed...
Generate a heatmap in MatPlotLib using a scatter data set
2,369,492
92
2010-03-03T07:42:17Z
13,233,972
10
2012-11-05T14:19:29Z
[ "python", "matplotlib" ]
I have a set of X,Y data points (about 10k) that are easy to plot as a scatter plot but that I would like to represent as a heatmap. I looked through the examples in MatPlotLib and they all seem to already start with heatmap cell values to generate the image. Is there a method that converts a bunch of x,y, all differ...
If you are using 1.2.x ``` x = randn(100000) y = randn(100000) hist2d(x,y,bins=100); ``` ![enter image description here](http://i.stack.imgur.com/yj9ku.png)
Generate a heatmap in MatPlotLib using a scatter data set
2,369,492
92
2010-03-03T07:42:17Z
36,515,364
8
2016-04-09T10:06:31Z
[ "python", "matplotlib" ]
I have a set of X,Y data points (about 10k) that are easy to plot as a scatter plot but that I would like to represent as a heatmap. I looked through the examples in MatPlotLib and they all seem to already start with heatmap cell values to generate the image. Is there a method that converts a bunch of x,y, all differ...
Instead of using np.hist2d, which in general produces quite ugly histograms, I would like to recycle [py-sphviewer](https://github.com/alejandrobll/py-sphviewer), a python package for rendering particle simulations using an adaptive smoothing kernel and that can be easily installed from pip (see webpage documentation)....
How do I use Python's httplib to send a POST to a URL, with a dictionary of parameters?
2,370,003
15
2010-03-03T09:27:35Z
2,370,057
31
2010-03-03T09:38:18Z
[ "python", "api", "post", "httplib" ]
I just want a function that can take 2 parameters: * the URL to POST to * a dictionary of parameters How can this be done with httplib? thanks.
From the [Python documentation](https://docs.python.org/release/2.7/library/httplib.html#examples): ``` >>> import httplib, urllib >>> params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) >>> headers = {"Content-type": "application/x-www-form-urlencoded", ... "Accept": "text/plain"} >>> conn = http...
How do I use Python's httplib to send a POST to a URL, with a dictionary of parameters?
2,370,003
15
2010-03-03T09:27:35Z
15,160,434
7
2013-03-01T14:44:40Z
[ "python", "api", "post", "httplib" ]
I just want a function that can take 2 parameters: * the URL to POST to * a dictionary of parameters How can this be done with httplib? thanks.
A simpler one, using just urllib: ``` import urllib params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0}) f = urllib.urlopen("http://www.example.org/cgi-bin/query", params) print f.read() ``` Found in Python docs for [urllib module](http://docs.python.org/2/library/urllib.html#examples)
SOAP 1.2 python client
2,370,573
13
2010-03-03T11:01:19Z
2,389,490
8
2010-03-05T19:42:46Z
[ "python", "soap" ]
I am looking for a python SOAP 1.2 client but it seems that it does not exist . All of the existing clients are either not maintainted or only compatible with SOAP 1.1: * suds * SOAPpy * ZSI
The [zeep](https://github.com/mvantellingen/python-zeep) library supports both SOAP 1.1 and 1.2 as long as the service's WSDL properly indicates it. ~~WSF/Python is supporting SOAP 1.2.~~ > ## INTRODUCTION > > WSF/Python is the Python language extension to WSO2 WSF/C > [<http://www.wso2.org/projects/wsf/c]>. > This v...
SOAP 1.2 python client
2,370,573
13
2010-03-03T11:01:19Z
5,262,037
11
2011-03-10T15:41:42Z
[ "python", "soap" ]
I am looking for a python SOAP 1.2 client but it seems that it does not exist . All of the existing clients are either not maintainted or only compatible with SOAP 1.1: * suds * SOAPpy * ZSI
Even though this question has an accepted answer, there's a few notes I'd like regarding suds. I'm currently writing some code for interfacing with .tel community hosting for work and I needed a Python SOAP library, and suds was pretty much ideal except for its lack of support for SOAP 1.2. I managed to hack around t...
Evaluating a mathematical expression in a string
2,371,436
49
2010-03-03T13:10:39Z
2,371,789
47
2010-03-03T13:52:30Z
[ "python", "math" ]
``` stringExp = "2^4" intVal = int(stringExp) # Expected value: 16 ``` This returns the following error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '2^4' ``` I know that `eval` can work around this, but isn't there a better an...
[Pyparsing](http://pyparsing.wikispaces.com/) can be used to parse mathematical expressions. In particular, [fourFn.py](http://pyparsing.wikispaces.com/file/view/fourFn.py) shows how to parse basic arithmetic expressions. Below, I've rewrapped fourFn into a numeric parser class for easier reuse. ``` from __future__ im...
Evaluating a mathematical expression in a string
2,371,436
49
2010-03-03T13:10:39Z
9,558,001
96
2012-03-04T19:15:26Z
[ "python", "math" ]
``` stringExp = "2^4" intVal = int(stringExp) # Expected value: 16 ``` This returns the following error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '2^4' ``` I know that `eval` can work around this, but isn't there a better an...
## `eval` is evil ``` eval("__import__('os').remove('important file')") # arbitrary commands eval("9**9**9**9**9**9**9**9", {'__builtins__': None}) # CPU, memory ``` Note: even if you use set `__builtins__` to `None` it still might be possible to break out using introspection: ``` eval('(1).__class__.__bases__[0].__...
Evaluating a mathematical expression in a string
2,371,436
49
2010-03-03T13:10:39Z
18,096,137
7
2013-08-07T06:28:40Z
[ "python", "math" ]
``` stringExp = "2^4" intVal = int(stringExp) # Expected value: 16 ``` This returns the following error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: '2^4' ``` I know that `eval` can work around this, but isn't there a better an...
Try [asteval](http://newville.github.io/asteval/) or possibly [numexpr](https://github.com/pydata/numexpr) for possibly safer alternatives to `eval()` and `Sympy.sympify().evalf()`.
Is there a Python version of CPAN?
2,372,445
3
2010-03-03T15:19:38Z
2,372,463
11
2010-03-03T15:21:26Z
[ "python" ]
So I've been using Perl for several years now and I'm starting to dabble a little in Python. Is there a sort of CPAN but for Python? What's the normal way to manage modules in Python? Any direction would be greatly appreciated. FWIW I use Linux so Windows-only solutions aren't really useful to me.
[The repository formerly known as Cheese Shop](http://pypi.python.org/pypi). > ## [PyPI](http://pypi.python.org/pypi) > > The Python Package Index is a repository of software for the Python programming language. There are currently 9140 packages here. To contact the PyPI admins, please use the [Get help](http://source...
How do I remove whitespace from the end of a string in Python?
2,372,573
36
2010-03-03T15:36:14Z
2,372,578
67
2010-03-03T15:37:00Z
[ "python" ]
I need to remove whitespaces after the word in the string. Can this be done in one line of code? Example: ``` string = " xyz " desired result : " xyz" ```
``` >>> " xyz ".rstrip() ' xyz' ``` more about `rstrip` in [docs](http://docs.python.org/library/stdtypes.html#str.rstrip)
Python: Fast querying in a big dbf (xbase) file
2,373,086
5
2010-03-03T16:38:47Z
6,682,426
8
2011-07-13T16:41:05Z
[ "python", "performance", "python-3.x", "dbf", "xbase" ]
I have a big DBF file (~700MB). I'd like to select only a few lines from it using a python script. I've seen that dbfpy is a nice module that allows to open this type of database, but for now I haven't found any querying capability. Iterating through all the elements from python is simply too slow. Can I do what I wan...
Using [my dbf module](http://pypi.python.org/pypi/dbf/) you can create temporary indexes and then search using those: ``` import dbf table = dbf.Table('big.dbf') index = table.create_index(lambda rec: rec.field) # field should be actual field name records = index.search(match=('value',)) ``` Creating the index may ...
Django - Access request.session in form
2,373,867
5
2010-03-03T18:24:01Z
2,374,072
9
2010-03-03T18:52:53Z
[ "python", "django", "django-forms" ]
I am calling a form as follows, then passing it to a template: ``` f = UserProfileConfig(request) ``` I need to be able to access the request.session within the form... so first I tried this: ``` class UserProfileConfig(forms.Form): def __init__(self,request,*args,**kwargs): super (UserProfileConfig,sel...
Try this: ``` class UserProfileConfig(forms.Form): def __init__(self,request,*args,**kwargs): super (UserProfileConfig,self).__init__(*args,**kwargs) self.fields['username'] = forms.CharField(label='Username',max_length=100,initial=request.session['some_var']) ``` I find this article about [dynam...
Set database connection timeout in Python
2,374,079
9
2010-03-03T18:53:49Z
2,976,544
9
2010-06-04T17:54:41Z
[ "python", "database", "oracle", "cx-oracle", "python-db-api" ]
I'm creating a RESTful API which needs to access the database. I'm using Restish, Oracle, and SQLAlchemy. However, I'll try to frame my question as generically as possible, without taking Restish or other web APIs into account. I would like to be able to set a timeout for a connection executing a query. This is to ens...
for the query, you can look on timer and conn.cancel() call. something in those lines: ``` t = threading.Timer(timeout,conn.cancel) t.start() cursor = conn.cursor() cursor.execute(query) res = cursor.fetchall() t.cancel() ```
How can I determine the final URL after redirection using python / urllib2?
2,374,122
4
2010-03-03T18:58:46Z
2,374,160
8
2010-03-03T19:05:14Z
[ "python", "redirect", "urllib2" ]
I need to get the final URL after redirection in python. What's a good way to do that?
``` >>> import urllib2 >>> var = urllib2.urlopen('http://www.stackoverflow.com/') >>> var.geturl() 'http://stackoverflow.com/' ```
Django - Working with multiple forms
2,374,224
21
2010-03-03T19:16:46Z
2,374,240
45
2010-03-03T19:19:38Z
[ "python", "django", "forms", "django-forms" ]
What I'm trying to do is to manage several forms in one page, I know there are formsets, and I know how the form management works, but I got some problems with the idea I have in mind. Just to help you to imagine what my problem is I'm going to use the django example models: ``` from django.db import models class Po...
Use the `prefix` kwarg You can declare your form as: ``` form = MyFormClass(prefix='some_prefix') ``` and then, as long as the prefix is the same, process data as: ``` form = MyFormClass(request.POST, prefix='some_prefix') ``` Django will handle the rest. This way you can have as many forms of the same type as yo...
Is it possible to get sqlalchemy to create a composite primary key with an integer part without making it an IDENTITY type?
2,374,243
7
2010-03-03T19:20:14Z
2,747,823
10
2010-04-30T21:31:55Z
[ "python", "sql-server", "sqlalchemy" ]
I'm using sqlalchemy 6.0. The SQL Server T-SQL dialect seems to want to make any integer that's part of my primary key into an identity. That may be ok if the integer field were the primary key, but mine is a composite and this isn't going to work for me. Is there a way to suppress this behavior? Here's a demonstratio...
I got bit by the same problem. The solution is to add autoincrement=False to the int primary key column constructor: ``` Column(u'int_part', Integer, primary_key=True, nullable=False, autoincrement=False) ``` Otherwise, sqlalchemy assumes it should make it an identity column.
Python 2.x - Write binary output to stdout?
2,374,427
28
2010-03-03T19:47:41Z
2,374,507
22
2010-03-03T20:01:20Z
[ "python", "binary", "stdout" ]
Is there any way to write binary output to sys.stdout in Python 2.x? In Python 3.x, you can just use sys.stdout.buffer (or detach stdout, etc...), but I haven't been able to find any solutions for Python 2.5/2.6. EDIT, **Solution**: From ChristopheD's link, below: ``` import sys if sys.platform == "win32": impor...
Which platform are you on? You could try [this recipe](http://code.activestate.com/recipes/65443-sending-binary-data-to-stdout-under-windows/) if you're on Windows (the link suggests it's Windows specific anyway). ``` if sys.platform == "win32": import os, msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINAR...
How do I calculate percentiles with python/numpy?
2,374,640
100
2010-03-03T20:21:13Z
2,374,662
116
2010-03-03T20:24:34Z
[ "python", "numpy", "percentile" ]
Is there a convenient way to calculate percentiles for a sequence or single-dimensional numpy array? I am looking for something similar to Excel's percentile function. I looked in NumPy's statistics reference, and couldn't find this. All I could find is the median (50th percentile), but not something more specific.
You might be interested in the [SciPy Stats](http://docs.scipy.org/doc/scipy/reference/stats.html) package. It has [the percentile function](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.scoreatpercentile.html#scipy.stats.scoreatpercentile) you're after and many other statistical goodies. `percentile...
How do I calculate percentiles with python/numpy?
2,374,640
100
2010-03-03T20:21:13Z
2,753,343
44
2010-05-02T11:46:20Z
[ "python", "numpy", "percentile" ]
Is there a convenient way to calculate percentiles for a sequence or single-dimensional numpy array? I am looking for something similar to Excel's percentile function. I looked in NumPy's statistics reference, and couldn't find this. All I could find is the median (50th percentile), but not something more specific.
By the way, there is [a pure-Python implementation of percentile function](http://code.activestate.com/recipes/511478-finding-the-percentile-of-the-values/), in case one doesn't want to depend on scipy. The function is copied below: ``` ## {{{ http://code.activestate.com/recipes/511478/ (r1) import math import functoo...
How do I calculate percentiles with python/numpy?
2,374,640
100
2010-03-03T20:21:13Z
17,060,201
21
2013-06-12T07:45:24Z
[ "python", "numpy", "percentile" ]
Is there a convenient way to calculate percentiles for a sequence or single-dimensional numpy array? I am looking for something similar to Excel's percentile function. I looked in NumPy's statistics reference, and couldn't find this. All I could find is the median (50th percentile), but not something more specific.
``` import numpy as np a = [154, 400, 1124, 82, 94, 108] print np.percentile(a,95) # gives the 95th percentile ```
Python Type Conversion
2,375,334
10
2010-03-03T22:00:59Z
2,375,344
37
2010-03-03T22:02:57Z
[ "python", "types", "int" ]
Whats the best way to convert int's, long's, double's to strings and vice versa in python. I am looping through a list and passing longs to a dict that should be turned into a unicode string. I do ``` for n in l: {'my_key':n[0],'my_other_key':n[1]} ``` Why are some of the most obvious things so complicated?
To convert from a numeric type to a string: ``` str(100) ``` To convert from a string to an int: ``` int("100") ``` To convert from a string to a float: ``` float("100") ```
In Django, how do I clear a sessionkey?
2,375,335
16
2010-03-03T22:01:24Z
2,375,362
35
2010-03-03T22:06:23Z
[ "python", "django", "session" ]
I set a session like this: ``` request.session['mykey']= 33 ``` How do I clear it? I just want to DELETE it.
``` del request.session['mykey'] ```
How does one monkey patch a function in python?
2,375,403
50
2010-03-03T22:11:38Z
2,375,443
54
2010-03-03T22:19:45Z
[ "python", "monkeypatching" ]
I'm having trouble replacing a function from a different module with another function and it's driving me crazy. Let's say I have a module bar.py that looks like this: ``` from a_package.baz import do_something_expensive def a_function(): print do_something_expensive() ``` And I have another module that looks l...
It may help to think of how Python namespaces work: they're essentially dictionaries. So when you do this: ``` from a_package.baz import do_something_expensive do_something_expensive = lambda: 'Something really cheap.' ``` think of it like this: ``` do_something_expensive = a_package.baz['do_something_expensive'] do...
How does one monkey patch a function in python?
2,375,403
50
2010-03-03T22:11:38Z
2,375,450
16
2010-03-03T22:20:30Z
[ "python", "monkeypatching" ]
I'm having trouble replacing a function from a different module with another function and it's driving me crazy. Let's say I have a module bar.py that looks like this: ``` from a_package.baz import do_something_expensive def a_function(): print do_something_expensive() ``` And I have another module that looks l...
There's a really elegant decorator for this: [Guido van Rossum: Python-Dev list: Monkeypatching Idioms](http://mail.python.org/pipermail/python-dev/2008-January/076194.html). There's also the [dectools](http://pypi.python.org/pypi/dectools/0.1.3) package, which I saw an PyCon 2010, which may be able to be used in this...
C#: Equivalent of the python try/catch/else block
2,375,794
6
2010-03-03T23:20:46Z
2,375,860
7
2010-03-03T23:31:40Z
[ "c#", "python", "exception", "try-catch" ]
In Python, there is this useful exception handling code: ``` try: # Code that could raise an exception except Exception: # Exception handling else: # Code to execute if the try block DID NOT fail ``` I think it's useful to be able to separate the code that *could* raise and exception from your normal code...
I would prefer to see the rest of the code outside the try/catch so it is clear where the exception you are trying to catch is coming from and that you don't accidentally catch an exception that you weren't trying to catch. I think the closest equivalent to the Python try/catch/else is to use a local boolean variable ...
Getting rid of Django IOErrors
2,375,950
6
2010-03-03T23:51:00Z
10,284,097
10
2012-04-23T16:05:21Z
[ "python", "django", "logging" ]
I'm running a Django site (via Apache/mod\_python) and I use Django's facilities to inform me and other developers about internal server errors. Sometimes errors like those appear: ``` Traceback (most recent call last): File "/opt/webapp/externals/lib/django/core/handlers/base.py", line 92, in get_response resp...
Extending the solution by @dlowe for Django 1.3, we can write the full working example as: # settings.py ``` LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'supress_unreadable_post': { '()': 'common.logging.SuppressUnreadablePost', } }, 'handl...
TypeError: unsupported operand type(s) for -: 'str' and 'int'
2,376,464
19
2010-03-04T02:13:23Z
2,376,520
25
2010-03-04T02:31:46Z
[ "python", "python-3.x" ]
New to python and programing how come I'm getting this error? ``` def cat_n_times(s, n): while s != 0: print(n) s = s - 1 text = input("What would you like the computer to repeat back to you: ") num = input("How many times: ") cat_n_times(num, text) ```
1. The reason this is failing is because (Python 3) `input` returns a string. To convert it to an integer, use `int(some_string)`. 2. You do not typically keep track of indices manually in Python. A better way to implement such a function would be ``` def cat_n_times(s, n): for i in range(n): p...
TypeError: unsupported operand type(s) for -: 'str' and 'int'
2,376,464
19
2010-03-04T02:13:23Z
2,376,563
17
2010-03-04T02:46:24Z
[ "python", "python-3.x" ]
New to python and programing how come I'm getting this error? ``` def cat_n_times(s, n): while s != 0: print(n) s = s - 1 text = input("What would you like the computer to repeat back to you: ") num = input("How many times: ") cat_n_times(num, text) ```
For future reference Python is [strongly typed](http://wiki.python.org/moin/Why%20is%20Python%20a%20dynamic%20language%20and%20also%20a%20strongly%20typed%20language). Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from `str` to `int`) so you must do this yourself...
Python: How to refactor this simple list code?
2,376,833
2
2010-03-04T04:13:55Z
2,376,848
7
2010-03-04T04:18:16Z
[ "python", "google-app-engine", "code-review" ]
I'm new to Python. Am I doing it right? The goal: 1. Get a bunch of `InCart` objects from Google App Engine's datastore that corresponds to the current user. Each `InCart` item has two attributes: `InCart.owner` and `InCart.item` 2. Provide the templating engine a set of items in any `InCart.item` ...
For: ``` items = [] for entry in cartEntries: items.append(entry.item) ``` you could use a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions): ``` items = [entry.item for entry in cartEntries] ``` Seasoned Python programmers find it easier to read and it's fewer lines.
Which key/value store is the most promising/stable?
2,376,846
58
2010-03-04T04:17:12Z
2,376,875
7
2010-03-04T04:25:30Z
[ "python", "ruby", "database", "comparison" ]
I'm looking to start using a key/value store for some side projects (mostly as a learning experience), but so many have popped up in the recent past that I've got no idea where to begin. Just listing from memory, I can think of: 1. CouchDB 2. MongoDB 3. Riak 4. Redis 5. Tokyo Cabinet 6. Berkeley DB 7. Cassandra 8. Mem...
They all have different features. And don't forget [Project Voldemort](http://project-voldemort.com/) which is actually used/tested by LinkedIn in their production before each release. It's hard to compare. You have to ask yourself what you need: e.g. do you want partitioning? if so then some of them, like CouchDB, wo...
Which key/value store is the most promising/stable?
2,376,846
58
2010-03-04T04:17:12Z
2,377,117
26
2010-03-04T05:35:50Z
[ "python", "ruby", "database", "comparison" ]
I'm looking to start using a key/value store for some side projects (mostly as a learning experience), but so many have popped up in the recent past that I've got no idea where to begin. Just listing from memory, I can think of: 1. CouchDB 2. MongoDB 3. Riak 4. Redis 5. Tokyo Cabinet 6. Berkeley DB 7. Cassandra 8. Mem...
> Which do you recommend, and why? I recommend Redis. Why? Continue reading!! > Which one is the fastest? I can't say whether it's the fastest. But Redis is [fast](http://redis.io/topics/benchmarks). It's fast because it holds all the data in RAM. Recently, virtual memory feature was added but still all the keys sta...
Which key/value store is the most promising/stable?
2,376,846
58
2010-03-04T04:17:12Z
2,380,691
8
2010-03-04T16:00:23Z
[ "python", "ruby", "database", "comparison" ]
I'm looking to start using a key/value store for some side projects (mostly as a learning experience), but so many have popped up in the recent past that I've got no idea where to begin. Just listing from memory, I can think of: 1. CouchDB 2. MongoDB 3. Riak 4. Redis 5. Tokyo Cabinet 6. Berkeley DB 7. Cassandra 8. Mem...
At this year's PyCon, Jeremy Edberg of Reddit gave a talk: <http://pycon.blip.tv/file/3257303/> He said that Reddit uses PostGres as a key-value store, presumably with a simple 2-column table; according to his talk it had benchmarked faster than any other key-value store they had tried. And, of course, it's very matu...
Which key/value store is the most promising/stable?
2,376,846
58
2010-03-04T04:17:12Z
2,380,871
7
2010-03-04T16:24:34Z
[ "python", "ruby", "database", "comparison" ]
I'm looking to start using a key/value store for some side projects (mostly as a learning experience), but so many have popped up in the recent past that I've got no idea where to begin. Just listing from memory, I can think of: 1. CouchDB 2. MongoDB 3. Riak 4. Redis 5. Tokyo Cabinet 6. Berkeley DB 7. Cassandra 8. Mem...
I've been playing with MongoDB and it has one thing that makes it perfect for my application, the ability to store complex Maps/Lists in the database directly. I have a large Map where each value is a list and I don't have to do anything special just to write and retrieve that without knowing all the different keys and...
Which key/value store is the most promising/stable?
2,376,846
58
2010-03-04T04:17:12Z
2,616,225
24
2010-04-11T06:22:26Z
[ "python", "ruby", "database", "comparison" ]
I'm looking to start using a key/value store for some side projects (mostly as a learning experience), but so many have popped up in the recent past that I've got no idea where to begin. Just listing from memory, I can think of: 1. CouchDB 2. MongoDB 3. Riak 4. Redis 5. Tokyo Cabinet 6. Berkeley DB 7. Cassandra 8. Mem...
You need to understand what modern NoSQL phenomenon is about. It is not about key-value storages. They've been available for decades (BerkeleyDB for example). Why all the fuss now ? It is not about fancy document or object oriented schemas and overcoming "impedance mismatch". Proponents of these features have been ...
How to write a python script to manipulate google spreadsheet data
2,377,301
5
2010-03-04T06:32:05Z
8,468,493
21
2011-12-11T23:55:10Z
[ "python", "google-spreadsheet", "gspread" ]
I am able to get the feed from the spreadsheet and worksheet ID. I want to capture the data from each cell. i.e, I am able to get the feed from the worksheet. Now I need to get data(string type?) from each of the cells to make a comparison and for input. How exactly can I do that?
There's another [spreadsheet library](https://github.com/burnash/gspread) worth to look at: gspread. I've used Google's data libary mentioned above and to me the provided api is weird. You need to extract spreadsheet's key to start working with this spreadsheet. Here it's a way simpler. If you need to fetch the data f...
deprecation of apply decorator
2,377,573
7
2010-03-04T07:40:50Z
2,377,983
12
2010-03-04T09:09:25Z
[ "python" ]
There was a beautiful way to organize class property in frame of one function, by using the apply decorator. ``` class Example(object): @apply def myattr(): doc = """This is the doc string.""" def fget(self): return self._half * 2 def fset(self, value): self._h...
> Is there any possibility to achieve such simplicity and readability for property The new Python 2.6 way is: ``` @property def myattr(self): """This is the doc string.""" return self._half * 2 @myattr.setter def myattr(self, value): self._half = value / 2 @myattr.deleter def myattr(self): del self....
Rendering mathematical notation in Python / OpenGL?
2,377,944
3
2010-03-04T08:59:07Z
2,377,956
8
2010-03-04T09:02:04Z
[ "python", "math", "opengl", "rendering", "pyglet" ]
How can I render mathematical notations / expressions in Python with OpenGL? I'm actually using [pyglet](http://www.pyglet.org/) however it uses OpenGL. Such things as [this](http://en.wikipedia.org/wiki/Quadratic_formula#Quadratic_formula): ![Quadratic formula](http://upload.wikimedia.org/math/3/e/a/3ea647783b51219...
I would say generate suitable [latex](http://en.wikipedia.org/wiki/LaTeX) expression, rendering it into an image, then load the image as a texture.
Tab not working properly in Python
2,378,119
3
2010-03-04T09:35:00Z
2,378,139
7
2010-03-04T09:39:08Z
[ "python", "eclipse", "eclipse-plugin", "pydev" ]
I have been using NotePAD++ for editing Python scripts. I recently downloaded the PyDEV IDE (for Eclipse). The problem is that when I wrote the scripts in NotePad++ I used "TAB" for indentation, and now when I open them with PyDEV, every time I try to write a new line instead of "TABS" PyDEV inserts spaces. (even if I ...
Yes, follow <http://www.python.org/dev/peps/pep-0008/> which states: > Indentation > > ``` > Use 4 spaces per indentation level. > ``` Replace all your tabs with spaces, and set Notepad++ to use spaces instead of tabs. Setting Eclipse to use tabs instead of spaces would be a step in the wrong direction.
Why does nose finds tests in files with only 644 permission?
2,378,146
7
2010-03-04T09:40:02Z
2,378,714
9
2010-03-04T11:08:42Z
[ "python", "permissions", "nose", "doctest" ]
Today I ran a bunch of doctests using Python 2.6 on a Ubuntu 9.10 with nose : ``` nosetests --with-doctest Ran 0 tests in 0.001s OK ``` WTF? I had tests in that files, why didn't that work? I changed permission to 644: ``` sudo chmod 644 * -R nosetests --with-doctest Ran 11 test in 0.004s FAILED (errors=1) ``` C...
Try the `--exe` flag: ``` $ nosetests --help ... --exe Look for tests in python modules that are executable. Normal behavior is to exclude executable modules, since they may not be import-safe [NOSE_INCLUDE_EXE] ```
Returning the lowest index for the first non whitespace character in a string in Python
2,378,962
7
2010-03-04T11:47:00Z
2,378,988
25
2010-03-04T11:51:32Z
[ "python", "string", "string-matching" ]
What's the shortest way to do this in Python? ``` string = " xyz" ``` must return index = 3
``` >>> s = " xyz" >>> len(s) - len(s.lstrip()) 3 ```
Python AST processing
2,379,355
5
2010-03-04T12:52:52Z
2,380,672
14
2010-03-04T15:58:08Z
[ "python", "abstract-syntax-tree" ]
I have a Python AST [as returned by ast.parse()]. I know this is an AST of a class method. How do I find all calls to other methods of the same class? Basically, I want to collect something like: ``` ['foo', 'bar'] ``` for a code snippet like: ``` def baz(self): # this is a class method '''baz docstring''' ...
The general approach is to subclass [`ast.NodeVisitor`](http://docs.python.org/library/ast.html?highlight=ast#ast.NodeVisitor): ``` >>> class VisitCalls(ast.NodeVisitor): ... def visit_Call(self, what): ... if what.func.value.id == 'self': ... print what.func.attr ... >>> f='''def x(self): ... return se...
Django Admin filter on Foreign Key property
2,379,702
13
2010-03-04T13:49:50Z
7,841,996
11
2011-10-20T20:43:36Z
[ "python", "django", "filter", "admin" ]
I want to add a filter in an admin changelist by a property of a foreign key, e.g. ``` class Address(model.Models): street = models.CharField(max_length=25) city = models.CharField(max_length=25) country = models.CharField(max_length=25) class Customer(models.Model): name = models.Char...
See <https://code.djangoproject.com/ticket/3400> . It works ok in django 1.3 :) ``` class Room(models.Model): house = models.ForeignKey(House) def __unicode__(self): return self.house.town.name class Booking(models.Model): room = models.ForeignKey(Room) def __unicode__(self): return ...
Make distutils look for numpy header files in the correct place
2,379,898
32
2010-03-04T14:17:13Z
2,379,912
47
2010-03-04T14:19:16Z
[ "python", "numpy", "distutils", "cython" ]
In my installation, numpy's `arrayobject.h` is located at `…/site-packages/numpy/core/include/numpy/arrayobject.h`. I wrote a trivial Cython script that uses numpy: ``` cimport numpy as np def say_hello_to(name): print("Hello %s!" % name) ``` I also have the following distutils `setup.py` (copied from the [Cyt...
Use `numpy.get_include()`: ``` from distutils.core import setup from distutils.extension import Extension from Cython.Distutils import build_ext import numpy as np # <---- New line ext_modules = [Extension("hello", ["hello.pyx"])] setup( name = 'Hello world app', cmdclass = {'build_ext'...
Converting date/time in YYYYMMDD/HHMMSS format to Python datetime
2,380,013
12
2010-03-04T14:33:25Z
2,380,078
29
2010-03-04T14:41:10Z
[ "python", "datetime" ]
I have a date in YYYYMMDD format and a time in HHMMSS format as strings in the 4th and 5th elements in a list. I.E.: ``` data[4] = '20100304' data[5] = '082835' ``` I am creating an instance of datetime (in a field named generates) like this: ``` generatedtime = datetime.datetime(int(data[4][:4]),int(data[4][4:6]),i...
No need to import `time`; [`datetime.datetime.strptime`](http://docs.python.org/library/datetime.html#datetime.datetime.strptime) can do it by itself. ``` import datetime dt=datetime.datetime.strptime(data[4]+data[5],'%Y%m%d%H%M%S') print(dt) # 2010-03-04 08:28:35 ``` For information on the format codes (e.g. `%Y%m%d...
How to identify what function call raise an exception in Python?
2,380,073
2
2010-03-04T14:40:42Z
2,380,096
8
2010-03-04T14:43:21Z
[ "python", "exception" ]
i need to identify who raise an exception to handle better str error, is there a way ? look at my example: ``` try: os.mkdir('/valid_created_dir') os.listdir('/invalid_path') except OSError, msg: # here i want i way to identify who raise the exception if is_mkdir_who_raise_an_exception: do some thi...
Wrap in "try/catch" each function individually. ``` try: os.mkdir('/valid_created_dir') except Exception,e: ## doing something, ## quite probably skipping the next try statement try: os.listdir('/invalid_path') except OSError, msg: ## do something ``` This will help readability/comprehension anyways.
How to identify what function call raise an exception in Python?
2,380,073
2
2010-03-04T14:40:42Z
2,380,177
7
2010-03-04T14:53:29Z
[ "python", "exception" ]
i need to identify who raise an exception to handle better str error, is there a way ? look at my example: ``` try: os.mkdir('/valid_created_dir') os.listdir('/invalid_path') except OSError, msg: # here i want i way to identify who raise the exception if is_mkdir_who_raise_an_exception: do some thi...
If you have completely separate tasks to execute depending on which function failed, as your code seems to show, then separate try/exec blocks, as the existing answers suggest, may be better (though you may probably need to skip the second part if the first one has failed). If you have many things that you need to do ...
Simple implementation of N-Gram, tf-idf and Cosine similarity in Python
2,380,394
38
2010-03-04T15:22:30Z
2,754,261
42
2010-05-02T17:20:58Z
[ "python", "document", "n-gram", "tf-idf", "vsm" ]
I need to compare documents stored in a DB and come up with a similarity score between 0 and 1. The method I need to use has to be very simple. Implementing a vanilla version of n-grams (where it possible to define how many grams to use), along with a simple implementation of tf-idf and Cosine similarity. Is there an...
Check out NLTK package: <http://www.nltk.org> it has everything what you need For the cosine\_similarity: ``` def cosine_distance(u, v): """ Returns the cosine of the angle between vectors v and u. This is equal to u.v / |u||v|. """ return numpy.dot(u, v) / (math.sqrt(numpy.dot(u, u)) * math.sqrt(...
Simple implementation of N-Gram, tf-idf and Cosine similarity in Python
2,380,394
38
2010-03-04T15:22:30Z
7,856,554
16
2011-10-22T00:11:07Z
[ "python", "document", "n-gram", "tf-idf", "vsm" ]
I need to compare documents stored in a DB and come up with a similarity score between 0 and 1. The method I need to use has to be very simple. Implementing a vanilla version of n-grams (where it possible to define how many grams to use), along with a simple implementation of tf-idf and Cosine similarity. Is there an...
If you are interested, I've done tutorial series ([Part I](http://blog.christianperone.com/?p=1589) and [Part II](http://blog.christianperone.com/?p=1747)) talking about tf-idf and using the [Scikits.learn (sklearn)](http://scikit-learn.sourceforge.net/stable/) Python module.
Django doctests in views.py
2,380,527
20
2010-03-04T15:39:23Z
3,030,065
20
2010-06-12T20:59:57Z
[ "python", "django", "unit-testing", "doctest" ]
The Django 1.4 [documentation on tests](https://docs.djangoproject.com/en/1.4/topics/testing/#writing-doctests) states: > For a given Django application, the test runner looks for doctests in two places: > > * The `models.py` file. You can define module-level doctests and/or a doctest for individual models. It's commo...
You can do this by adding/editing the suite() function in tests.py which defines what tests will be run by the django test runner. ``` import unittest import doctest from project import views def suite(): suite = unittest.TestSuite() suite.addTest(doctest.DocTestSuite(views)) return suite ``` Then just r...
Django doctests in views.py
2,380,527
20
2010-03-04T15:39:23Z
4,816,284
7
2011-01-27T12:28:07Z
[ "python", "django", "unit-testing", "doctest" ]
The Django 1.4 [documentation on tests](https://docs.djangoproject.com/en/1.4/topics/testing/#writing-doctests) states: > For a given Django application, the test runner looks for doctests in two places: > > * The `models.py` file. You can define module-level doctests and/or a doctest for individual models. It's commo...
This is my `tests/__init__.py` implementation, based on [Jesse Shieh answer](http://stackoverflow.com/questions/2380527/django-doctests-in-views-py/3030065#3030065): ``` import doctest import unittest list_of_doctests = [ 'myapp.views.myview', 'myapp.forms.myform', ] list_of_unittests = [ 'sometestshere',...
Django doctests in views.py
2,380,527
20
2010-03-04T15:39:23Z
20,564,401
11
2013-12-13T10:39:17Z
[ "python", "django", "unit-testing", "doctest" ]
The Django 1.4 [documentation on tests](https://docs.djangoproject.com/en/1.4/topics/testing/#writing-doctests) states: > For a given Django application, the test runner looks for doctests in two places: > > * The `models.py` file. You can define module-level doctests and/or a doctest for individual models. It's commo...
Things have [changed in Django 1.6](https://docs.djangoproject.com/en/dev/releases/1.6/#new-test-runner): > Doctests will no longer be automatically discovered. To integrate > doctests in your test suite, follow the [recommendations in the Python > documentation](http://docs.python.org/2/library/doctest.html#unittest-...
Redirect Python standard input/output to C# forms application
2,380,649
4
2010-03-04T15:55:01Z
2,381,182
13
2010-03-04T17:06:26Z
[ "c#", "python", "redirect", "stdout", "stdin" ]
I apologize if this is a duplicate question, I searched a bit and couldn't find anything similar - I have a Python library that connects to my C# application via a socket in order to allow simple Python scripting (IronPython isn't an option right now for a couple of reasons). I would like to create a Windows Forms cont...
In case anyone else stumbles across this, I figured out the problem - by default, the Python interpreter only enters interactive mode if it detects that a TTY device is connected to standard input (which is normally only true if the program is run from the console). In order to redirect the standard IO streams, you hav...
set() runtime in python
2,381,026
5
2010-03-04T16:45:30Z
2,381,054
7
2010-03-04T16:48:52Z
[ "python" ]
Just wondering what the run time of lookup for set() is? O(1) or O(n)? if I have x = set() whats the runtime of if "a" in x: print a in set!
`set` is implemented using a hash, so the lookup is, on average, close to O(1). The worst case is O(n), where n objects have colliding hashes.
How to get the Python date object for last Wednesday
2,381,786
12
2010-03-04T18:36:55Z
2,382,238
33
2010-03-04T19:46:41Z
[ "python", "datetime", "date" ]
Using Python I would like to find the date object for last Wednesday. I can figure out where today is on the calendar using isocalendar, and determine whether or not we need to go back a week to get to the previous Wednesday. However, I can't figure out how to create a new date object with that information. Essentially...
I think you want this. If the specified day is a Wednesday it will give you that day. ``` from datetime import date from datetime import timedelta today = date.today() offset = (today.weekday() - 2) % 7 last_wednesday = today - timedelta(days=offset) ``` Example, the last wednesday for every day in March: ``` for x...