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 listing dirs in a different order based upon platform
5,667,514
9
2011-04-14T18:02:39Z
11,501,313
10
2012-07-16T09:16:13Z
[ "python", "os.walk" ]
I am writing and testing code on XPsp3 w/ python 2.7. I am running the code on 2003 server w/ python 2.7. My dir structure will look something like this ``` d:\ssptemp d:\ssptemp\ssp9-1 d:\ssptemp\ssp9-2 d:\ssptemp\ssp9-3 d:\ssptemp\ssp9-4 d:\ssptemp\ssp10-1 d:\ssptemp\ssp10-2 d:\ssptemp\ssp10-3 d:\ssptemp\ssp10-4...
``` for path, dirs, files in os.walk('d:\ssptemp'): # sort dirs and files dirs.sort() files.sort() print "parsing dir(s)" # ... ```
Python urllib2 automatic form filling and retrieval of results
5,667,699
9
2011-04-14T18:17:17Z
5,668,588
16
2011-04-14T19:27:40Z
[ "python", "forms", "automation", "urllib2", "urllib" ]
I'm looking to be able to query a site for warranty information on a machine that this script would be running on. It should be able to fill out a form if needed ( like in the case of say HP's service site) and would then be able to retrieve the resulting web page. I already have the bits in place to parse the resulti...
If you absolutely **need** to use urllib2, the basic gist is this: ``` import urllib import urllib2 url = 'http://whatever.foo/form.html' form_data = {'field1': 'value1', 'field2': 'value2'} params = urllib.urlencode(form_data) response = urllib2.urlopen(url, params) data = response.read() ``` If you send along POST ...
Use Python's string.replace vs re.sub
5,668,947
27
2011-04-14T19:58:42Z
5,668,962
31
2011-04-14T19:59:56Z
[ "python", "regex" ]
For Python 2.5, 2.6, should I be using `string.replace` or `re.sub` for basic text replacements? In PHP, this was explicitly stated but I can't find a similar note for Python.
As long as you can make do with `str.replace()`, you should use it. It avoids all the pitfalls of regular expressions (like escaping), and is generally faster.
Use Python's string.replace vs re.sub
5,668,947
27
2011-04-14T19:58:42Z
5,669,044
7
2011-04-14T20:07:56Z
[ "python", "regex" ]
For Python 2.5, 2.6, should I be using `string.replace` or `re.sub` for basic text replacements? In PHP, this was explicitly stated but I can't find a similar note for Python.
Another thing to consider is that if you're doing rather complex replacements, [str.translate()](http://docs.python.org/library/stdtypes.html#str.translate) might be what you're looking for.
Use Python's string.replace vs re.sub
5,668,947
27
2011-04-14T19:58:42Z
5,669,104
26
2011-04-14T20:13:31Z
[ "python", "regex" ]
For Python 2.5, 2.6, should I be using `string.replace` or `re.sub` for basic text replacements? In PHP, this was explicitly stated but I can't find a similar note for Python.
`str.replace()` should be used whenever it's possible to. It's more explicit, simpler, and faster. ``` In [1]: import re In [2]: text = """For python 2.5, 2.6, should I be using string.replace or re.sub for basic text replacements. In PHP, this was explicitly stated but I can't find a similar note for python. """ In...
Use Python's string.replace vs re.sub
5,668,947
27
2011-04-14T19:58:42Z
5,670,379
20
2011-04-14T22:19:09Z
[ "python", "regex" ]
For Python 2.5, 2.6, should I be using `string.replace` or `re.sub` for basic text replacements? In PHP, this was explicitly stated but I can't find a similar note for Python.
String manipulation is **usually** preferable to regex when you can figure out how to adapt it. Regex is incredibly powerful, but it's **usually** slower, and **usually** harder to write, debug, and maintain. That being said, notice the amount of "usually" in the above paragraph! It's possible (and I've seen it done) ...
How to export a table to csv or excel format
5,669,773
8
2011-04-14T21:14:05Z
5,671,651
10
2011-04-15T02:01:58Z
[ "python", "oracle11g", "cx-oracle" ]
I need to export a oracle table to a csv/excel file format (along with the column headings). A solution through cx\_oracle or through sqlplus welcome. Python code from the comment: ``` con = cx.connect() cur = con.cursor() printer = cur.execute(sqlcode) con.commit() ```
perhaps use csv module (from standard library): ``` import csv cursor = connection.cursor() # assuming you know how to connect to your oracle db cursor.execute('select * from table_you_want_to_turn_to_csv') with open('output_file.csv', 'wb') as fout: writer = csv.writer(fout) writer.writerow([ i[0] for i in cu...
When to close cursors using MySQLdb
5,669,878
44
2011-04-14T21:23:24Z
16,718,647
20
2013-05-23T15:59:30Z
[ "python", "mysql", "mysql-python" ]
I'm building a WSGI web app and I have a MySQL database. I'm using MySQLdb, which provides cursors for executing statements and getting results. **What is the standard practice for getting and closing cursors?** In particular, how long should my cursors last? Should I get a new cursor for each transaction? I believe y...
It's better to rewrite it using 'with' keyword. 'With' will take care about closing cursor (it's important because it's unmanaged resource) automatically. The benefit is it will close cursor in case of exception too. ``` from contextlib import closing import MySQLdb ''' At the beginning you open a DB connection. Part...
When to close cursors using MySQLdb
5,669,878
44
2011-04-14T21:23:24Z
22,618,781
32
2014-03-24T19:26:39Z
[ "python", "mysql", "mysql-python" ]
I'm building a WSGI web app and I have a MySQL database. I'm using MySQLdb, which provides cursors for executing statements and getting results. **What is the standard practice for getting and closing cursors?** In particular, how long should my cursors last? Should I get a new cursor for each transaction? I believe y...
Instead of asking what is standard practice, since that's often unclear and subjective, you might try looking to the module itself for guidance. In general, using the `with` keyword as another user suggested is a great idea, but in this specific circumstance it may not give you quite the functionality you expect. As o...
Pyramid and FormAlchemy admin interface
5,671,300
5
2011-04-15T00:45:52Z
5,678,806
11
2011-04-15T15:13:42Z
[ "python", "authorization", "acl", "pyramid", "formalchemy" ]
I have a pyramid project using the formalchemy admin interface. I added the basic ACL authentication and the pyramid\_formalchemy plugin always denys even though I am authenticated. Any thoughts on how only allow authenticated users to use the pyramid\_formalchemy admin interface? The authorization policy was add lik...
`pyramid_formalchemy` uses the permissions `'view', 'edit', 'delete', 'new'` to determine who can do what. The `__acl__` is propagated down from your SQLAlchemy model object. Thus, you need to put an `__acl__` on each of your model objects allowing your desired groups access to those permissions. For example, from the ...
Trouble Setting Up MySQLdb Module
5,671,480
2
2011-04-15T01:21:11Z
5,671,963
11
2011-04-15T03:08:31Z
[ "python", "mysql", "osx", "python-module", "mysql-python" ]
I'm pulling my hair out over here trying to set up MySQLdb on my Mac in order to connect to a remote MySQL server. 1. I have installed the latest C MySQL client libraries 2. I have installed XCode 4 3. I did naively try to install the module before installing XCode or the client libraries I am attempting to set up th...
You've set yourself up for headaches by installing the new and forward-looking `Xcode 4` rather than the latest version of `Xcode 3` which is what Mac OS X 10.6 was released with. The immediate issue you are running into is that Python tries to build C extension modules with the same configuration that Python itself wa...
Enumerating all paths in a tree
5,671,486
6
2011-04-15T01:22:03Z
5,671,568
7
2011-04-15T01:39:33Z
[ "python", "algorithm", "reference", "tree", "traversal" ]
I was wondering how to best implement a tree data structure to be able to enumerate paths of all levels. Let me explain it with the following example: ``` A / \ B C | /\ D E F ``` I want to be able to generate the following: ``` A B C D E F A-B A-C B-D C-E C-F A-B-D A-C-E A-C-F ``` As of...
Whenever you find a problem on trees, just use recursion :D ``` def paths(tree): #Helper function #receives a tree and #returns all paths that have this node as root and all other paths if tree is the empty tree: return ([], []) else: #tree is a node root = tree.value rooted_paths = [[root]] ...
Is using __add__ in Python on an int a bad idea?
5,672,009
4
2011-04-15T03:15:47Z
5,672,123
9
2011-04-15T03:35:53Z
[ "python" ]
I'm looking to increment a value by one and Python does not have the ++ operator. Consider the following example: ``` # In a method called calculate(self, basecost, othertaxes=None) # Returns the value of the tax (self) applied to basecost in relation to previous taxes i = -1 basecost += sum((tax.calculate(basecost, o...
Seems to be this: ``` basecost += sum((tax.calculate(basecost, othertaxes[:i]) for i,tax in enumerate(othertaxes)) ```
Most elegant way to modify elements of nested lists in place
5,672,363
27
2011-04-15T04:22:11Z
5,672,403
12
2011-04-15T04:29:14Z
[ "python", "nested-lists" ]
I have a 2D list that looks like this: ``` table = [['donkey', '2', '1', '0'], ['goat', '5', '3', '2']] ``` I want to change the last three elements to integers, but the code below feels very ugly: ``` for row in table: for i in range(len(row)-1): row[i+1] = int(row[i+1]) ``` But I'd rather have somethi...
Try: ``` >>> for row in table: ... row[1:]=map(int,row[1:]) ... >>> table [['donkey', 2, 1, 0], ['goat', 5, 3, 2]] ``` AFAIK, assigning to a `list` slice forces the operation to be done in place instead of creating a new `list`.
Most elegant way to modify elements of nested lists in place
5,672,363
27
2011-04-15T04:22:11Z
5,672,439
17
2011-04-15T04:36:08Z
[ "python", "nested-lists" ]
I have a 2D list that looks like this: ``` table = [['donkey', '2', '1', '0'], ['goat', '5', '3', '2']] ``` I want to change the last three elements to integers, but the code below feels very ugly: ``` for row in table: for i in range(len(row)-1): row[i+1] = int(row[i+1]) ``` But I'd rather have somethi...
``` for row in table: row[1:] = [int(c) for c in row[1:]] ``` Does above look more pythonic?
Most elegant way to modify elements of nested lists in place
5,672,363
27
2011-04-15T04:22:11Z
5,673,213
9
2011-04-15T06:40:41Z
[ "python", "nested-lists" ]
I have a 2D list that looks like this: ``` table = [['donkey', '2', '1', '0'], ['goat', '5', '3', '2']] ``` I want to change the last three elements to integers, but the code below feels very ugly: ``` for row in table: for i in range(len(row)-1): row[i+1] = int(row[i+1]) ``` But I'd rather have somethi...
I like Shekhar answer a lot. As a general rule, when writing Python code, if you find yourself writing f`or i in range(len(somelist))`, you're doing it wrong: * try `enumerate` if you have a single list * try `zip` or `itertools.izip` if you have 2 or more lists you want to iterate on in parallel In your case, the f...
How to write a Fabric script that uncomments a particular line of a user's .bashrc file?
5,673,304
4
2011-04-15T06:53:11Z
5,674,150
15
2011-04-15T08:24:30Z
[ "python", "bash", "fabric" ]
How would you write a Fabric script that uncomments the line ``` #force_color_prompt=yes ``` from the logged-in user's .bashrc file? Note: This question is specifically about editing this particular line, not about simply appending force\_color\_prompt=yes to the end of the file and ignoring this line.
fabric do have api for that. `fabric.contrib.files.uncomment` ``` from fabric.contrib.files import uncomment uncomment("~/.bashrc", "^#force_color_prompt=yes", char='#') ```
Seasonal Adjustment in R or Python
5,673,658
2
2011-04-15T07:29:08Z
5,674,233
13
2011-04-15T08:34:35Z
[ "python", "time-series" ]
does anybody know of a routine to do seasonal adjustment in Python or even better, in R? Here is an example data (South African CPI), which tends to have spikes in the first few months of the year: ![SA m/m CPI](http://i.stack.imgur.com/W5Pwh.gif) So I would like to find the underlying pressures stripping out the seas...
Step 1. Define the data. (Obtained from <http://www.statssa.gov.za/publications/P0141/P0141February2011.pdf>) ``` CPI <- c(102.3, 103.1, 104.3, 105.7, 106.2, 106.6, 107, 108.2, 108.5, 108.9, 108.9, 108.9, 109.2, 109.5, 110.2, 111.1, 111.3, 111.5, 111.5, 112.2, 112.3, 112.4, 112.6, 112.8, 113, 113.5,...
Is there something better than django-piston?
5,674,442
27
2011-04-15T08:54:56Z
5,674,575
28
2011-04-15T09:06:15Z
[ "python", "django", "rest" ]
With 145 forks, 125 open issues, and the last release almost 2years ago, django-piston appears to be approaching abandonware and since the project I'm working on is likely to be a big one, I'd like to standardise on something that's going to be around for a while. Is there something resembling a consensus in the Python...
check <http://djangopackages.com/grids/g/api/> (django-tastypie looks very promising) I also don't like Piston very much. Don't misunderstand me. It is (or was) a good app, though it has its issues. The main problem I had working with it that it hides Debugging information coming from django. If you are absolutely un...
Is there something better than django-piston?
5,674,442
27
2011-04-15T08:54:56Z
5,674,854
17
2011-04-15T09:32:36Z
[ "python", "django", "rest" ]
With 145 forks, 125 open issues, and the last release almost 2years ago, django-piston appears to be approaching abandonware and since the project I'm working on is likely to be a big one, I'd like to standardise on something that's going to be around for a while. Is there something resembling a consensus in the Python...
Two other REST packages that may be of interest : * <http://django-rest-framework.org/> * <http://benoitc.github.com/dj-webmachine/index.html>
Is there something better than django-piston?
5,674,442
27
2011-04-15T08:54:56Z
10,386,233
10
2012-04-30T15:27:22Z
[ "python", "django", "rest" ]
With 145 forks, 125 open issues, and the last release almost 2years ago, django-piston appears to be approaching abandonware and since the project I'm working on is likely to be a big one, I'd like to standardise on something that's going to be around for a while. Is there something resembling a consensus in the Python...
It is worth mentioning about [django-tastypie](https://github.com/toastdriven/django-tastypie) This is getting faster acceptance than the others.
efficient python array to numpy array conversion
5,674,960
10
2011-04-15T09:41:51Z
5,675,147
19
2011-04-15T10:02:06Z
[ "python", "numpy" ]
I get a big array (image with 12 Mpix) in the array format from the python standard lib. Since I want to perform operations on those array, I wish to convert it to a numpy array. I tried the following: ``` import numpy import array from datetime import datetime test = array.array('d', [0]*12000000) t = datetime.now() ...
``` np.array(test) # 1.19s np.fromiter(test, dtype=np.int) # 1.08s np.frombuffer(test) # 459ns !!! ```
Django models - problem importing
5,675,328
7
2011-04-15T10:23:41Z
5,675,450
20
2011-04-15T10:33:25Z
[ "python", "django", "class", "django-models" ]
I've refactored my models files into a module - this way it's much easier to maintain the code since it has grown quite a bit. The funny thing is though that it won't work for one of the classes that references another class that references the fist one in it's turn: UPD: the cycling references are confusing python a...
To avoid cyclic imports, specify FK model as a string, e.g ``` collection = models.ForeignKey('Collection') # Collection is in the same module ``` or ``` collection = models.ForeignKey('myapp.Collection') # Collection is in another app ```
Python read from command line arguments or stdin
5,675,938
6
2011-04-15T11:22:39Z
5,675,954
8
2011-04-15T11:25:11Z
[ "python", "input", "stdin", "command-line-arguments" ]
When writing text-oriented command line programs in Python, I often want to read either all the files passed on the command line, or (XOR) standard input (like Unix `cat` does, or Perl's `<>`). So, I say ``` if len(args) == 0: # result from optparse input = sys.stdin else: input = itertools.chain(*(open(a) fo...
You need [fileinput](http://docs.python.org/library/fileinput.html). A standard use case is: ``` import fileinput for line in fileinput.input(): process(line) ```
How can I fill out a Python string with spaces?
5,676,646
201
2011-04-15T12:22:01Z
5,676,673
50
2011-04-15T12:24:46Z
[ "python", "string", "string-formatting" ]
I want to fill out a string with spaces. I know that the following works for zero's: ``` >>> print "'%06d'"%4 '000004' ``` But what should I do when I want this?: ``` 'hi ' ``` of course I can measure string length and do `str+" "*leftover`, but I'd like the shortest way.
You can try this: ``` print "'%-100s'" % 'hi' ```
How can I fill out a Python string with spaces?
5,676,646
201
2011-04-15T12:22:01Z
5,676,676
311
2011-04-15T12:24:56Z
[ "python", "string", "string-formatting" ]
I want to fill out a string with spaces. I know that the following works for zero's: ``` >>> print "'%06d'"%4 '000004' ``` But what should I do when I want this?: ``` 'hi ' ``` of course I can measure string length and do `str+" "*leftover`, but I'd like the shortest way.
You can do this with [**`str.ljust(width[, fillchar])`**](http://docs.python.org/library/stdtypes.html#str.ljust): > Return the string left justified in a string of length *width*. Padding is done using the specified *fillchar* (default is a space). The original string is returned if *width* is less than `len(s)`. ``...
How can I fill out a Python string with spaces?
5,676,646
201
2011-04-15T12:22:01Z
5,676,707
30
2011-04-15T12:27:45Z
[ "python", "string", "string-formatting" ]
I want to fill out a string with spaces. I know that the following works for zero's: ``` >>> print "'%06d'"%4 '000004' ``` But what should I do when I want this?: ``` 'hi ' ``` of course I can measure string length and do `str+" "*leftover`, but I'd like the shortest way.
Use [**`str.ljust()`**](http://docs.python.org/library/stdtypes.html#str.ljust): ``` >>> 'Hi'.ljust(6) 'Hi ' ``` You should also consider [**`string.zfill()`**](http://docs.python.org/library/stdtypes.html#str.zfill), [**`str.ljust()`**](http://docs.python.org/library/stdtypes.html#str.ljust) and [**`str.center()`...
How can I fill out a Python string with spaces?
5,676,646
201
2011-04-15T12:22:01Z
5,676,884
150
2011-04-15T12:41:24Z
[ "python", "string", "string-formatting" ]
I want to fill out a string with spaces. I know that the following works for zero's: ``` >>> print "'%06d'"%4 '000004' ``` But what should I do when I want this?: ``` 'hi ' ``` of course I can measure string length and do `str+" "*leftover`, but I'd like the shortest way.
Unless you need to support Python 2.5, you can (and probably should) use the [powerful new string-formatting mini-language](http://docs.python.org/2/library/string.html#formatstrings), like so: ``` '{0: <16}'.format('Hi') ```
How can I fill out a Python string with spaces?
5,676,646
201
2011-04-15T12:22:01Z
11,635,057
10
2012-07-24T16:14:48Z
[ "python", "string", "string-formatting" ]
I want to fill out a string with spaces. I know that the following works for zero's: ``` >>> print "'%06d'"%4 '000004' ``` But what should I do when I want this?: ``` 'hi ' ``` of course I can measure string length and do `str+" "*leftover`, but I'd like the shortest way.
you can also **center** your string: ``` '{0: ^20}'.format('nice') ```
How can I fill out a Python string with spaces?
5,676,646
201
2011-04-15T12:22:01Z
25,293,744
28
2014-08-13T18:40:28Z
[ "python", "string", "string-formatting" ]
I want to fill out a string with spaces. I know that the following works for zero's: ``` >>> print "'%06d'"%4 '000004' ``` But what should I do when I want this?: ``` 'hi ' ``` of course I can measure string length and do `str+" "*leftover`, but I'd like the shortest way.
The new(ish) [string format method](https://docs.python.org/2/library/string.html#string-formatting) lets you do some fun stuff with nested keyword arguments. The simplest case: ``` >>> '{message: <16}'.format(message='Hi') 'Hi ' ``` If you want to pass in `16` as a variable: ``` >>> '{message: <{width}}...
python how to force subprocess.call to not wait for the called command to complete
5,677,391
4
2011-04-15T13:18:50Z
5,677,732
9
2011-04-15T13:47:57Z
[ "python", "subprocess" ]
Im using subprocess.call to execute a bat file. subprocess.call is waiting for the bat file to complete before it continues. I want it to start the bat then continue on. Looking at the documents for subprocess it didnt look like it had an option to not wait for the command to complete. Is there a way to do this or ano...
subprocess.Popen is what you are looking for!
How can I test my python module without installing it
5,677,809
7
2011-04-15T13:54:51Z
5,677,975
14
2011-04-15T14:08:31Z
[ "python", "testing" ]
I'm in the process of redesigning/refactoring my Python quantum chemistry package (pyquante). One of the things I don't like about the existing release is that I have to install the package to run the test suite. That is, the test suite has statements like `from PyQuante import SCF`, and, of course, this PyQuante could...
Create a proper package for your stuff and use ``` python setup.py develop ``` to make it a proper dev-package. See: * <http://stackoverflow.com/a/19048754/548039> * <http://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode>
How to run a python script at a specific time(s)
5,677,853
6
2011-04-15T13:57:57Z
5,677,899
7
2011-04-15T14:02:04Z
[ "python" ]
I'd like to write a simple python script for doing a specific job. I'm getting some time and link information from a web site. ``` times= [ ('17.04.2011', '06:41:44', 'abc.php?xxx'), ('17.04.2011', '07:21:31', 'abc.php?yyy'), ('17.04.2011', '07:33:04', 'abc.php?zzz'), ('17.04.2011', '07:41:23', 'abc.php?www'),] ``` W...
Take a look at Python's [sched](http://docs.python.org/library/sched.html) module.
Easy SQLite wrappers for Python
5,678,032
2
2011-04-15T14:12:09Z
5,678,109
11
2011-04-15T14:18:30Z
[ "python", "sqlite", "wrapper" ]
Are there any other SQLite wrappers for Python available, comparable to Rococheting's mySQL wrapper for php? <http://www.ricocheting.com/code/php/mysql-database-class-wrapper-v3> If no such thing exists at the time I guess I'll create my own wrapper, but I want to make sure I'm not doing redundant work.
[SQLite is part of Python standard library since Python 2.5](http://docs.python.org/library/sqlite3.html). The API is similar to your linked PHP MySQL class wrapper (you will be working with modules and functions instead of static class methods). If you're looking for an alternative API, you can use [SQLAlchemy](http:...
Django: Tweaking @login_required decorator
5,678,585
11
2011-04-15T14:56:51Z
5,678,753
20
2011-04-15T15:09:35Z
[ "python", "django", "user", "decorator" ]
I want to begin a private Beta for my website. I have a splash page where a user can enter a code to then access the rest of the site. Currently, all the other site pages (except the splash page) consist of a series of redirects set up by requiring user login (via @login\_required decorator). I want both logged in use...
Write your own decorator - it's fairly straight forward. In fact, if you look at the Django source for `login_required`, you should be able to fiddle around with a copy for your own purposes. ``` def my_login_required(function): def wrapper(request, *args, **kw): user=request.user if not (user.id...
how to parse big datasets using RDFLib?
5,678,623
6
2011-04-15T14:59:36Z
5,679,249
7
2011-04-15T15:47:39Z
[ "python", "parsing", "graph", "rdf", "rdflib" ]
I'm trying to parse several big graphs with RDFLib 3.0, apparently it handles first one and dies on the second (MemoryError)... looks like MySQL is not supported as store anymore, can you please suggest a way to somehow parse those? ``` Traceback (most recent call last): File "names.py", line 152, in <module> ma...
How many triples on those RDF files ? I have tested `rdflib` and it won't scale much further than few tens of ktriples - if you are lucky. No way it really performs well for files with millions of triples. The best parser out there is `rapper` from [Redland Libraries](http://librdf.org/). My first advice is to not use...
Listing Related Fields in Django ModelAdmin
5,678,968
2
2011-04-15T15:25:48Z
5,684,745
7
2011-04-16T05:47:49Z
[ "python", "django", "django-admin" ]
I'm listing a model in Django's admin via a TabularInline. Inside this inline, I'd like to use Django's model traversal syntax to list data in other models referenced in the model via foreign keys. e.g. ``` class MyRelatedModel(models.Model) name = models.CharField(max_length=50) created = models.DateField(aut...
As per Roseman's suggestion above, you can display related (one-to-one or many-to-one) data in a readonly manner with Inline admin models. Here's a little example, just to make sure that we are all on the same page. You can see below that there are three ways to achieve your goal (if I understand that goal correctly). ...
Developing Python Module
5,679,359
12
2011-04-15T15:56:33Z
5,679,404
18
2011-04-15T15:59:32Z
[ "python" ]
I'd like to start developing an existing Python module. It has a source folder and the setup.py script to build and install it. The build script just copies the source files since they're all python scripts. Currently, I have put the source folder under version control and whenever I make a change I re-build and re-in...
Use a [virtualenv](http://pypi.python.org/pypi/virtualenv) and use `python setup.py develop` to link your module to the virtual Python environment. This will make your project's Python packages/modules show up on the sys.path without having to run install. Example: ``` % virtualenv ~/virtenv % . ~/virtenv/bin/activat...
Merging a list of time-range tuples that have overlapping time-ranges
5,679,638
26
2011-04-15T16:21:08Z
5,679,899
7
2011-04-15T16:48:00Z
[ "python", "algorithm", "merge" ]
I have a list of tuples where each tuple is a `(start-time, end-time)`. I am trying to merge all overlapping time ranges and return a list of distinct time ranges. For example ``` [(1, 5), (2, 4), (3, 6)] ---> [(1,6)] [(1, 3), (2, 4), (5, 8)] ---> [(1, 4), (5,8)] ``` Here is how I implemented it. ``` # Algorithm #...
A few ways to make it more efficient, Pythonic: 1. Eliminate the `set()` construction, since the algorithm should prune out duplicates during in the main loop. 2. If you just need to iterate over the results, use `yield` to generate the values. 3. Reduce construction of intermediate objects, for example: move the `tup...
OR statement handling two != clauses Python
5,681,271
2
2011-04-15T19:12:03Z
5,681,291
12
2011-04-15T19:14:57Z
[ "python", "operator-keyword", "clause" ]
(Using Python 2.7) I understand this is pretty elementary but why wouldn't the following statement work as written: ``` input = int(raw_input()) while input != 10 or input != 20: print 'Incorrect value, try again' bet = int(raw_input()) ``` Basically I only want to accept 10 or 20 as an answer. Now, regardles...
You need **`and`**: ``` while input != 10 and input != 20: ``` Think it through: If the `input` is `10`, then the first expression is `false`, causing Python to evaluate the second expression `input != 20`. `10` is different form `20`, so this expressions evaluates to `true`. As `false or true == true`, the whole exp...
OR statement handling two != clauses Python
5,681,271
2
2011-04-15T19:12:03Z
5,681,310
9
2011-04-15T19:17:25Z
[ "python", "operator-keyword", "clause" ]
(Using Python 2.7) I understand this is pretty elementary but why wouldn't the following statement work as written: ``` input = int(raw_input()) while input != 10 or input != 20: print 'Incorrect value, try again' bet = int(raw_input()) ``` Basically I only want to accept 10 or 20 as an answer. Now, regardles...
....or a different way to express it that may seem more natural to you: ``` while input not in (10, 20): # your code here... ```
How to speed up numpy array-filling in python?
5,683,136
7
2011-04-15T22:59:25Z
5,685,025
7
2011-04-16T06:57:49Z
[ "python", "optimization", "numpy" ]
I'm trying to fill a preallocated bytearray using the following code: ``` # preallocate a block array dt = numpy.dtype('u8') in_memory_blocks = numpy.zeros(_AVAIL_IN_MEMORY_BLOCKS, dt) ... # write all the blocks out, flushing only as desired blocks_per_flush_xrange = xrange(0, blocks_per_flush) for _ in xrange(0, nu...
Due to the fact that `0.._BLOCK_MAX` covers all the possible values for `numpy.uint8` (I assume that `numpy.dtype('u8')` (i.e., `numpy.uint64` is a typo) you could use: ``` import numpy as np for _ in xrange(0, num_flushes): in_memory_blocks = np.frombuffer(np.random.bytes(blocks_per_flush), ...
Why does str() round up floats?
5,683,869
3
2011-04-16T01:30:43Z
5,683,877
7
2011-04-16T01:32:43Z
[ "python", "string", "rounding" ]
The built-in Python str() function outputs some weird results when passing in floats with many decimals. This is what happens: ``` >>> str(19.9999999999999999) >>> '20.0' ``` I'm expecting to get: ``` >>> '19.9999999999999999' ``` Does anyone know why? and maybe workaround it? Thanks!
It's not `str()` that rounds, it's the fact that you're using floats in the first place. Float types are fast, but have limited precision; in other words, they are *imprecise by design*. This applies to all programming languages. For more details on float quirks, please read "[What Every Programmer Should Know About Fl...
every element of list is True boolean
5,683,875
13
2011-04-16T01:32:33Z
5,683,888
8
2011-04-16T01:35:06Z
[ "python" ]
I know that ``` all(map(compare,new_subjects.values()))==True ``` would tell me if every element of the list is True. However, how do I tell whether every element except for one of them is True?
``` values = map(compare, new_subjects.values()) len([x for x in values if x]) == len(values) - 1 ``` Basically, you filter the list for true values and compare the length of that list to the original to see if it's one less.
Finding k-nearest neighbors for a given vector?
5,684,370
11
2011-04-16T04:00:58Z
5,684,386
7
2011-04-16T04:03:55Z
[ "python", "mysql", "algorithm", "language-agnostic", "search" ]
Given that I have the following in my knowledge-database: ``` 1 0 6 20 0 0 6 20 1 0 3 6 0 0 3 6 1 0 15 45 0 0 15 45 1 0 17 44 0 0 17 44 1 0 2 5 0 0 2 5 ``` I want to be able to find the nearest neighbors of the following vector: ``` 1 0 5 16 0 0 5 16 ``` according to a distance metric....
In Python (from www.comp.mq.edu.au/): ``` def count_different_values(k_v1s, k_v2s): """kv1s and kv2s should be dictionaries mapping keys to values. count_different_values() returns the number of keys in k_v1s and k_v2s that don't have the same value""" ks = set(k_v1s.iterkeys()) | set(k_v2s.iterkeys...
Installing django-haystack
5,684,471
7
2011-04-16T04:26:46Z
5,768,048
18
2011-04-24T01:23:30Z
[ "python", "django", "django-haystack" ]
Super simple question: I went through the "getting start" doc for haystack (using whoosh; I installed both python-whoosh and haystack using pip (first time using it)), and I simply cannot run python manage.py rebuild\_index. I get this error: ``` python manage.py rebuild_index Unknown command: 'rebuild_index' Type 'ma...
Did you perhaps install the wrong thing? This (embarrassingly) happend to me just today. Make sure you install 'django-haystack' and not just 'haystack' (and you will have to remove 'haystack', since it conflicts with 'django-haystack').
Django Debug Toolbar Only Working for Admin Section
5,684,798
9
2011-04-16T05:59:03Z
6,122,974
8
2011-05-25T10:26:56Z
[ "python", "django", "django-debug-toolbar" ]
Hey, I've been using Django 1.2.1 for some time now and came across Django Debug Toolbar just the other day. It looks really useful and I'm really eager to try some stuff out. I installed exactly how the readme said. Step by Step. I put the middleware at the end just in case things get caught up but I'm using quite st...
Debug toolbar requires that there's at least a closing </body> tag in the response HTML. This tag can be changed by changing `settings.DEBUG_TOOLBAR_CONFIG['INSERT_BEFORE']` <http://django-debug-toolbar.readthedocs.org/en/latest/configuration.html#toolbar-options>
Django : Filter query based on custom function
5,685,037
18
2011-04-16T07:02:18Z
5,685,046
15
2011-04-16T07:05:57Z
[ "python", "django", "django-queryset" ]
I've got a function built into my Django model class and I want to use that function to filter my query results. ``` class service: ...... def is_active(self): if datetime.now() > self.end_time: return False return True ``` Now I want to use this function into...
You may not be able to, instead you can post-process the queryset with a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) or [generator expression](http://docs.python.org/reference/expressions.html#generator-expressions). For example: ``` [x for x in Q if x.somecond()] ```
Django : Filter query based on custom function
5,685,037
18
2011-04-16T07:02:18Z
5,685,201
14
2011-04-16T07:46:47Z
[ "python", "django", "django-queryset" ]
I've got a function built into my Django model class and I want to use that function to filter my query results. ``` class service: ...... def is_active(self): if datetime.now() > self.end_time: return False return True ``` Now I want to use this function into...
I would suggest you to use a custom manager for your class, like this you could use : `nserv = service.objects.are_active()` This would be achieved with something like: ``` class ServiceManager(models.Manager): def are_active(self): # use your method to filter results return you_custom_queryset ``` See [cus...
Django : Filter query based on custom function
5,685,037
18
2011-04-16T07:02:18Z
28,348,186
7
2015-02-05T15:46:26Z
[ "python", "django", "django-queryset" ]
I've got a function built into my Django model class and I want to use that function to filter my query results. ``` class service: ...... def is_active(self): if datetime.now() > self.end_time: return False return True ``` Now I want to use this function into...
I just had a similar issue. The problem was i had to return a QuerySet instance. A quick solution for me was to do something like: ``` active_serv_ids = [service.id for service in Service.objects.all() if service.is_active()] nserv = Service.objects.filter(id__in=active_serv_ids) ``` pretty sure this is not the prett...
Putting other widgets in gtk.Menu
5,685,103
6
2011-04-16T07:21:41Z
5,848,296
8
2011-05-01T12:19:45Z
[ "python", "pygtk", "appindicator" ]
I'd like to be able to put a gtk.ProgressBar in my gtk.Menu, but since menus only takes gtk.MenuItems and its subclasses, what I've done instead is take a plain gtk.MenuItem and tried adding my progress bar as a child to that. Since gtk.MenuItem is a subclass of gtk.Bin, it should be able to hold pretty much any widget...
This is a limitation of Ubuntu's Application Indicators, see [this question at askubuntu](http://askubuntu.com/questions/16431/putting-an-arbitrary-gtk-widget-into-an-appindicator-indicator).
"inconsistent use of tabs and spaces in indentation"
5,685,406
34
2011-04-16T08:47:35Z
5,685,816
68
2011-04-16T10:12:27Z
[ "python" ]
I'm trying to create an application in Python 3.2 and i use tabs all the time for indentation, but even the editor changes some of them into spaces and then print out "inconsistent use of tabs and spaces in indentation" when i try to run the program. How can i change the spaces into tabs? It's driving me crazy. (I'm a...
Don't use tabs. 1. Set your editor to use 4 **spaces** for indentation. 2. Make a search and replace to replace all tabs with 4 spaces. 3. Make sure your editor is set to **display** tabs as 8 spaces. Note: The reason for 8 spaces for tabs is so that you immediately notice when tabs have been inserted unintentionally...
"inconsistent use of tabs and spaces in indentation"
5,685,406
34
2011-04-16T08:47:35Z
18,801,584
7
2013-09-14T12:06:22Z
[ "python" ]
I'm trying to create an application in Python 3.2 and i use tabs all the time for indentation, but even the editor changes some of them into spaces and then print out "inconsistent use of tabs and spaces in indentation" when i try to run the program. How can i change the spaces into tabs? It's driving me crazy. (I'm a...
Recently had the same problem. Found out that I just needed to convert the .py file's charset to **UTF-8** as that's the set Python 3 uses. Btw, I used 4-space tabs all the time, so the problem wasn't caused by them.
Is there a function that can calculate a score for aligned sequences given the alignment parameters?
5,686,211
6
2011-04-16T11:39:53Z
5,698,950
8
2011-04-18T05:38:56Z
[ "python", "bioinformatics", "biopython" ]
I try to score the already-aligned sequences. Let say ``` seq1 = 'PAVKDLGAEG-ASDKGT--SHVVY----------TI-QLASTFE' seq2 = 'PAVEDLGATG-ANDKGT--LYNIYARNTEGHPRSTV-QLGSTFE' ``` with given parameters ``` substitution matrix : blosum62 gap open penalty : -5 gap extension penalty : -1 ``` I did look through the biopython coo...
Jessada, The Blosum62 matrix (note the spelling ;) is in Bio.SubsMat.MatrixInfo and is a dictionary with tuples resolving to scores (so `('A', 'A')` is worth 4 pts). It doesn't have the gaps, and it's only one triangle of the matrix (so it might ahve ('T', 'A') but not ('A', 'T'). There are some helper functions in Bi...
python find last in string
5,686,388
2
2011-04-16T12:14:29Z
5,686,400
8
2011-04-16T12:17:08Z
[ "python", "string", "find" ]
I'm looking for a simple method of identifying the last position of a string inside another string ... for instance. If I had: `file = C:\Users\User\Desktop\go.py` and I wanted to crop this so that `file = go.py` Normally I would have to run `C:\Users\User\Desktop\go.py` through a loop + find statement, and Evey tim...
If it is only about file paths, you can use [`os.path.basename`](http://docs.python.org/library/os.path.html#os.path.basename): ``` >>> import os >>> os.path.basename(file) 'go.py' ``` Or if you are not running the code on Windows, you have to use `ntpath` instead of `os.path`.
Detect socket hangup without sending or receiving?
5,686,490
21
2011-04-16T12:32:46Z
5,686,720
22
2011-04-16T13:10:13Z
[ "python", "c", "linux", "sockets", "tcp" ]
I'm writing a TCP server that can take 15 seconds or more to begin generating the body of a response to certain requests. Some clients like to close the connection at their end if the response takes more than a few seconds to complete. Since generating the response is very CPU-intensive, I'd prefer to halt the task th...
The [select](http://docs.python.org/library/select.html) module contains what you'll need. If you only need Linux support and have a sufficiently recent kernel, `select.epoll()` should give you the information you need. Most Unix systems will support `select.poll()`. If you need cross-platform support, the standard wa...
Detect socket hangup without sending or receiving?
5,686,490
21
2011-04-16T12:32:46Z
8,434,845
13
2011-12-08T17:12:33Z
[ "python", "c", "linux", "sockets", "tcp" ]
I'm writing a TCP server that can take 15 seconds or more to begin generating the body of a response to certain requests. Some clients like to close the connection at their end if the response takes more than a few seconds to complete. Since generating the response is very CPU-intensive, I'd prefer to halt the task th...
I've had a recurring problem communicating with equipment that had separate TCP links for send and receive. The basic problem is that the TCP stack doesn't generally tell you a socket is closed when you're just trying to read - you have to try and write to get told the other end of the link was dropped. Partly, that is...
Detect socket hangup without sending or receiving?
5,686,490
21
2011-04-16T12:32:46Z
8,439,530
11
2011-12-09T00:15:13Z
[ "python", "c", "linux", "sockets", "tcp" ]
I'm writing a TCP server that can take 15 seconds or more to begin generating the body of a response to certain requests. Some clients like to close the connection at their end if the response takes more than a few seconds to complete. Since generating the response is very CPU-intensive, I'd prefer to halt the task th...
The socket KEEPALIVE option allows to detect this kind of "drop the connection without telling the other end" scenarios. You should set the SO\_KEEPALIVE option at SOL\_SOCKET level. In Linux, you can modify the timeouts per socket using TCP\_KEEPIDLE (seconds before sending keepalive probes), TCP\_KEEPCNT (failed kee...
Python Reflection
5,686,723
2
2011-04-16T13:10:43Z
5,686,734
9
2011-04-16T13:13:19Z
[ "python", "reflection" ]
suppose we have many objects in memory. Each one has a distinct id. How can I iterate the memory to find a specific object that is compared to some id ? In order to grab it and use it through getattr ?
You should maintain a collection of these objects as they are created in a class attribute, then provide a class method for retrieving them. Something along the lines of: ``` class Thing(object): all = {} def __init__(self, id, also, etc): self.id = id self.all[id] = self @classmethod ...
Iteration through all 1 dimensional subarrays of a multi-dimensional array
5,687,362
9
2011-04-16T15:01:19Z
5,688,945
10
2011-04-16T19:21:18Z
[ "python", "multidimensional-array", "numpy" ]
What is the fastest way to iterate through all one dimensional sub-arrays of an n dimensional array in python. For example consider the 3-D array: ``` import numpy as np a = np.arange(24) a = a.reshape(2,3,4) ``` The desired sequence of yields from the iterator is : ``` a[:,0,0] a[:,0,1] .. a[:,2,3] a[0,:,0] .. a[...
Here is a compact implementation of such an iterator: ``` def iter1d(a): return itertools.chain.from_iterable( numpy.rollaxis(a, axis, a.ndim).reshape(-1, dim) for axis, dim in enumerate(a.shape)) ``` This will yield the subarrays in the order you gave in your post: ``` for x in iter1d(a): pr...
How can I insert data into a MySQL database?
5,687,718
29
2011-04-16T16:02:18Z
5,687,856
76
2011-04-16T16:21:56Z
[ "python", "mysql" ]
I want to insert the integers 188 and 90 in my MySQL database, but the following code doesn't work: ``` import MySQLdb conn = MySQLdb.connect(host= "localhost", user="root", passwd="newpassword", db="engy1") x = conn.cursor() x.execute("SELECT * FROM anooog1") x.e...
``` #Server Connection to MySQL: import MySQLdb conn = MySQLdb.connect(host= "localhost", user="root", passwd="newpassword", db="engy1") x = conn.cursor() try: x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90)) conn.commit() except: conn.rollbac...
How can I insert data into a MySQL database?
5,687,718
29
2011-04-16T16:02:18Z
17,715,173
18
2013-07-18T05:27:39Z
[ "python", "mysql" ]
I want to insert the integers 188 and 90 in my MySQL database, but the following code doesn't work: ``` import MySQLdb conn = MySQLdb.connect(host= "localhost", user="root", passwd="newpassword", db="engy1") x = conn.cursor() x.execute("SELECT * FROM anooog1") x.e...
# Here is OOP: ``` import MySQLdb class Database: host = 'localhost' user = 'root' password = '123' db = 'test' def __init__(self): self.connection = MySQLdb.connect(self.host, self.user, self.password, self.db) self.cursor = self.connection.cursor() def insert(self, query)...
how do you install django older version using easy_install?
5,688,053
8
2011-04-16T16:51:04Z
5,688,237
25
2011-04-16T17:21:24Z
[ "python", "django", "virtualenv" ]
I just broke my environment because of django 1.3. None of my sites are able to run. So, i decided to use virtualenv to set virtual environment with different python version as well as django. But, seems like if i download the package and install using "sudo python setup.py install" this does not get added to my virt...
It's probably better to use [Pip instead of easy\_install](http://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install). Then make sure you [create you virtualenv](http://guide.python-distribute.org/pip.html#creating-a-virtualenv) with the `--no-site-packages`-option. For convenience you should consider ...
Writing a Python Music Streamer
5,688,573
18
2011-04-16T18:21:07Z
14,406,269
18
2013-01-18T19:31:24Z
[ "python", "http", "streaming", "mp3", "shoutcast" ]
I would like to implement a server in Python that streams music in MP3 format over HTTP. I would like it to broadcast the music such that a client can connect to the stream and start listening to whatever is currently playing, much like a radio station. Previously, I've implemented my own HTTP server in Python using S...
The mp3 format was designed for streaming, which makes some things simpler than you might have expected. The data is essentially a stream of [audio frames](http://www.mp3-tech.org/programmer/frame_header.html) with built-in boundary markers, rather than a file header followed by raw data. This means that once a client ...
How to check if a template exists in Django?
5,690,213
10
2011-04-16T22:58:55Z
5,690,311
15
2011-04-16T23:18:42Z
[ "python", "django" ]
What is the most efficient way to check if a template exists in Django? I was thinking of catching the `TemplateDoesNotExist` exception, but maybe there is a more Djangoistic way to do it? Thanks for your help!
I don't think you'll be able to do this without catching this exception, but you could use [`django.template.loader.get_template(template_name)`](http://docs.djangoproject.com/en/dev/ref/templates/api/#django.template.loader.get_template) in your try statement instead of a optimist call of render\_to\_response. (If you...
How to check if a template exists in Django?
5,690,213
10
2011-04-16T22:58:55Z
10,882,049
23
2012-06-04T13:19:13Z
[ "python", "django" ]
What is the most efficient way to check if a template exists in Django? I was thinking of catching the `TemplateDoesNotExist` exception, but maybe there is a more Djangoistic way to do it? Thanks for your help!
If your intention is to use a template if it exists and default to a second template, you would better use select\_template: ``` django.template.loader.select_template(['custom_template','default_template']) ``` This will load the first existing template in the list.
same python interpreter instance running multiple scripts simultaneously?
5,690,327
5
2011-04-16T23:22:01Z
5,690,384
9
2011-04-16T23:30:30Z
[ "python" ]
6-7 years ago i saw an initiative of a way to run python on tight resources env by running the interpreter only once, while allowing several scripts to use it at the same time. the idea was bot the save the interpreter startup overhead and to save RAM. Does something alike exists? this question [can we execute mutip...
Yes and no. Python itself uses a Global Interpreter Lock (GIL), which you can read a lot about, if you care to. To make a long story short, however, it ensures the interpreter is basically single-threaded. You can create (and run) more than one thread in your Python program, but when/if they use the Python interpreter,...
Best way to do a "not None" test in Python for a normal and Unicode empty string?
5,690,491
13
2011-04-16T23:56:16Z
5,691,419
29
2011-04-17T04:12:36Z
[ "python", "string" ]
In Python 2.7, I'm writing a class that calls a function in an API which might, or might not, return an empty string. Furthermore, the empty string might be unicode `u""`, or non-unicode `""`. I was wondering what the best way to check for this? The following code works great for an empty string, but not an empty unic...
Empty strings are considered false. ``` if string: # String is not empty. else: # String is empty. ```
Variable scopes in python classes
5,690,888
16
2011-04-17T01:37:01Z
5,690,903
13
2011-04-17T01:41:37Z
[ "python", "scope" ]
declaring a variable in a class (outside of a function) : all class functions can access it (basically a public variable) declaring a variable inside a function inside a class : only that function can access it (its in that functions scope) declaring a variable with self.(variable name) inside a function inside a cla...
Declaring a variable at the top level of the class is like declaring a static or class variable. Qualifying it with self is declaring an instance variable. Class variables can be modified by referring to them by class name (e.g. `Class.x = 5`) and all instances will inherit these changes. Instance variables are private...
Variable scopes in python classes
5,690,888
16
2011-04-17T01:37:01Z
5,690,920
48
2011-04-17T01:45:41Z
[ "python", "scope" ]
declaring a variable in a class (outside of a function) : all class functions can access it (basically a public variable) declaring a variable inside a function inside a class : only that function can access it (its in that functions scope) declaring a variable with self.(variable name) inside a function inside a cla...
Since the listing in your question is not 100% clear, I've decided to explain it with a simple example. It also includes some things like `__something` variables you did not mention in your list. ``` class Test: a = None b = None def __init__(self, a): print self.a self.a = a self....
Creating custom connectivity in PyBrain neural networks
5,692,624
25
2011-04-17T09:09:29Z
5,716,233
22
2011-04-19T12:19:49Z
[ "python", "neural-network", "pybrain" ]
I want to create an artificial neural network (in PyBrain) that follows the following layout: ![layout](http://i.stack.imgur.com/LzH77.png) However, I cannot find the proper way to achieve this. The only option that I see in the documentation is the way to create fully connected layers, which is not what I want: I wa...
The solution is to use the connection type of your choice, but with **slicing** parameters: `inSliceFrom`, `inSliceTo`, `outSliceFrom` and `outSliceTo`. I agree the documentation should mention this, so far it's only in the `Connection` class' comments. Here is example code for your case: ``` #create network and modu...
Store python datetime object in sqlite3
5,693,118
2
2011-04-17T11:03:08Z
5,693,214
8
2011-04-17T11:24:51Z
[ "python", "sqlite3" ]
``` token=uuid.uuid4().bytes.encode("base64") expires=datetime.now()+timedelta(days=1) print token print expires con = sqlite3.connect(dbpath,detect_types=sqlite3.PARSE_DECLTYPES) cur = con.cursor() cur.execute( "INSERT INTO token VALUES ('%s', ?)" % (token,expires)) a=cur.fetchone() con.commit() con.close()...
Never use `%` operator with SQL - it can lead to SQL injection. Fix your `execute` statement like this: ``` cur.execute("INSERT INTO token VALUES (?, ?)", (token,expires)) ``` Actually there is another one problem: you can't use `cur.fetchone()` after `INSERT`. Full example: ``` $ sqlite3 test.db sqlite> create tab...
Clicking a button automatically in a web browser with python
5,693,221
5
2011-04-17T11:25:36Z
5,693,244
8
2011-04-17T11:32:03Z
[ "python", "bots" ]
Sort of like a bot, i have already checked out some sites such as pyjamas and scrapy, I know how to print data of websites, but still dont know how to interact with buttons. Can somebody help me with some demonstarative code? Lets say i have a form ``` <form name="input" action="html_form_action.asp" method="get"> Us...
You can use [mechanize](http://wwwsearch.sourceforge.net/mechanize/) for that. It provides an easy way for interacting with websites.
Why is an MD5 hash created by Python different from one created using echo and md5sum in the shell?
5,693,360
89
2011-04-17T11:54:05Z
5,693,363
169
2011-04-17T11:55:02Z
[ "python", "shell", "md5sum" ]
A Python MD5 hash is different than the one created by the md5sum command on the shell. Why? ``` >>> import hashlib >>> h = hashlib.md5() >>> h.update("mystringforhash") >>> print h.hexdigest() 86b6423cb6d211734fc7d81bbc5e11d3 # Result from Python $ echo mystringforhash | md5sum 686687dd68c5de717b34569dbfb8d3c3 - #...
`echo` appends a `\n` since you usually do not want lines not ending with a linebreak in your shell (it looks really ugly if the prompt does not start at the very left). Use the `-n` argument to omit the trailing linebreak and it will print the same checksum as your python script: ``` > echo -n mystringforhash | md5...
zip function help with tuples
5,693,559
6
2011-04-17T12:40:42Z
5,693,585
11
2011-04-17T12:47:45Z
[ "python", "tuples" ]
I am hoping someone can help me with a problem I'm stuck with. I have a large number of tuples (>500) that look like this: ``` (2,1,3,6) (1,2,5,5) (3,0,1,6) (10,1,1,4) (0,3,3,0) ``` A snippet of my code reads: ``` sum1 = (A,B,C,D) # creates a tuple of sums of (A,B,C,D) mysum = map(sum, zip(A, B, C, D)) pri...
``` >>> zip((1,2,3),(10,20,30),(100,200,300)) [(1, 10, 100), (2, 20, 200), (3, 30, 300)] >>> [sum(x) for x in zip((1,2,3),(10,20,30),(100,200,300))] [111, 222, 333] ``` To do this with an arbitrarily large set of tuples: ``` >>> myTuples = [(1,2,3), (10,20,30), (100,200,300)] >>> [sum(x) for x in zip(*myTuples)] [11...
What's difference between a simple webserver and Apache server?
5,693,741
10
2011-04-17T13:20:07Z
5,693,750
7
2011-04-17T13:21:35Z
[ "python", "apache", "webserver" ]
Here the simple webserver means a server that deal with simple HTTP request, just like the following one: ``` import BaseHTTPServer class WebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): if self.path == ‘/foo’: self.send_response(200) self.do_somethin...
Apache is written in C and designed to be scalable while BaseHTTPServer is meant for local/testing/debugging environments. So you shouldn't use BaseHTTPServer for any production sites.
What's difference between a simple webserver and Apache server?
5,693,741
10
2011-04-17T13:20:07Z
5,693,792
9
2011-04-17T13:29:33Z
[ "python", "apache", "webserver" ]
Here the simple webserver means a server that deal with simple HTTP request, just like the following one: ``` import BaseHTTPServer class WebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): if self.path == ‘/foo’: self.send_response(200) self.do_somethin...
> Or in other words, if i want to use python to implement a server which can be put into use of business, what also should i do? There are already python-based web servers, such as CherryPy (which I think is intended to be a web server solution on the same stack level as Apache; it is more python-based though, and Apa...
How to convert text to speech using python on ubuntu 10.10?
5,694,193
3
2011-04-17T14:52:48Z
5,694,571
9
2011-04-17T16:00:40Z
[ "python", "speech-recognition", "text-to-speech" ]
I am new to this kind of programming which involves text to speech or speech to text conversion, that's why I am here for some initial help. I have searched over internet about it and I came across pyttsx for ubuntu, initially I could not get started with it but somehow I managed to do that but now the problem is that ...
espeak is included in ubuntu by default. Try this one from python. ``` import os import datetime def tts(text): return os.system("espeak -s 155 -a 200 "+text+" " ) m = datetime.datetime.now().strftime("%I %M %S") tts("'Sir the time is"+str(int(m[0:2]))+" "+str(int(m[3:5]))+" : ' ") ```
Py_Initialize fails - unable to load the file system codec
5,694,706
25
2011-04-17T16:22:37Z
5,694,730
19
2011-04-17T16:25:28Z
[ "c++", "python" ]
I am attempting to put together a simple c++ test project that uses python 3.2. The project builds fine but Py\_Initialize raises a fatal error: ``` Fatal Python error: Py_Initialize: unable to load the file system codec LookupError: no codec search functions registered: can't find encoding ``` **Minimal code:** ```...
Check PYTHONPATH system variable and make sure it doesn't points to Python 2.x <http://bugs.python.org/issue11288>
Py_Initialize fails - unable to load the file system codec
5,694,706
25
2011-04-17T16:22:37Z
15,331,222
10
2013-03-11T04:30:31Z
[ "c++", "python" ]
I am attempting to put together a simple c++ test project that uses python 3.2. The project builds fine but Py\_Initialize raises a fatal error: ``` Fatal Python error: Py_Initialize: unable to load the file system codec LookupError: no codec search functions registered: can't find encoding ``` **Minimal code:** ```...
Parts of this have been mentioned before, but in a nutshell this is what worked for my environment where I have multiple Python installs and my global OS environment set-up to point to a *different* install than the one I attempt to work with when encountering the problem. Make sure your (local or global) environment ...
Group list by values
5,695,208
25
2011-04-17T17:42:39Z
5,695,268
47
2011-04-17T17:51:50Z
[ "python", "list", "grouping" ]
Let's say I have a list like this: ``` list = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]] ``` How can I most elegantly group this to get this list output in Python: ``` list = [["A", "C"], ["B"], ["D", "E"]] ``` So the values are grouped by the secound value but the order is preserved...
``` values = set(map(lambda x:x[1], list)) newlist = [[y[0] for y in list if y[1]==x] for x in values] ```
Group list by values
5,695,208
25
2011-04-17T17:42:39Z
5,695,343
15
2011-04-17T18:02:54Z
[ "python", "list", "grouping" ]
Let's say I have a list like this: ``` list = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]] ``` How can I most elegantly group this to get this list output in Python: ``` list = [["A", "C"], ["B"], ["D", "E"]] ``` So the values are grouped by the secound value but the order is preserved...
``` from operator import itemgetter from itertools import groupby lki = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]] lki.sort(key=itemgetter(1)) glo = [[x for x,y in g] for k,g in groupby(lki,key=itemgetter(1))] print glo ``` . EDIT Another solution that needs no import , is more readable, keeps the orde...
Group list by values
5,695,208
25
2011-04-17T17:42:39Z
5,695,349
8
2011-04-17T18:03:42Z
[ "python", "list", "grouping" ]
Let's say I have a list like this: ``` list = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]] ``` How can I most elegantly group this to get this list output in Python: ``` list = [["A", "C"], ["B"], ["D", "E"]] ``` So the values are grouped by the secound value but the order is preserved...
Howard's answer is concise and elegant, but it's also O(n^2) in the worst case. For large lists with large numbers of grouping key values, you'll want to sort the list first and then use `itertools.groupby`: ``` >>> from itertools import groupby >>> from operator import itemgetter >>> seq = [["A",0], ["B",1], ["C",0],...
Help me understand why Unicode only works sometimes with Python
5,695,421
11
2011-04-17T18:15:41Z
5,708,560
10
2011-04-18T20:34:13Z
[ "python", "unicode", "windows-7", "ubuntu", "ipython" ]
Here's a little program: ``` #!/usr/bin/env python # -*- encoding: utf-8 -*- print('abcd kΩ ☠ °C √Hz µF ü ☃ ♥') print(u'abcd kΩ ☠ °C √Hz µF ü ☃ ♥') ``` On Ubuntu, Gnome terminal, IPython does what I would expect: ``` In [6]: run Unicodetest.py abcd kΩ ☠ °C √Hz µF ü ☃ ♥ abcd kΩ...
I/O in Python (and most other languages) is based on *bytes*. When you write a byte string (`str` in 2.x, `bytes` in 3.x) to a file, the bytes are simply written as-is. When you write a Unicode string (`unicode` in 2.x, `str` in 3.x) to a file, the data needs to be *encoded* to a byte sequence. For a further explanati...
Python, len and slices on unicode strings
5,695,714
8
2011-04-17T19:01:03Z
5,695,748
16
2011-04-17T19:05:09Z
[ "python", "string", "unicode" ]
I am handling a situation where I need to make a string fit in the allocated gap in the screen, as I'm using unicode len() and slices[] work apparently on bytes and I end up cutting unicode strings too short, because `€` only occupies one space in the screen but 2 for len() or slices[]. I have the encoding headers p...
You're not creating Unicode strings there; you're creating byte strings with UTF-8 encoding (which is variable-length, as you're seeing). You need to use constants of the form `u"..."` (or `u'...'`). If you do that, you get the expected result: ``` % cat test.py # -*- coding: utf-8 -*- a = u"2 €uros" b = u"2 Euros" ...
I'm trying to understand just exactly how to use the cmd module
5,696,233
4
2011-04-17T20:31:31Z
5,696,521
8
2011-04-17T21:18:48Z
[ "python", "module", "cmd" ]
Let me preface this by saying: I'm a neophyte to Pyhon! I've written a bunch of modules to drive a user interactive application via the command line. Additionally, someone recommended that I look at using the cmd module. And I've looked at it on some sites, but still not sure how to use it. I don't have dyslexia or any...
Doug Hellmann's [Python Module of the Week series](http://www.doughellmann.com/PyMOTW/index.html) has [a good example of using the `cmd` module](http://www.doughellmann.com/PyMOTW/cmd/). Another good example is the [ActiveState recipe "Console built with Cmd object"](http://code.activestate.com/recipes/280500-console...
Django-CMS plugin isn't showing up in available plugins
5,696,287
4
2011-04-17T20:40:19Z
5,700,886
8
2011-04-18T09:27:14Z
[ "python", "django", "django-cms" ]
I've been attempting to write a Django CMS plugin, but it's not showing up in the "Available plugins" on the page edits and I'm very unsure why as I've read the source of another few plugins trying to see what I've done wrong. It's as if Django-CMS hasn't registered the plugin. Directory structure: ``` /linkrotator ...
The problem is an import error in your cms\_plugins.py. You do `from linkrator.models import LinksPlugin as LinkListPluginModel`, it should be `from linkrotator.models import LinkListPluginModel`. You should also set a name on LinkListPlugin, or the name will be blank when it shows up under available plugins. Giving us...
How do I use kd-trees for determining string similarity?
5,696,859
5
2011-04-17T22:23:11Z
5,696,876
7
2011-04-17T22:26:30Z
[ "python", "algorithm", "kdtree" ]
I am trying to utilize k-nearest neighbors for the string similarity problem i.e. given a string and a knowledge base, I want to output k strings that are similar to my given string. Are there any tutorials that explain how to utilize kd-trees to efficiently do this k-nearest neighbor lookup for strings? The string len...
Probably one of the hottest blog posts I had read a year or so ago: [Levenstein Automata](http://blog.notdot.net/2010/07/Damn-Cool-Algorithms-Levenshtein-Automata). Take a look at that article. It provides not only a description of the algorithm but also code to follow. Technically, it's not a kd-tree but it's quite re...
How can a #defined C value be exposed to Python in a Cython module?
5,697,479
15
2011-04-18T00:35:54Z
5,705,865
15
2011-04-18T16:20:58Z
[ "python", "cython" ]
I'd like to make the integer constants (ACTIVE\_TAG, etc) defined here: <http://www.bulletphysics.com/Bullet/BulletFull/btCollisionObject_8h_source.html#l00022> available as normal attributes of a Cython defined module I'm working on, so that Python application code can access them (to pass them in to wrapped APIs wh...
Here's one way, which, while seemingly tedious, could feasibly be automated for any given .h file as input: Step 1. Get all the constants you want into a file, say `bulletdefs.h`, which has the `#defines` but with leading underscores, e.g: ``` #define _ACTIVE_TAG 1 #define _ISLAND_SLEEPING 2 #define _WANTS_DEACTIVATI...
How to set filename property in BlobStore?
5,697,844
9
2011-04-18T01:59:55Z
5,697,964
8
2011-04-18T02:30:12Z
[ "python", "google-app-engine", "blobstore" ]
I'm programatically uploading image files and want to set the filename. When I upload a file via POST, the filename property is set automatically. However when using the method below, the filename is not getting set. ``` image = urllib2.urlopen(url) file_name = files.blobstore.create(mime_type='image/p...
Parse the filename from the url (see related question [here](http://stackoverflow.com/questions/163009/urllib2-file-name)). Then you can set it by adding an additional parameter to your files.blobstore.create call: ``` file_name = files.blobstore.create(mime_type='image/png',_blobinfo_uploaded_filename=file_name_from_...
Why matplotlib has no attribute 'pylab'?
5,698,442
4
2011-04-18T04:12:32Z
5,698,737
10
2011-04-18T05:08:39Z
[ "python", "matplotlib" ]
I imported `matplotlib` in the way like this: ``` import matplotlib as mpl ``` A error saying **'module' object has no attribute 'pylab'** was thrown out when i run the following code: ``` x = np.arange(0,10,0.01) # import numpy as np y = np.sin(x) mpl.pylab.plot(x,y) mpl.pylab.show() ``` And there was no error a...
To plot in non-interactive mode, you should use the module `pyplot`, not `pylab`. ``` from matplotlib import pyplot import numpy pyplot.plot(range(1,100), numpy.sin(range(1,100))) pyplot.show() ``` The module `pylab` is not typically used as a submodule of matplotlib, but as a top-level module instead. Typically, it...
using unbound methods in another python class
5,701,201
3
2011-04-18T09:57:24Z
5,702,198
10
2011-04-18T11:32:27Z
[ "python", "methods" ]
I have an unbound method as `<unbound method foo.ops>`, i would like to use the same method with another class. take an example ``` class foo2(object): pass foo2.ops = foo.ops ``` however ``` obj = foo2() obj.ops() raises TypeError: unbound method ops() must be called with foo instance as first argument (got not...
If you want to add the same method to several unrelated classes (e.g. doing AOP), don't copy an unbound method from one of them. Instead, define a plain function and assign it as a method to every class. Usually a better way to do it is a mixin (using plain inheritance) or a metaclass (class decorator syntax is neat)....
Selecting from multidimensional numpy array
5,701,811
4
2011-04-18T10:52:20Z
5,701,939
8
2011-04-18T11:06:06Z
[ "python", "arrays", "multidimensional-array", "matrix", "numpy" ]
I have a multidimensional array a with shape (nt, nz, ny, nx). The dimensions are time, z, y, x. For each time, x and y, I've selected the appropriate z in a new index array J with shape (nt, ny, nx). J contains the indices along the height dimension that I'd like to select. Using Python, I could do this in a loop: ``...
You can use `numpy.indices()` together with advanced indexing: ``` t, y, x = numpy.indices(J.shape) b = a[t, J, y, x] ```
On second initialization of an object, why is __init__ called before __del__?
5,702,944
7
2011-04-18T12:34:04Z
5,702,962
11
2011-04-18T12:35:10Z
[ "python", "oop" ]
Consider the following example code ``` class A: def __init__(self, i): self.i = i print("Initializing object {}".format(self.i)) def __del__(self): print("Deleting object {}".format(self.i)) for i in [1, 2]: a = A(i) ``` Creating the object within the loop was intended to assure...
Creation of the second object happens before the name is rebound and the first object is disposed of. 1. The first `A` is instantiated. 2. `a` is bound. 3. The second `A` is instantiated. 4. `a` is rebound, and the first `A` is disposed of. 5. The program ends, and the second `A` is disposed of.
On second initialization of an object, why is __init__ called before __del__?
5,702,944
7
2011-04-18T12:34:04Z
5,703,017
9
2011-04-18T12:40:11Z
[ "python", "oop" ]
Consider the following example code ``` class A: def __init__(self, i): self.i = i print("Initializing object {}".format(self.i)) def __del__(self): print("Deleting object {}".format(self.i)) for i in [1, 2]: a = A(i) ``` Creating the object within the loop was intended to assure...
You can't rely on the garbage collector's implementation details when planning lifetime dependencies. You need to do this explicitly one way or another. Context managers spring to mind, for example: ``` from contextlib import contextmanager @contextmanager def deleting(obj): try: yield finally: ...
How can I install my project from source with Buildout?
5,703,456
6
2011-04-18T13:15:18Z
5,705,913
11
2011-04-18T16:26:07Z
[ "python", "deployment", "buildout" ]
I want to use [Buildout](http://pypi.python.org/pypi/zc.buildout) to install my [Distribute](http://pypi.python.org/pypi/distribute)-based project and its dependencies to an isolated environment. My project should be installed directly from the source tree (a local Git repository), and is not registered with PyPI. How ...
You have 3 options, depending on where you want your buildout configuration to live and what options you have to check out your git repository. Note that as far as Python is concerned, the resulting egg is exactly the same. The only difference between a development egg and a "normal" egg is that a development egg over...
"+=" causing syntax error in Python
5,704,292
3
2011-04-18T14:22:51Z
5,704,338
24
2011-04-18T14:25:25Z
[ "python" ]
``` n = 1 p = 4 print n += p ``` gives me: > File "p7.py", line 17 > > print n += p > > SyntaxError: invalid syntax How can this problem be fixed?
`n += p` is a statement in Python, not an expression that returns a value you could print. This is different from a couple of other languages, for example Ruby, where *everything* is an expression. You need to do ``` n += p print n ```
"+=" causing syntax error in Python
5,704,292
3
2011-04-18T14:22:51Z
5,704,364
7
2011-04-18T14:26:43Z
[ "python" ]
``` n = 1 p = 4 print n += p ``` gives me: > File "p7.py", line 17 > > print n += p > > SyntaxError: invalid syntax How can this problem be fixed?
Assignment, including "augmented" assignment (`x op= expr` as shorcut for `x = x op expr`), is a statement, not an expression. So it doesn't result in a value. You can't print the result of something that doesn't result in anything - but that's what you're telling Python to do: "Evaluate `n += p`, then print the result...
mysqldb interfaceError
5,704,590
4
2011-04-18T14:41:24Z
13,342,468
17
2012-11-12T10:57:20Z
[ "python", "mysql", "mysql-python" ]
I have a very weird problem with mysqldb (mysql module for python). I have a file with queries for inserting records in tables. If I call the functions from the file, it works just fine; but when trying to call one of the functions from another file it throws me a > \_mysql\_exception.InterfaceError: (0, '') I reall...
I got this error when I was trying to use a closed connection.
parse string of integer sets with intervals to list
5,704,931
4
2011-04-18T15:06:55Z
5,705,014
12
2011-04-18T15:13:04Z
[ "python", "string", "parsing", "list", "intervals" ]
I have `"2,5,7-9,12"` string. I want to get [2, 5, 7, 8, 9, 12] list from it. Is there any built-in function for it in python? Thanks. **UPD.** I suppose, the straight answer is **No**. Anyway, thanks for your "snippets". Using one, suggested by **Sven Marnach**.
``` s = "2,5,7-9,12" ranges = (x.split("-") for x in s.split(",")) print [i for r in ranges for i in range(int(r[0]), int(r[-1]) + 1)] ``` prints ``` [2, 5, 7, 8, 9, 12] ```