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
Python Leave Loop Early
2,184,287
18
2010-02-02T13:23:46Z
2,184,298
11
2010-02-02T13:25:58Z
[ "python", "loops" ]
How do I leave a loop early in python? ``` for a in b: if criteria in list1: print "oh no" #Force loop i.e. force next iteration without going on someList.append(a) ``` Also, in java you can `break` out of a loop, is there an equivalent in Python?
Firstly, bear in mind it might be possible to do what you want with a list comprehension. So you might be able to use something like: ``` somelist = [a for a in b if not a.criteria in otherlist] ``` If you want to leave a loop early in Python you can use `break`, just like in Java. ``` >>> for x in xrange(1,6): ... ...
How to get the most represented object from an array
2,184,336
3
2010-02-02T13:33:04Z
2,185,297
8
2010-02-02T15:41:05Z
[ "python", "algorithm", "arrays", "performance", "list" ]
I have an array with some objects, and there are several objects that are alike. E.g: fruit = [apple, orange, apple, banana, banana, orange, apple, apple] What is the most efficient way to get the most represented object from this array? In this case it would be "apple" but how would you go out and calculate that in a...
Don't reinvent the wheel. In Python 2.7+ you can use [the Counter class](http://docs.python.org/dev/library/collections.html#collections.Counter): ``` import collections fruit=['apple', 'orange', 'apple', 'banana', 'banana', 'orange', 'apple', 'apple'] c=collections.Counter(fruit) print(c.most_common(1)) # [('apple', ...
Python thinks a 3000-line text file is one line long?
2,184,543
11
2010-02-02T14:05:34Z
2,184,586
24
2010-02-02T14:12:24Z
[ "python", "text", "character-encoding", "newline" ]
I have a very long text file that I'm trying to process using Python. However, the following code: ``` for line in open('textbase.txt', 'r'): print 'hello world' ``` produces only the following output: ``` hello world ``` It's as though Python thinks the file is only one line long, though it is many thousands ...
According to the [documentation for `open()`](http://docs.python.org/library/functions.html#open), you should add a `U` to the mode: ``` open('textbase.txt', 'Ur') ``` This enables "[universal newlines](http://www.python.org/dev/peps/pep-0278/)", which normalizes them to `\n` in the strings it gives you. However, th...
Even numbers in Python
2,184,745
9
2010-02-02T14:32:30Z
2,184,764
31
2010-02-02T14:34:56Z
[ "python", "range" ]
Does anyone know if Python has an in-built function to work to print out even values. Like range() for example. Thanks
[Range has three parameters.](http://docs.python.org/library/functions.html#range) You can write `range(0, 10, 2)`.
Test if a variable is a list or tuple
2,184,955
115
2010-02-02T15:00:23Z
2,184,979
15
2010-02-02T15:03:24Z
[ "python", "types", "list" ]
In python, what's the best way to test if a variable contains a list or a tuple? (ie. a collection) Is isinstance as evil as suggested here? <http://www.canonical.org/~kragen/isinstance/> Update : the most common reason I want to distinguish a list from a string is when I have some indefinitely deep nested tree / dat...
Document the argument as needing to be a sequence, and use it as a sequence. Don't check the type.
Test if a variable is a list or tuple
2,184,955
115
2010-02-02T15:00:23Z
2,185,098
28
2010-02-02T15:19:27Z
[ "python", "types", "list" ]
In python, what's the best way to test if a variable contains a list or a tuple? (ie. a collection) Is isinstance as evil as suggested here? <http://www.canonical.org/~kragen/isinstance/> Update : the most common reason I want to distinguish a list from a string is when I have some indefinitely deep nested tree / dat...
There's nothing wrong with using `isinstance` as long as it's not redundant. If a variable should only be a list/tuple then document the interface and just use it as such. Otherwise a check is perfectly reasonable: ``` if isinstance(a, collections.Iterable): # use as a container else: # not a container! ``` T...
Test if a variable is a list or tuple
2,184,955
115
2010-02-02T15:00:23Z
2,185,198
53
2010-02-02T15:29:58Z
[ "python", "types", "list" ]
In python, what's the best way to test if a variable contains a list or a tuple? (ie. a collection) Is isinstance as evil as suggested here? <http://www.canonical.org/~kragen/isinstance/> Update : the most common reason I want to distinguish a list from a string is when I have some indefinitely deep nested tree / dat...
Go ahead and use `isinstance` if you need it. It is somewhat evil, as it excludes custom sequences, iterators, and other things that you might actually need. However, sometimes you need to behave differently if someone, for instance, passes a string. My preference there would be to explicitly check for `str` or `unicod...
Test if a variable is a list or tuple
2,184,955
115
2010-02-02T15:00:23Z
4,507,292
8
2010-12-22T08:11:03Z
[ "python", "types", "list" ]
In python, what's the best way to test if a variable contains a list or a tuple? (ie. a collection) Is isinstance as evil as suggested here? <http://www.canonical.org/~kragen/isinstance/> Update : the most common reason I want to distinguish a list from a string is when I have some indefinitely deep nested tree / dat...
``` >>> l = [] >>> l.__class__.__name__ in ('list', 'tuple') True ```
Test if a variable is a list or tuple
2,184,955
115
2010-02-02T15:00:23Z
8,236,234
257
2011-11-23T01:25:17Z
[ "python", "types", "list" ]
In python, what's the best way to test if a variable contains a list or a tuple? (ie. a collection) Is isinstance as evil as suggested here? <http://www.canonical.org/~kragen/isinstance/> Update : the most common reason I want to distinguish a list from a string is when I have some indefinitely deep nested tree / dat...
``` if type(x) is list: print 'a list' elif type(x) is tuple: print 'a tuple' else: print 'neither a tuple or a list' ```
Test if a variable is a list or tuple
2,184,955
115
2010-02-02T15:00:23Z
15,348,388
8
2013-03-11T20:53:16Z
[ "python", "types", "list" ]
In python, what's the best way to test if a variable contains a list or a tuple? (ie. a collection) Is isinstance as evil as suggested here? <http://www.canonical.org/~kragen/isinstance/> Update : the most common reason I want to distinguish a list from a string is when I have some indefinitely deep nested tree / dat...
How about: `hasattr(a, "__iter__")` ? It tells if the object returned can be iterated over as a generator. By default, tuples and lists can, but not the string types.
Writing Python packages with multiple C modules
2,185,197
9
2010-02-02T15:29:57Z
2,185,588
14
2010-02-02T16:15:28Z
[ "python", "module", "organization" ]
I am writing a Python C extension which uses the pygame C API. So far so good. Now I wonder how I organize my source code so that I can have multiple submodules in the package. All the tutorials out there focus on one .c file extensions. I tried looking at some projects setup.py files but they blew my mind with complex...
I think the easiest way to do this would be to create the package in "pure python"; in other words, create `mypackage/`, create an empty `mypackage/__init__.py` , and then put your extension modules at `mypackage/module1.so`, `mypackage/module2.so`, and so on. If you want things in `mypackage` instead of it being empt...
Images caching in browser - app-engine-patch aplication
2,185,449
4
2010-02-02T15:58:54Z
2,200,653
7
2010-02-04T15:04:57Z
[ "python", "google-app-engine", "browser", "caching", "app-engine-patch" ]
I have a little problem with caching the images in the browser for my app-engine aplication I`m sending last-modified, expires and cache-control headers but image is loaded from the server every time. Here is the header part of the code: response['Content-Type'] = 'image/jpg' response['Last-Modified'] = current\_time...
Here is an example code for my fix copy in dpaste [here](http://dpaste.com/hold/154503/) ``` def view_image(request, key): data = memcache.get(key) if data is not None: if(request.META.get('HTTP_IF_MODIFIED_SINCE') >= data['Last-Modified']): data.status_code = 304 return data else: ...
Use a Glob() to find files recursively in Python?
2,186,525
313
2010-02-02T18:19:50Z
2,186,555
14
2010-02-02T18:24:48Z
[ "python", "path", "glob" ]
This is what I have: ``` glob(os.path.join('src','*.c')) ``` but I want to search the subfolders of src. Something like this would work: ``` glob(os.path.join('src','*.c')) glob(os.path.join('src','*','*.c')) glob(os.path.join('src','*','*','*.c')) glob(os.path.join('src','*','*','*','*.c')) ``` But this is obvious...
You'll want to use `os.walk` to collect filenames that match your criteria. For example: ``` import os cfiles = [] for root, dirs, files in os.walk('src'): for file in files: if file.endswith('.c'): cfiles.append(os.path.join(root, file)) ```
Use a Glob() to find files recursively in Python?
2,186,525
313
2010-02-02T18:19:50Z
2,186,565
610
2010-02-02T18:26:54Z
[ "python", "path", "glob" ]
This is what I have: ``` glob(os.path.join('src','*.c')) ``` but I want to search the subfolders of src. Something like this would work: ``` glob(os.path.join('src','*.c')) glob(os.path.join('src','*','*.c')) glob(os.path.join('src','*','*','*.c')) glob(os.path.join('src','*','*','*','*.c')) ``` But this is obvious...
**Python 3.5+** Starting with Python version 3.5, the [`glob`](https://docs.python.org/3/library/glob.html) module supports the `"**"` directive (which is parsed only if you pass `recursive` flag): ``` import glob for filename in glob.iglob('src/**/*.c', recursive=True): print(filename) ``` If you need an list,...
Use a Glob() to find files recursively in Python?
2,186,525
313
2010-02-02T18:19:50Z
2,186,639
29
2010-02-02T18:39:38Z
[ "python", "path", "glob" ]
This is what I have: ``` glob(os.path.join('src','*.c')) ``` but I want to search the subfolders of src. Something like this would work: ``` glob(os.path.join('src','*.c')) glob(os.path.join('src','*','*.c')) glob(os.path.join('src','*','*','*.c')) glob(os.path.join('src','*','*','*','*.c')) ``` But this is obvious...
``` import os import fnmatch def recursive_glob(treeroot, pattern): results = [] for base, dirs, files in os.walk(treeroot): goodfiles = fnmatch.filter(files, pattern) results.extend(os.path.join(base, f) for f in goodfiles) return results ``` [`fnmatch`](http://docs.python.org/library/fn...
Use a Glob() to find files recursively in Python?
2,186,525
313
2010-02-02T18:19:50Z
2,186,673
80
2010-02-02T18:44:51Z
[ "python", "path", "glob" ]
This is what I have: ``` glob(os.path.join('src','*.c')) ``` but I want to search the subfolders of src. Something like this would work: ``` glob(os.path.join('src','*.c')) glob(os.path.join('src','*','*.c')) glob(os.path.join('src','*','*','*.c')) glob(os.path.join('src','*','*','*','*.c')) ``` But this is obvious...
Similar to other solutions, but using fnmatch.fnmatch instead of glob, since os.walk already listed the filenames: ``` import os, fnmatch def find_files(directory, pattern): for root, dirs, files in os.walk(directory): for basename in files: if fnmatch.fnmatch(basename, pattern): ...
Use a Glob() to find files recursively in Python?
2,186,525
313
2010-02-02T18:19:50Z
6,484,486
31
2011-06-26T14:14:22Z
[ "python", "path", "glob" ]
This is what I have: ``` glob(os.path.join('src','*.c')) ``` but I want to search the subfolders of src. Something like this would work: ``` glob(os.path.join('src','*.c')) glob(os.path.join('src','*','*.c')) glob(os.path.join('src','*','*','*.c')) glob(os.path.join('src','*','*','*','*.c')) ``` But this is obvious...
I've modified the glob module to support \*\* for recursive globbing, e.g: ``` >>> import glob2 >>> all_header_files = glob2.glob('src/**/*.c') ``` <https://github.com/miracle2k/python-glob2/> Useful when you want to provide your users with the ability to use the \*\* syntax, and thus os.walk() alone is not good eno...
Use a Glob() to find files recursively in Python?
2,186,525
313
2010-02-02T18:19:50Z
7,977,340
10
2011-11-02T08:10:45Z
[ "python", "path", "glob" ]
This is what I have: ``` glob(os.path.join('src','*.c')) ``` but I want to search the subfolders of src. Something like this would work: ``` glob(os.path.join('src','*.c')) glob(os.path.join('src','*','*.c')) glob(os.path.join('src','*','*','*.c')) glob(os.path.join('src','*','*','*','*.c')) ``` But this is obvious...
Here's a solution with nested list comprehensions, `os.walk` and simple suffix matching instead of `glob`: ``` import os cfiles = [os.path.join(root, filename) for root, dirnames, filenames in os.walk('src') for filename in filenames if filename.endswith('.c')] ``` It can be compressed to a one-li...
Use a Glob() to find files recursively in Python?
2,186,525
313
2010-02-02T18:19:50Z
26,869,233
24
2014-11-11T16:08:39Z
[ "python", "path", "glob" ]
This is what I have: ``` glob(os.path.join('src','*.c')) ``` but I want to search the subfolders of src. Something like this would work: ``` glob(os.path.join('src','*.c')) glob(os.path.join('src','*','*.c')) glob(os.path.join('src','*','*','*.c')) glob(os.path.join('src','*','*','*','*.c')) ``` But this is obvious...
Starting with Python 3.4, one can use the [`glob()`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob) method of one of the `Path` classes in the new [pathlib](https://docs.python.org/3/library/pathlib.html) module, which supports `**` wildcards. For example: ``` from pathlib import Path for file_path...
Getting correct string length in Python for strings with ANSI color codes
2,186,919
12
2010-02-02T19:18:36Z
2,187,024
7
2010-02-02T19:33:30Z
[ "python", "escaping", "ansi-colors" ]
I've got some Python code that will automatically print a set of data in a nice column format, including putting in the appropriate ASCII escape sequences to color various pieces of the data for readability. I eventually end up with each line being represented as a list, with each item being a column that is space-pad...
The pyparsing wiki includes this [helpful expression](http://pyparsing-public.wikispaces.com/Helpful+Expressions#toc7) for matching on ANSI escape sequences: ``` ESC = Literal('\x1b') integer = Word(nums) escapeSeq = Combine(ESC + '[' + Optional(delimitedList(integer,';')) + oneOf(list(alphas))) ``` ...
range and xrange for 13-digit numbers in Python?
2,187,135
12
2010-02-02T19:49:16Z
2,187,319
12
2010-02-02T20:12:45Z
[ "python", "range", "numbers", "xrange" ]
`range()` and `xrange()` work for 10-digit-numbers. But how about 13-digit-numbers? I didn't find anything in the forum.
You could try this. Same semantics as range: ``` import operator def lrange(num1, num2 = None, step = 1): op = operator.__lt__ if num2 is None: num1, num2 = 0, num1 if num2 < num1: if step > 0: num1 = num2 op = operator.__gt__ elif step < 0: num1 = num2 ...
Python: Print only the message on warnings
2,187,269
13
2010-02-02T20:08:10Z
2,187,337
9
2010-02-02T20:14:34Z
[ "python", "warnings" ]
I'm issuing lots of warnings in a validator, and I'd like to suppress everything in stdout except the message that is supplied to `warnings.warn()`. I.e., now I see this: ``` ./file.py:123: UserWarning: My looong warning message some Python code ``` I'd like to see this: ``` My looong warning message ``` **Edit 2:...
Monkeypatch [`warnings.showwarning()`](http://docs.python.org/library/warnings.html#warnings.showwarning) with your own custom function.
Python: Print only the message on warnings
2,187,269
13
2010-02-02T20:08:10Z
2,187,390
7
2010-02-02T20:21:44Z
[ "python", "warnings" ]
I'm issuing lots of warnings in a validator, and I'd like to suppress everything in stdout except the message that is supplied to `warnings.warn()`. I.e., now I see this: ``` ./file.py:123: UserWarning: My looong warning message some Python code ``` I'd like to see this: ``` My looong warning message ``` **Edit 2:...
There is always monkeypatching: ``` import warnings def custom_formatwarning(msg, *a): # ignore everything except the message return str(msg) + '\n' warnings.formatwarning = custom_formatwarning warnings.warn("achtung") ```
python 2.6 cPickle.load results in EOFError
2,187,558
8
2010-02-02T20:46:03Z
2,187,579
14
2010-02-02T20:49:38Z
[ "python", "pickle", "eoferror" ]
I use cPickle to pickle a list of integers, using HIGHEST\_PROTOCOL, ``` cPickle.dump(l, f, HIGHEST_PROTOCOL) ``` When I try to unpickle this using the following code, I get an EOFError. I tried 'seeking' to offset 0 before unpickling, but the error persists. ``` l = cPickle.load(f) ``` Any ideas?
If you are on windows, make sure you ``` open(filename, 'wb') # for writing open(filename, 'rb') # for reading ```
Which is web.py killer app?
2,187,610
4
2010-02-02T20:53:10Z
2,187,798
7
2010-02-02T21:19:53Z
[ "python", "web.py" ]
A killer app is an app that make a library or framework famous. I think web.py is quite famous, but I don't know any big, widely used app written in web.py. Could you point out any? I've head that the first version of youtube.com was coded using web.py but I'd like you to mention an open source one so I can see its co...
From [web.py](http://webpy.org/src) website here is a list of "Real Web Apps" written in web.py. None of them has yet become the next twitter. * [redditriver.com](http://redditriver.com/): a mobile version of reddit.com * [webme](http://wm.justos.org/txt.intro): a blogging and podcasting system * [webr](http://antrix....
What is the equivalent of php's print_r() in python?
2,187,821
55
2010-02-02T21:24:26Z
2,187,834
18
2010-02-02T21:26:00Z
[ "php", "python" ]
Or is there a better way to quickly output the contents of an array (multidimensional or what not). Thanks.
Check out [pprint module](http://docs.python.org/library/pprint.html).
What is the equivalent of php's print_r() in python?
2,187,821
55
2010-02-02T21:24:26Z
2,187,843
33
2010-02-02T21:27:51Z
[ "php", "python" ]
Or is there a better way to quickly output the contents of an array (multidimensional or what not). Thanks.
The python [print](http://docs.python.org/reference/simple_stmts.html#print) statement does a good job of formatting multidimesion arrays without requiring the [print\_r](http://php.net/manual/en/function.print-r.php) available in php. As the definition for print states that each object is converted to a string, and a...
Integrating Python or Perl with PHP
2,187,998
2
2010-02-02T21:53:41Z
2,188,027
8
2010-02-02T21:58:10Z
[ "php", "python", "perl", "integration", "phpbb" ]
I'm going to help my friend in a improve of his phpBB board, but I want to make somethings there in Python or Perl. But it's possible to integrate these languages with PHP?
You can always call the python or perl interpreter from within PHP! Minimalistic interchange is possible by means of passing command line arguments and capturing stdout (`exec` or `passthru` are related php functions). However, I don't think its's a good idea - using two interpreters instead of one doubles the overall...
Integrating Python or Perl with PHP
2,187,998
2
2010-02-02T21:53:41Z
2,188,168
8
2010-02-02T22:19:01Z
[ "php", "python", "perl", "integration", "phpbb" ]
I'm going to help my friend in a improve of his phpBB board, but I want to make somethings there in Python or Perl. But it's possible to integrate these languages with PHP?
I'd say that the only reasonable way of doing that is if you are making a separate service, that you talk to via Ajax or XML or something like that. Everything else is more trouble than it's worth.
Writing good tests for Django applications
2,188,551
27
2010-02-02T23:23:48Z
2,188,904
17
2010-02-03T00:40:15Z
[ "python", "django", "unit-testing", "django-testing" ]
I've never written any tests in my life, but I'd like to start writing tests for my Django projects. I've read some articles about tests and decided to try to write some tests for an extremely simple Django app or a start. The app has two views (a list view, and a detail view) and a model with four fields: ``` class ...
I am not perfect in testing but a few thoughts: > Basically you should test every function, method, class, whatever, that you have written by yourself. This implies that you don't have to test functions, classes, etc. which the framework provides. That said, a quick check of your test functions: * `test_detail_stat...
How can I detect and track people using OpenCV?
2,188,646
34
2010-02-02T23:50:00Z
2,300,503
26
2010-02-20T00:16:52Z
[ "python", "opencv", "computer-vision", "motion-detection" ]
I have a camera that will be stationary, pointed at an indoors area. People will walk past the camera, within about 5 meters of it. Using **OpenCV**, I want to detect individuals walking past - my ideal return is an array of detected individuals, with bounding rectangles. I've looked at several of the built-in samples...
The latest SVN version of OpenCV contains an (undocumented) implementation of HOG-based pedestrian detection. It even comes with a pre-trained detector and a python wrapper. The basic usage is as follows: ``` from cv import * storage = CreateMemStorage(0) img = LoadImage(file) # or read from camera found = list(HOG...
Stock Icons not shown on buttons
2,188,659
11
2010-02-02T23:51:26Z
2,188,784
9
2010-02-03T00:16:46Z
[ "python", "gtk", "pygtk" ]
``` self.button = gtk.Button(stock=gtk.STOCK_DELETE) ``` Only Shows: Delete
This is a recent change in GTK - the developers wanted icons not to appear on buttons. On Linux, this can be changed by editing the gconf key ``` /desktop/gnome/interface/buttons_have_icons ``` On windows, I think (I haven't actually tried this) that you need to set a value in your gtkrc file (for me it's in `C:\Prog...
Stock Icons not shown on buttons
2,188,659
11
2010-02-02T23:51:26Z
3,175,809
13
2010-07-04T18:50:01Z
[ "python", "gtk", "pygtk" ]
``` self.button = gtk.Button(stock=gtk.STOCK_DELETE) ``` Only Shows: Delete
The Python equivalent for setting the property without having to change any system config files is: ``` settings = gtk.settings_get_default() settings.props.gtk_button_images = True ``` This should follow a call to window.show() and, obviously, precede the gtk.main() loop.
getting the id of a created record in SQLAlchemy
2,188,844
4
2010-02-03T00:29:51Z
2,189,662
12
2010-02-03T04:19:12Z
[ "python", "insert", "sqlalchemy" ]
How can I get the id of the created record in SQLAlchemy? I'm doing: ``` engine.execute("insert into users values (1,'john')") ```
When you execute a plain text statement, you're at the mercy of the DBAPI you're using as to whether or not the new PK value is available and via what means. With SQlite and MySQL DBAPIs you'll have it as result.lastrowid, which just gives you the value of .lastrowid for the cursor. With PG, Oracle, etc., there's no "....
What is the python equivalent of the Perl pattern to track if something has already been seen?
2,188,863
5
2010-02-03T00:32:21Z
2,188,878
11
2010-02-03T00:35:25Z
[ "python", "perl" ]
In Perl, one can do the following ``` for (@foo) { # do something next if $seen{$_}++; } ``` I would like to be able to do the equivalent in Python, that is to skip a block if it has been executed once.
``` seen = set() for x in foo: if x in seen: continue seen.add(x) # do something ``` See the [`set`](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset) documentation for more information. Also, the examples at the bottom of the [itertools](http://docs.python.org/library/itertool...
embedding short python scripts inside a bash script
2,189,098
26
2010-02-03T01:36:41Z
2,189,116
21
2010-02-03T01:44:25Z
[ "python", "bash" ]
I'd like to embed the text of short python scripts inside of a bash script, for use in say, my `.bash_profile`. What's the best way to go about doing such a thing? The solution I have so far is to call the python interpreter with the `-c` option, and tell the interpreter to `exec` whatever it reads from `stdin`. From ...
Why should you need to use `-c`? This works for me: ``` python << END ... code ... END ``` without needing anything extra.
embedding short python scripts inside a bash script
2,189,098
26
2010-02-03T01:36:41Z
2,189,118
17
2010-02-03T01:45:24Z
[ "python", "bash" ]
I'd like to embed the text of short python scripts inside of a bash script, for use in say, my `.bash_profile`. What's the best way to go about doing such a thing? The solution I have so far is to call the python interpreter with the `-c` option, and tell the interpreter to `exec` whatever it reads from `stdin`. From ...
The python interpreter accepts `-` on the command line as a synonym for `stdin` so you can replace the calls to pyexec with: ``` python - <<END ``` See command line reference [here](http://docs.python.org/using/cmdline.html#command-line).
How to create a new datebase(named xx.db) using python and sqlite3
2,189,393
45
2010-02-03T03:04:34Z
2,189,437
69
2010-02-03T03:16:43Z
[ "python", "sqlite" ]
``` import sqlite3 conn = sqlite3.connect(r"D:\aaa.db") ``` Is there a way to automatically create the db file if it doesn't already exist when I connect to it? thanks
The code you give *does* create `'D:\\aaa.db'` if it doesn't exist.
How to create a new datebase(named xx.db) using python and sqlite3
2,189,393
45
2010-02-03T03:04:34Z
2,189,463
7
2010-02-03T03:23:19Z
[ "python", "sqlite" ]
``` import sqlite3 conn = sqlite3.connect(r"D:\aaa.db") ``` Is there a way to automatically create the db file if it doesn't already exist when I connect to it? thanks
If it isn't created automatically, make sure that you have the directory permissions correct
Length of an integer in Python
2,189,800
96
2010-02-03T04:56:52Z
2,189,814
111
2010-02-03T05:00:53Z
[ "python", "count", "integer" ]
In Python, how do you find the number of digits in an integer?
If you want the length of an integer as in the number of digits in the integer, you can always convert it to string like `str(133)` and find its length like `len(str(123))`.
Length of an integer in Python
2,189,800
96
2010-02-03T04:56:52Z
2,189,827
104
2010-02-03T05:04:54Z
[ "python", "count", "integer" ]
In Python, how do you find the number of digits in an integer?
Without conversion to string ``` import math digits = int(math.log10(n))+1 ``` To also handle zero and negative numbers ``` import math if n > 0: digits = int(math.log10(n))+1 elif n == 0: digits = 1 else: digits = int(math.log10(-n))+2 # +1 if you don't count the '-' ``` You'd probably want to put that...
Length of an integer in Python
2,189,800
96
2010-02-03T04:56:52Z
2,189,834
17
2010-02-03T05:06:44Z
[ "python", "count", "integer" ]
In Python, how do you find the number of digits in an integer?
Python `2.*` `int`s take either 4 or 8 bytes (32 or 64 bits), depending on your Python build. `sys.maxint` (`2**31-1` for 32-bit ints, `2**63-1` for 64-bit ints) will tell you which of the two possibilities obtains. In Python 3, `int`s (like `long`s in Python 2) can take arbitrary sizes up to the amount of available m...
Length of an integer in Python
2,189,800
96
2010-02-03T04:56:52Z
7,702,209
8
2011-10-09T08:07:04Z
[ "python", "count", "integer" ]
In Python, how do you find the number of digits in an integer?
Let the number be n then the number of digits in n is given by: ``` math.floor(math.log10(n))+1 ``` Note that this will give correct answers for integers only.
None in boost.python
2,190,349
8
2010-02-03T07:33:40Z
2,191,360
14
2010-02-03T11:01:18Z
[ "c++", "python", "boost" ]
I am trying to translate the following code ``` d = {} d[0] = None ``` into C++ with boost.python ``` boost::python::dict d; d[0] = ?None ``` How can I get a None object in boost.python? ANSWER: ``` boost::python::dict d; d[0] = boost::python::object(); ```
There is no constructor of `boost::python::object` that takes a `PyObject*` (from my understanding, a ctor like that would invalidate the whole idea if mapping Python types to C++ types anyway, because the PyObject\* could be anything). According to the [documentation](http://www.boost.org/doc/libs/1_42_0/libs/python/d...
Screen scraping with Python
2,190,502
15
2010-02-03T08:11:30Z
2,190,631
11
2010-02-03T08:38:18Z
[ "python", "screen-scraping", "htmlunit", "pycurl" ]
Does Python have screen scraping libraries that offer JavaScript support? I've been using **pycurl** for simple HTML requests, and Java's **HtmlUnit** for more complicated requests requiring JavaScript support. Ideally I would like to be able to do everything from Python, but I haven't come across any libraries that ...
[Beautiful soup](http://www.crummy.com/software/BeautifulSoup/) is still probably your best bet. If you need "JavaScript support" for the purpose of intercepting Ajax requests then you should use some sort of capture too (such as [YATT](http://www.pocketsoap.com/YATT/)) to monitor what those requests are, and then emu...
Screen scraping with Python
2,190,502
15
2010-02-03T08:11:30Z
2,215,099
12
2010-02-06T23:08:19Z
[ "python", "screen-scraping", "htmlunit", "pycurl" ]
Does Python have screen scraping libraries that offer JavaScript support? I've been using **pycurl** for simple HTML requests, and Java's **HtmlUnit** for more complicated requests requiring JavaScript support. Ideally I would like to be able to do everything from Python, but I haven't come across any libraries that ...
There are many options when dealing with static HTML, which the other responses cover. However if you need JavaScript support and want to stay in Python I recommend using [webkit](http://pyqt.sourceforge.net/Docs/PyQt5/pyqt4_differences.html#qtwebkit-module) to render the webpage (including the JavaScript) and then exa...
Find an element in a list of tuples
2,191,699
54
2010-02-03T12:08:58Z
2,191,707
95
2010-02-03T12:10:05Z
[ "python", "list", "search", "tuples" ]
I have a list 'a' ``` a= [(1,2),(1,4),(3,5),(5,7)] ``` I need to find all the tuples for a particular number. say for 1 it will be ``` result = [(1,2),(1,4)] ``` How do I do that?
If you just want the first number to match you can do it like this: ``` [item for item in a if item[0] == 1] ``` If you are just searching for tuples with 1 in them: ``` [item for item in a if 1 in item] ```
Find an element in a list of tuples
2,191,699
54
2010-02-03T12:08:58Z
18,114,565
44
2013-08-07T22:01:37Z
[ "python", "list", "search", "tuples" ]
I have a list 'a' ``` a= [(1,2),(1,4),(3,5),(5,7)] ``` I need to find all the tuples for a particular number. say for 1 it will be ``` result = [(1,2),(1,4)] ``` How do I do that?
There is actually a clever way to do this that is useful for any list of tuples where the size of each tuple is 2: you can convert your list into a single dictionary. For example, ``` test = [("hi", 1), ("there", 2)] test = dict(test) print test["hi"] # prints 1 ```
Python: How do I force iso-8859-1 file output?
2,191,730
5
2010-02-03T12:14:28Z
2,191,845
9
2010-02-03T12:33:57Z
[ "python", "character-encoding" ]
How do I force Latin-1 (which I guess means iso-8859-1?) file output in Python? Here's my code at the moment. It works, but trying to import the resulting output file into a Latin-1 MySQL table produces [weird encoding errors](http://stackoverflow.com/questions/2188522/importing-text-to-mysql-strange-format). ``` out...
Simply use the [`codecs`](http://docs.python.org/library/codecs.html) module for writing the file: ``` import codecs outputFile = codecs.open("textbase.tab", "w", "ISO-8859-1") ``` Of course, the strings you write have to be Unicode strings (type `unicode`), they won't be converted if they are plain `str` objects (wh...
Conditional operator in Python?
2,191,890
49
2010-02-03T12:44:07Z
2,191,896
88
2010-02-03T12:44:47Z
[ "python", "syntax" ]
do you know if Python supports some keyword or expression like in C++ to return values based on `if` condition, all in the same line (The C++ `if` expressed with the question mark `?`) ``` // C++ value = ( a > 10 ? b : c ) ```
From Python 2.5 onwards you can do: ``` value = b if a > 10 else c ``` Previously you would have to do something like the following, although the semantics isn't identical as the short circuiting effect is lost: ``` value = [c, b][a > 10] ``` There's also another hack using 'and ... or' but it's best to not use it ...
What is the Python egg cache (PYTHON_EGG_CACHE)?
2,192,323
62
2010-02-03T13:50:10Z
2,192,369
28
2010-02-03T13:56:10Z
[ "python", "python-egg-cache" ]
I've just upgraded from Python 2.6.1 to 2.6.4 on my development machine and upon starting a python script was presented with the following message: > Can't extract file(s) to egg cache > > The following error occurred while > trying to extract file(s) to the > Python egg cache: > > [Errno 13] Permission denied: > '/va...
The python egg cache is simply a directory used by setuptools to store packages installed that conform to the [egg specification](http://peak.telecommunity.com/DevCenter/EggFormats). You can [read more about setuptools here](http://pypi.python.org/pypi/setuptools). Additionally, as the error message states, you can sp...
What is the Python egg cache (PYTHON_EGG_CACHE)?
2,192,323
62
2010-02-03T13:50:10Z
2,193,746
55
2010-02-03T17:03:15Z
[ "python", "python-egg-cache" ]
I've just upgraded from Python 2.6.1 to 2.6.4 on my development machine and upon starting a python script was presented with the following message: > Can't extract file(s) to egg cache > > The following error occurred while > trying to extract file(s) to the > Python egg cache: > > [Errno 13] Permission denied: > '/va...
From my investigations it turns out that some eggs are packaged as zip files, and are saved as such in Python's `site-packages` directory. These zipped eggs need to be unzipped before they can be executed, so are expanded into the `PYTHON_EGG_CACHE` directory which by default is `~/.python-eggs` (located in the user's...
What is the Python egg cache (PYTHON_EGG_CACHE)?
2,192,323
62
2010-02-03T13:50:10Z
11,958,516
8
2012-08-14T18:29:31Z
[ "python", "python-egg-cache" ]
I've just upgraded from Python 2.6.1 to 2.6.4 on my development machine and upon starting a python script was presented with the following message: > Can't extract file(s) to egg cache > > The following error occurred while > trying to extract file(s) to the > Python egg cache: > > [Errno 13] Permission denied: > '/va...
This is a dark side-effect of using otherwise nice eggs mechanism. Eggs are packages (a directory full of files) packed into one `.egg` file to simplify depolyment. They are stored in `/site-packages/` dir. As long as the files stored in the egg are `.py` files it works great. Python import can import things from an...
Why isn't there a do while flow control statement in python?
2,192,344
13
2010-02-03T13:53:01Z
2,192,371
10
2010-02-03T13:56:20Z
[ "python" ]
Is there a good reason why there isn't a do while flow control statement in python? Why do pepole have to write while and break explicitly?
Probably because Guido didn't think it was necessary. There are a bunch of different flow-control statements you could support, but most of them are variants of each other. Frankly, I've found the do-while statement to be one of the less useful ones.
Why isn't there a do while flow control statement in python?
2,192,344
13
2010-02-03T13:53:01Z
2,192,401
11
2010-02-03T14:01:31Z
[ "python" ]
Is there a good reason why there isn't a do while flow control statement in python? Why do pepole have to write while and break explicitly?
It has been proposed in [PEP 315](http://www.python.org/dev/peps/pep-0315/) but hasn't been implemented because nobody has come up with a syntax that's clearer than the `while True` with an inner `if-break`.
Verify a file exists over ssh
2,192,442
4
2010-02-03T14:08:34Z
2,192,825
9
2010-02-03T14:59:29Z
[ "python", "bash", "testing", "ssh", "pexpect" ]
I am trying to test if a file exists over SSH using pexpect. I have got most of the code working but I need to catch the value so I can assert whether the file exists. The code I have done is below: ``` def VersionID(): ssh_newkey = 'Are you sure you want to continue connecting' # my ssh command line ...
Why not take advantage of the fact that the return code of the command is passed back over SSH? ``` $ ssh victory 'test -f .bash_history' $ echo $? 0 $ ssh victory 'test -f .csh_history' $ echo $? 1 $ ssh hostdoesntexist 'test -f .csh_history' ssh: Could not resolve hostname hostdoesntexist: Name or service not known ...
Python: Creating a streaming gzip'd file-like?
2,192,529
17
2010-02-03T14:19:14Z
2,193,508
10
2010-02-03T16:29:39Z
[ "python", "gzip", "zlib" ]
I'm trying to figure out the best way to compress a stream with Python's `zlib`. I've got a file-like input stream (`input`, below) and an output function which accepts a file-like (`output_function`, below): ``` with open("file") as input: output_function(input) ``` And I'd like to gzip-compress `input` chunks ...
It's quite kludgy (self referencing, etc; just put a few minutes writing it, nothing really elegant), but it does what you want if you're still interested in using `gzip` instead of `zlib` directly. Basically, `GzipWrap` is a (very limited) file-like object that produces a gzipped file out of a given iterable (e.g., a...
Using explicit del in python on local variables
2,192,926
10
2010-02-03T15:12:15Z
2,193,071
28
2010-02-03T15:32:10Z
[ "python", "coding-style" ]
What are the best practices and recommendations for using explicit `del` statement in python? I understand that it is used to remove attributes or dictionary/list elements and so on, but sometimes I see it used on local variables in code like this: ``` def action(x): result = None something = produce_something...
I don't remember when I last used `del` -- the need for it is rare indeed, and typically limited to such tasks as cleaning up a module's namespace after a needed `import` or the like. In particular, it's **not** true, as another (now-deleted) answer claimed, that > Using `del` is the only way to make sure > a object'...
Python: urllib2.urlopen(url, data) Why do you have to urllib.urlencode() the data?
2,192,987
7
2010-02-03T15:20:45Z
2,193,035
9
2010-02-03T15:27:30Z
[ "python", "urllib2", "urllib" ]
I thought that a post sent all the information in HTTP headers when you used post (I'm not well informed on this subject obviously), so I'm confused why you have to urlencode() the data to a `key=value&key2=value2` format. How does that formatting come into play when using POST?: ``` # Fail data = {'name': 'John Smith...
It is related to the "Content-Type" header: the client must have an idea of how the POST data is encoded or else how would it know how to decode it? The standard way of doing this is through *application/x-www-form-urlencoded* encoding format. Now, if the question is "why do we need to encode?", the answer is "becaus...
extend Python namedtuple with many @properties?
2,193,009
7
2010-02-03T15:24:11Z
2,193,111
10
2010-02-03T15:37:14Z
[ "python", "properties", "namedtuple" ]
How can namedtuples be extended or subclassed with many additional @properties ? For a few, one can just write the text below; but there are many, so I'm looking for a generator or property factory. One way would be to generate text from `_fields` and exec it; another would be an add\_fields with the same effect at r...
The answer to your question > How can namedtuples be extended or > subclassed with additional `@properties` > ? is: exactly the way you're doing it! What error are you getting? To see a simpler case, ``` >>> class x(collections.namedtuple('y', 'a b c')): ... @property ... def d(self): return 23 ... >>> a=x(1, 2...
Display function definition in interactive shell
2,193,231
8
2010-02-03T15:55:06Z
2,193,342
7
2010-02-03T16:07:04Z
[ "python", "shell" ]
I am working in the Python Interactive Shell (ActiveState ActivePython 2.6.4 under Windows XP). I created a function that does what I want. However, I've cleared the screen so I can't go back and look at the function definition. It is also a multiline function so the up arrow to redisplay lines is of minimal value. Is ...
No, `__code__` and `func_code` are references to the compiled bytecode -- you can disassemble them (see `dis.dis`) but not get back to the Python source code. Alas, the source code is simply gone, not remembered anywhere...: ``` >>> import inspect >>> def f(): ... print 'ciao' ... >>> inspect.getsource(f) Tracebac...
catching SQLAlchemy exceptions
2,193,670
15
2010-02-03T16:53:00Z
2,193,712
16
2010-02-03T16:59:40Z
[ "python", "sqlalchemy", "exception" ]
What is the upper level exception that I can catch SQLAlechmy exceptions with ? ``` >>> from sqlalchemy import exc >>> dir(exc) ['ArgumentError', 'CircularDependencyError', 'CompileError', 'ConcurrentModificationError', 'DBAPIError', 'DataError', 'DatabaseError', 'DisconnectionError', 'FlushError', 'IdentifierError', ...
From [the source](https://github.com/zzzeek/sqlalchemy/blob/master/lib/sqlalchemy/exc.py#L10): > The base exception class is > `SQLAlchemyError`.
catching SQLAlchemy exceptions
2,193,670
15
2010-02-03T16:53:00Z
4,430,982
22
2010-12-13T16:25:56Z
[ "python", "sqlalchemy", "exception" ]
What is the upper level exception that I can catch SQLAlechmy exceptions with ? ``` >>> from sqlalchemy import exc >>> dir(exc) ['ArgumentError', 'CircularDependencyError', 'CompileError', 'ConcurrentModificationError', 'DBAPIError', 'DataError', 'DatabaseError', 'DisconnectionError', 'FlushError', 'IdentifierError', ...
To catch any exception SQLAlchemy throws: ``` from sqlalchemy import exc db.add(user) try: db.commit() except exc.SQLAlchemyError: pass ``` See help(sqlalchemy.exc) and help(sqlalchemy.orm.exc) for a list of possible exceptions that sqlalchemy can raise.
Overcoming the "disadvantages" of string immutability
2,193,705
6
2010-02-03T16:58:18Z
2,193,895
8
2010-02-03T17:24:13Z
[ "python", "string", "immutability" ]
I want to change the value of a particular string index, but unfortunately ``` string[4] = "a" ``` raises a `TypeError`, because strings are immutable ("item assignment is not supported"). So instead I use the rather clumsy ``` string = string[:4] + "a" + string[4:] ``` Is there a better way of doing this?
The strings in Python are immutable, just like numbers and tuples. This means that you can create them, move them around, but not change them. Why is this so ? For a few reasons (you can find a better discussion online): * By design, strings in Python are considered elemental and unchangeable. This spurs better, safer...
In python, how do I exclude files from a loop if they begin with a specific set of letters?
2,193,710
8
2010-02-03T16:59:31Z
2,193,749
16
2010-02-03T17:03:30Z
[ "python", "string" ]
I'm writing a Python script that goes through a directory and gathers certain files, but there are a number of files I want excluded that all start the same. Example code: ``` for name in files: if name != "doc1.html" and name != "doc2.html" and name != "doc3.html": print name ``` Let's say there are 100 hu...
``` if not name.startswith('doc'): print name ``` If you have more prefixes to exclude you can even do this: ``` if not name.startswith(('prefix', 'another', 'yetanother')): print name ``` [startswith](https://docs.python.org/2/library/stdtypes.html#str.startswith) can accept a tuple of prefixes.
Set the hardware clock in Python?
2,193,964
5
2010-02-03T17:33:14Z
2,194,029
9
2010-02-03T17:40:23Z
[ "python", "linux", "hwclock" ]
How do I set the hardware clock with Python on embedded Linux systems?
Probably no easy way other than doing an os.system() call. ``` import os os.system('hwclock --set %s' % date_str) ``` or using the 'date' command ``` import os os.system('date -s %s' % date_str) ``` or if you are dying to do some c coding, wrapping the system calls with swig... but I think that would be more work t...
python empty argument
2,194,163
10
2010-02-03T17:58:54Z
2,194,175
9
2010-02-03T18:00:47Z
[ "python" ]
how do I print help info if no arguments are passed to python script? ``` #!/usr/bin/env python import sys for arg in sys.argv: if arg == "do": do this if arg == "" print "usage is bla bla bla" ``` what I'm missing is `if arg == ""` line that I don't know how to express :(
``` if len(sys.argv)<2: ``` The name of the program is always in sys.argv[0]
python empty argument
2,194,163
10
2010-02-03T17:58:54Z
2,194,187
15
2010-02-03T18:02:36Z
[ "python" ]
how do I print help info if no arguments are passed to python script? ``` #!/usr/bin/env python import sys for arg in sys.argv: if arg == "do": do this if arg == "" print "usage is bla bla bla" ``` what I'm missing is `if arg == ""` line that I don't know how to express :(
``` if len(sys.argv) == 1: # Print usage... ``` The first element of sys.argv is always either the name of the script itself, or an empty string. If sys.argv has only one element, then there must have been no arguments. <http://docs.python.org/library/sys.html#sys.argv>
Is there something similar to python's enumerate for linq
2,194,684
3
2010-02-03T19:09:37Z
2,194,703
8
2010-02-03T19:12:41Z
[ ".net", "python", "linq" ]
In python I can easily get an index when iterating e.g. ``` >>> letters = ['a', 'b', 'c'] >>> [(char, i) for i, char in enumerate(letters)] [('a', 0), ('b', 1), ('c', 2)] ``` How can I do something similar with linq?
Sure. There is an [overload of `Enumerable.Select`](http://msdn.microsoft.com/en-us/library/bb534869.aspx) that takes a `Func<TSource, int, TResult>` to project an element together with its index: For example: ``` char[] letters = new[] { 'a', 'b', 'c' }; var enumerate = letters.Select((c, i) => new { Char = c, Index...
In Sphinx, is there a way to document parameters along with declaring them?
2,194,777
11
2010-02-03T19:21:39Z
2,194,814
8
2010-02-03T19:27:46Z
[ "python", "restructuredtext", "python-sphinx" ]
I prefer to document each parameter (as needed) on the same line where I declare the parameter in order to apply [D.R.Y.](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself) If I have code like this: ``` def foo( flab_nickers, # a series of under garments to process has_polka_dots=False, nee...
I would do this. Starting with this code. ``` def foo( flab_nickers, # a series of under garments to process has_polka_dots=False, needs_pressing=False # Whether the list of garments should all be pressed ): ... ``` I would write a parser that grabs the function parameter definitions ...
Where can I download the Django documentation?
2,195,089
13
2010-02-03T20:13:11Z
2,195,098
12
2010-02-03T20:15:22Z
[ "python", "django", "documentation" ]
Django's website seems good but for some reason I couldn't find where to download the documentation: <http://docs.djangoproject.com/en/1.1/> (Yes, I need the docs for 1.1) Does anyone know?
Django's documentation is built using [Sphinx](http://sphinx.pocoo.org/index.html) and [included in their source tree](http://code.djangoproject.com/browser/django/trunk/docs). From a checked-out copy of Django's source, just run `make` in the docs directory. You can find instructions for getting the source here: <htt...
Where can I download the Django documentation?
2,195,089
13
2010-02-03T20:13:11Z
6,588,530
9
2011-07-05T20:32:55Z
[ "python", "django", "documentation" ]
Django's website seems good but for some reason I couldn't find where to download the documentation: <http://docs.djangoproject.com/en/1.1/> (Yes, I need the docs for 1.1) Does anyone know?
You can download offline documentation for Django 1.1, 1.2 and 1.3 in both PDF and HTML from <http://sramana.github.com/dod/>.
Where can I download the Django documentation?
2,195,089
13
2010-02-03T20:13:11Z
12,428,868
11
2012-09-14T16:56:38Z
[ "python", "django", "documentation" ]
Django's website seems good but for some reason I couldn't find where to download the documentation: <http://docs.djangoproject.com/en/1.1/> (Yes, I need the docs for 1.1) Does anyone know?
Offline Documentation for Django **1.2**, **1.3** and **1.4** in various formats: <http://readthedocs.org/projects/django/downloads/>
Python's layout of low-value ints in memory
2,195,964
4
2010-02-03T22:28:41Z
2,196,014
7
2010-02-03T22:34:03Z
[ "python", "memory" ]
My question is: where do these patterns (below) originate? I learned (somewhere) that Python has unique "copies", if that's the right word, for small integers. For example: ``` >>> x = y = 0 >>> id(0) 4297074752 >>> id(x) 4297074752 >>> id(y) 4297074752 >>> x += 1 >>> id(x) 4297074728 >>> y 0 ``` When I look at the ...
Low-value integers are preallocated, high value integers are allocated whenever they are computed. Integers that appear in source code are the same object. On my system, ``` >>> id(2) == id(1+1) True >>> id(1000) == id(1000+0) False >>> id(1000) == id(1000) True ``` You'll also notice that the ids depend on the syste...
Matplotlib: Formatting dates on the x-axis in a 3D Bar graph
2,195,983
10
2010-02-03T22:30:52Z
2,215,733
9
2010-02-07T03:07:32Z
[ "python", "numpy", "graph", "matplotlib", "data-analysis" ]
Given this [3D bar graph sample code](http://matplotlib.sourceforge.net/examples/mplot3d/bars3d_demo.html), how would you convert the numerical data in the x-axis to formatted date/time strings? I've attempted using the ax.xaxis\_date() function without success. I also tried using plot\_date(), which doesn't appear to ...
There might be some confusion here, the Axes3D has the properties w\_xaxis, w\_yaxis and w\_zaxis for the axises instead of the usual xaxix, yaxis, etc.. **UPDATE** Now uses function to format labels. ``` from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np import matplotlib.date...
how to extract formatted text content from PDF
2,196,621
14
2010-02-04T00:48:28Z
2,196,933
9
2010-02-04T02:13:20Z
[ "python", "pdf", "text", "extract", "google-docs" ]
How can I extract the text content (not images) from a PDF while (roughly) maintaining the style and layout like Google Docs can?
To extract the text from the PDF AND get it's position you can use [PDFMiner](http://www.unixuser.org/~euske/python/pdfminer/index.html). PDFMiner can also export the PDF directly in HTML keeping the text at the good position. I don't know your use case, but there's a lot of problems you can encounter when doing this ...
Improving Numpy Performance
2,196,693
17
2010-02-04T01:00:42Z
2,205,095
8
2010-02-05T04:42:23Z
[ "python", "math", "numpy", "scipy", "convolution" ]
I'd like to improve the performance of convolution using python, and was hoping for some insight on how to best go about improving performance. I am currently using scipy to perform the convolution, using code somewhat like the snippet below: ``` import numpy import scipy import scipy.signal import timeit a=numpy.ar...
The code in scipy for doing 2d convolutions is a bit messy and unoptimized. See <http://svn.scipy.org/svn/scipy/trunk/scipy/signal/firfilter.c> if you want a glimpse into the low-level functioning of scipy. If all you want is to process with a small, constant kernel like the one you showed, a function like this might ...
django input element error css class
2,196,797
8
2010-02-04T01:30:26Z
2,242,528
7
2010-02-11T05:43:24Z
[ "python", "django", "validation", "django-forms" ]
I'd like to know how can I add .error class to input elements ([to registration app](http://django-registration.googlecode.com/svn/trunk/registration/)) when the form validation fails.
This can be done completely through your template. You build the form template for each form field that you want to test you can use the following example construct ``` <input type="text" class="reg-txt{% if form.fieldname.errors %} errors{% endif %}"/> ``` This lets you provide the interface you want without modify...
django input element error css class
2,196,797
8
2010-02-04T01:30:26Z
4,171,771
26
2010-11-13T09:05:37Z
[ "python", "django", "validation", "django-forms" ]
I'd like to know how can I add .error class to input elements ([to registration app](http://django-registration.googlecode.com/svn/trunk/registration/)) when the form validation fails.
It's now easy -- new feature in Django 1.2 Just add an attribute on the form class & you're good to go. This feature is mentioned in the docs under a "new in 1.2" note, but you can find the magic at `django.forms.forms.BoundField.css_classes` Here's the [API reference](http://docs.djangoproject.com/en/dev/ref/forms/ap...
django input element error css class
2,196,797
8
2010-02-04T01:30:26Z
8,256,041
22
2011-11-24T11:06:34Z
[ "python", "django", "validation", "django-forms" ]
I'd like to know how can I add .error class to input elements ([to registration app](http://django-registration.googlecode.com/svn/trunk/registration/)) when the form validation fails.
If you want to place your error CSS class to form input widgets (not their containers), you can derive your form class from the following one: ``` class StyledErrorForm(forms.Form): def is_valid(self): ret = forms.Form.is_valid(self) for f in self.errors: self.fields[f].widget.attrs.upd...
Add an object to a python list
2,196,956
17
2010-02-04T02:21:52Z
2,196,972
15
2010-02-04T02:29:05Z
[ "python", "object" ]
I am trying to add an object to a list but since I'm adding the actual object when I try to reset the list thereafter, all the values in the list are reset. Is there an actual way how I can add a monitor object to the list and change the values and not affect the ones I've already saved in the list? Thanks Code: ```...
Is your problem similar to this: ``` l = [[0]] * 4 l[0][0] += 1 print l # prints "[[1], [1], [1], [1]]" ``` If so, you simply need to copy the objects when you store them: ``` import copy l = [copy.copy(x) for x in [[0]] * 4] l[0][0] += 1 print l # prints "[[1], [0], [0], [0]]" ``` The objects in question should im...
How to add a timeout to a function in Python
2,196,999
23
2010-02-04T02:38:38Z
2,197,101
13
2010-02-04T03:16:19Z
[ "python", "process", "asynchronous", "cross-platform", "timeout" ]
Many attempts have been made in the past to add timeout functionality in Python such that when a specified time limit expired, waiting code could move on. Unfortunately, previous recipes either allowed the running function to continue running and consuming resources or else killed the function using a platform-specific...
The principal problem with your code is the overuse of the double underscore namespace conflict prevention in a class that isn't intended to be subclassed at all. In general, `self.__foo` is a code smell that should be accompanied by a comment along the lines of `# This is a mixin and we don't want arbitrary subclasse...
Why are empty strings returned in split() results?
2,197,451
58
2010-02-04T05:14:52Z
2,197,493
85
2010-02-04T05:24:44Z
[ "python", "string", "split" ]
What is the point of `'/segment/segment/'.split('/')` returning `['', 'segment', 'segment', '']`? Notice the empty elements. If you're splitting on a delimiter that happens to be at position one and at the very end of a string, what extra value does it give you to have the empty string returned from each end?
`str.split` complements `str.join`, so ``` "/".join(['', 'segment', 'segment', '']) ``` gets you back the original string. If the empty strings were not there, the first and last `'/'` would be missing after the `join()`
Why are empty strings returned in split() results?
2,197,451
58
2010-02-04T05:14:52Z
2,197,575
21
2010-02-04T05:44:24Z
[ "python", "string", "split" ]
What is the point of `'/segment/segment/'.split('/')` returning `['', 'segment', 'segment', '']`? Notice the empty elements. If you're splitting on a delimiter that happens to be at position one and at the very end of a string, what extra value does it give you to have the empty string returned from each end?
There are two main points to consider here: * Expecting the result of `'/segment/segment/'.split('/')` to be equal to `['segment', 'segment']` is reasonable, but then this loses information. If `split()` worked the way you wanted, if I tell you that `a.split('/') == ['segment', 'segment']`, you can't tell me what `a` ...
Why are empty strings returned in split() results?
2,197,451
58
2010-02-04T05:14:52Z
2,197,605
7
2010-02-04T05:50:30Z
[ "python", "string", "split" ]
What is the point of `'/segment/segment/'.split('/')` returning `['', 'segment', 'segment', '']`? Notice the empty elements. If you're splitting on a delimiter that happens to be at position one and at the very end of a string, what extra value does it give you to have the empty string returned from each end?
Having `x.split(y)` always return a list of `1 + x.count(y)` items is a precious regularity -- as @gnibbler's already pointed out it makes `split` and `join` exact inverses of each other (as they obviously should be), it also precisely maps the semantics of all kinds of delimiter-joined records (such as `csv` file line...
Why doesn't super(Thread, self).__init__() work for a threading.Thread subclass?
2,197,563
13
2010-02-04T05:42:22Z
2,197,625
37
2010-02-04T05:56:02Z
[ "python", "multithreading" ]
Every object I know of in Python can take care of its base class initialization by calling: ``` super(BaseClass, self).__init__() ``` This doesn't seem to be the case with a subclass of `threading.Thread`, since if I try this in `SubClass.__init__()`, I get: ``` RuntimeError: thread.__init__() not called ``` What g...
This works fine: ``` >>> class MyThread(threading.Thread): ... def __init__(self): ... super(MyThread, self).__init__() ``` I think your code's bug is that you're passing the **base** class, rather than the **current** class, to `super` -- i.e. you're calling `super(threading.Thread, ...`, and that's just wrong...
Convert "little endian" hex string to IP address in Python
2,197,974
4
2010-02-04T07:16:48Z
2,198,052
21
2010-02-04T07:39:24Z
[ "python", "sockets", "ip-address", "endianness" ]
What's the best way to turn a string in this form into an IP address: `"0200A8C0"`. The "octets" present in the string are in reverse order, i.e. the given example string should generate `192.168.0.2`.
Network address manipulation is provided by the socket module. > [`socket.inet_ntoa(packed_ip)`](http://docs.python.org/library/socket.html#socket.inet_ntoa) > > Convert a 32-bit packed IPv4 address (a string four characters in length) to its standard dotted-quad string representation (for example, ‘123.45.67.89’)...
how to use array in django
2,197,975
2
2010-02-04T07:17:41Z
2,198,402
7
2010-02-04T09:04:17Z
[ "python", "django", "django-models" ]
I have a db table which has an integer array. But how can I add this field in my model? I tried writing it using `IntegerField` but on save it is giving error ``` int() argument must be a string or a number, not 'list ``` How can I add this field to my model? I am using this field in my views.py so I need to add it i...
You may be interested in using a [`CommaSeparatedIntegerField`](http://docs.djangoproject.com/en/dev/ref/models/fields/#commaseparatedintegerfield). If you've got a list of integers like this: ``` my_ints = [1,2,3,4,5] ``` and a model like this: ``` class MyModel(models.Model): values = CommaSeparatedIntegerFie...
Getting python MySQLdb to run on Ubuntu
2,198,260
9
2010-02-04T08:32:56Z
2,198,288
7
2010-02-04T08:38:55Z
[ "python", "ubuntu-9.10", "mysql" ]
I created a virtualbox with a fresh install of ubuntu 9.10. I am trying to get MySQLdb to run on python but I'm failing at the `import MySQLdb` I first tried `sudo easy_install MySQL_python-1.2.3c1-py2.6-linux-i686.egg` and then `sudo apt-get install python-mysqldb`. Both apparently installed ok, but gave me the fol...
Your MySQLdb egg installation looks like it is not working properly. You should go into /usr/local/lib/python2.6/dist-packages and remove it. The Ubuntu python-mysqldb package should work fine. Unless you have a good reason, you should stick to your distribution's package manager when installing new software.
What does pk__in mean in Django?
2,198,635
3
2010-02-04T09:48:05Z
2,198,657
12
2010-02-04T09:50:25Z
[ "python", "django" ]
``` Model.objects.filter(pk__in=[list of ids]) ``` and ``` Model.objects.filter(pk__in=[1,2,3]) ``` How do I show this data in a template? ``` def xx(request): return HttpResponse(Model.objects.filter(pk__in=[1,2,3])) ```
It means, give me all objects of model `Model` that either have `1`,`2` or `3` as their primary key. See [Field lookups - in](http://docs.djangoproject.com/en/1.1/ref/models/querysets/#in). You get a list of objects back you can show them in the template like every other list, using the [`for` template tag](http://do...
In Django, my request.session is not carrying over...does anyone know why?
2,199,150
2
2010-02-04T11:14:42Z
2,200,624
8
2010-02-04T15:01:37Z
[ "python", "django", "session" ]
In one view, I set: ``` request.session.set_expiry(999) request.session['test'] = '123' ``` In another view, I do: ``` print request.session['test'] ``` and it cannot be found. (error) It's very simple, I just have 2 views. It seems that once I leave a view and come back to it...it's gone! Why?
Could it be related to this?, just found it at <http://code.djangoproject.com/wiki/NewbieMistakes> Appending to a list in session doesn't work Problem If you have a list in your session, append operations don't get saved to the object. Solution Copy the list out of the session object, append to it, then copy it back...
matching multiple line in python regular expression
2,199,552
11
2010-02-04T12:22:43Z
2,199,744
13
2010-02-04T12:52:05Z
[ "python" ]
I want to extract the data between `<tr>` tags from an html page. I used the following code.But i didn't get any result. The html between the `<tr>` tags is in multiple lines ``` category =re.findall('<tr>(.*?)</tr>',data); ``` Please suggest a fix for this problem.
just to clear up the issue. Despite all those links to `re.M` it wouldn't work here as simple skimming of the its explanation would reveal. You'd need `re.S`, if you wouldn't try to parse html, of course: ``` >>> doc = """<table border="1"> <tr> <td>row 1, cell 1</td> <td>row 1, cell 2</td> </t...
What is the most lightweight way to transmit data over the internet using Python?
2,199,963
6
2010-02-04T13:31:20Z
2,200,965
9
2010-02-04T15:43:05Z
[ "python", "network-protocols" ]
I have two computers in geographically dispersed locations, both connected to the internet. On each computer I am running a Python program, and I would like to send and receive data from one to the other. I'd like to use the most simple approach possible, while remaining somewhat secure. I have considered the followin...
Protocol buffers are "lightweight" in the sense that they produce very compact wire representation, thus saving bandwidth, memory, storage, etc -- while staying very general-purpose and cross-language. We use them a **lot** at Google, of course, but it's not clear whether you care about these performance characteristic...
which is more efficient for buffer manipulations: python strings or array()
2,200,027
3
2010-02-04T13:41:07Z
2,200,091
9
2010-02-04T13:50:56Z
[ "python", "arrays", "performance" ]
I am building a routine that processes disk buffers for forensic purposes. Am I better off using python strings or the array() type? My first thought was to use strings, but I'm trying to void unicode problems, so perhaps array('c') is better?
Write the code using what is most natural (strings), find out if it's too slow and then improve it. Arrays can be used as drop-in replacements for `str` in most cases, as long as you restrict yourself to index and slice access. Both are fixed-length. Both should have about the same memory requirements. Arrays are muta...
Python: default/common way to read png images
2,200,742
16
2010-02-04T15:15:26Z
2,200,768
23
2010-02-04T15:18:42Z
[ "python", "image", "png" ]
I haven't found a standard way in Python to read images. Is there really none (because there are so many functions for so many custom stuff that I really wonder that there are no functions to read images)? Or what is it? (It should be available in the MacOSX standard installation and in most recent versions on Linux di...
No, there are no modules in the standard library for reading/writing/processing images directly. But the most common library might be [PIL (Python Imaging Library)](http://www.pythonware.com/products/pil/). Many projects are not included in the standard library because they are 1) totally optional and 2) cannot be main...
How bad is it to override a method from a third-party module?
2,200,880
9
2010-02-04T15:30:17Z
2,201,106
11
2010-02-04T16:02:23Z
[ "python", "numpy", "override" ]
How bad is it to redefine a class method from another, third-party module, in Python? In fact, users can create NumPy matrices that contain [numbers with uncertainty](http://pypi.python.org/pypi/uncertainties/); ideally, I would like their code to run unmodified (compared to when the code manipulates float matrices); ...
Subclassing (which does involve overriding, as the term is generally used) is generally much preferable to "monkey-patching" (stuffing altered methods into existing classes or modules), even when the latter is available (built-in types, meaning ones implemented in C, can protect themselves against monkey-patching, and ...
How do you execute a server-side Python script using jQuery?
2,201,561
7
2010-02-04T16:59:38Z
2,201,614
7
2010-02-04T17:06:39Z
[ "javascript", "jquery", "python", "ajax" ]
I have a very simple Python file, called python1.py, whose contents are: ``` f = open('C:\\Temp\\test.txt', 'w') f.write('Succeeded') f.close() ``` I wish to execute this from JavaScript, like so: ``` jQuery.ajax({ type: "POST", url: "/cgi-bin/python1.py", success: function (msg) { alert("Data Saved:...
You simply need to configure your web server to execute your \*.py scripts, instead of serving them as plain text. If you are using Apache as a web server, you need to enable [mod\_python](http://www.modpython.org/) or [mod\_wsgi](http://code.google.com/p/modwsgi/). --- **EDIT:** Since you are using using Apache, y...
How do you execute a server-side Python script using jQuery?
2,201,561
7
2010-02-04T16:59:38Z
7,085,301
7
2011-08-16T21:32:58Z
[ "javascript", "jquery", "python", "ajax" ]
I have a very simple Python file, called python1.py, whose contents are: ``` f = open('C:\\Temp\\test.txt', 'w') f.write('Succeeded') f.close() ``` I wish to execute this from JavaScript, like so: ``` jQuery.ajax({ type: "POST", url: "/cgi-bin/python1.py", success: function (msg) { alert("Data Saved:...
You could also use the opensource project Pico. It's a really elegant way of calling server side Python code from client side Javascript. The author has provided some simple examples here <https://github.com/fergalwalsh/pico/wiki/Example-1:-Hello-World>
Need a way to count entities in GAE datastore that meet a certain condition? (over 1000 entities)
2,201,580
4
2010-02-04T17:02:37Z
2,202,059
7
2010-02-04T18:12:27Z
[ "python", "google-app-engine", "gae-datastore" ]
I'm building an app on GAE that needs to report on events occurring. An event has a type and I also need to report by event type. For example, say there is an event A, B and C. They occur periodically at random. User logs in and creates a set of entities to which those events can be attributed. When the user comes bac...
App Engine is not a relational database and you won't be able to quickly do counts on the fly like this. The best approach is to update the counts at write time, not generate them at read time. When generating counts, there are two general approaches that scale well with App Engine to minimize write contention: 1. St...
How to define two fields "unique" as couple
2,201,598
174
2010-02-04T17:04:30Z
2,201,687
304
2010-02-04T17:16:34Z
[ "python", "django", "django-models" ]
Is there a way to define a couple of fields as unique in Django? I have a table of volumes (of journals) and I don't want more then one volume number for the same journal. ``` class Volume(models.Model): id = models.AutoField(primary_key=True) journal_id = models.ForeignKey(Journals, db_column='jid', null=Tru...
There is a simple solution for you called [unique\_together](https://docs.djangoproject.com/en/dev/ref/models/options/#unique-together) which does exactly what you want. **For example:** ``` class MyModel(models.Model): field1 = models.CharField(max_length=50) field2 = models.CharField(max_length=50) class Met...