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 unittest and discovery
3,295,386
22
2010-07-21T00:13:54Z
8,335,165
38
2011-12-01T00:40:50Z
[ "python", "unit-testing", "discovery" ]
I have directories, which contain files named like: `test_foo.py` Each file is a test case. I would like to 1) Run all the tests in a directory from the command line. I am using `unittest2`, since we are running Python 2.5.1. From one of these directories I tried typing this at the command line: ``` python -m unitt...
Once you have discovered tests, you can run them with a test runner. ``` import unittest2 loader = unittest2.TestLoader() tests = loader.discover('.') testRunner = unittest2.runner.TextTestRunner() testRunner.run(tests) ``` Running the above code will print the test results to standard out.
Creating django objects with a random primary key
3,295,405
7
2010-07-21T00:17:57Z
3,295,428
11
2010-07-21T00:23:39Z
[ "python", "django", "random", "primary-key" ]
I'm working with an API that wants me to generate opaque "reference IDs" for transactions with their API, in other words, unique references that users can't guess or infer in any way. (is 'infer' proper english?) This is what I've hacked together currently: ``` randomRef = randint(0, 99999999999999) while Transaction...
Why not just encrypt the normal sequential ids instead? To someone who doesn't know the encryption key, the ids will seem just as random. You can write a wrapper that automatically decrypts the ID on the way to the DB, and encrypts it on the way from the DB.
Creating django objects with a random primary key
3,295,405
7
2010-07-21T00:17:57Z
4,467,107
10
2010-12-17T02:08:30Z
[ "python", "django", "random", "primary-key" ]
I'm working with an API that wants me to generate opaque "reference IDs" for transactions with their API, in other words, unique references that users can't guess or infer in any way. (is 'infer' proper english?) This is what I've hacked together currently: ``` randomRef = randint(0, 99999999999999) while Transaction...
I created a gist based on this question: <https://gist.github.com/735861> Following Amber's advice, the private keys are encrypted and decrypted using DES. The encrypted key is represented in base 36, but any other character-based representation will work as long as the representation is unique. Any model that would ...
Else clause on Python while statement
3,295,938
140
2010-07-21T02:49:05Z
3,295,949
189
2010-07-21T02:51:33Z
[ "python", "syntax", "while-loop", "if-statement" ]
I've noticed the following code is legal in Python. My question is why? Is there a specific reason? ``` n = 5 while n != 0: print n n -= 1 else: print "what the..." ```
The `else` clause is only executed when your `while` condition becomes false. If you `break` out of the loop, or if an exception is raised, it won't be executed. One way to think about it is as an if/else construct with respect to the condition: ``` if condition: handle_true() else: handle_false() ``` is ana...
Else clause on Python while statement
3,295,938
140
2010-07-21T02:49:05Z
3,295,972
51
2010-07-21T02:54:50Z
[ "python", "syntax", "while-loop", "if-statement" ]
I've noticed the following code is legal in Python. My question is why? Is there a specific reason? ``` n = 5 while n != 0: print n n -= 1 else: print "what the..." ```
The `else` clause is executed if you exit a block normally, by hitting the loop condition or falling off the bottom of a try block. It is *not* executed if you `break` or `return` out of a block, or raise an exception. It works for not only while and for loops, but also try blocks. You typically find it in places wher...
Else clause on Python while statement
3,295,938
140
2010-07-21T02:49:05Z
24,105,859
13
2014-06-08T11:53:17Z
[ "python", "syntax", "while-loop", "if-statement" ]
I've noticed the following code is legal in Python. My question is why? Is there a specific reason? ``` n = 5 while n != 0: print n n -= 1 else: print "what the..." ```
In reply to `Is there a specific reason?`, here is one interesting application: breaking out of multiple levels of looping. Here is how it works: the outer loop has a break at the end, so it would only be executed once. However, if the inner loop completes (finds no divisor), then it reaches the else statement and the...
Why aren't my sqlite3 foreign keys working?
3,296,040
6
2010-07-21T03:15:10Z
3,296,052
10
2010-07-21T03:19:01Z
[ "python", "foreign-keys", "sqlite3" ]
I run the following code from a python interpreter, and expect the insert statement to fail and throw some kind of exception. But it's not happening: ``` Python 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> impo...
Working foreign key support in SQLite is very new -- it was only released in 3.6.19 on October 14th. Are you sure you're using SQLite 3.6.19 or later? Check the sqlite\_version constant in the sqlite3 module. E.g. on a Mac OS X 10.6 system with the default python/sqlite install: ``` >>> import sqlite3 >>> sqlite3.sql...
Opposite of Python for ... else
3,296,044
4
2010-07-21T03:16:55Z
3,296,058
15
2010-07-21T03:20:24Z
[ "python", "python-3.x", "for-loop", "if-statement" ]
The following python code will result in n (14) being printed, as the for loop is completed. ``` for n in range(15): if n == 100: break else: print(n) ``` However, what I want is the opposite of this. Is there any way to do a for ... else (or while ... else) loop, but only execute the else code if the...
There is no explicit `for...elseifbreak`-like construct in Python (or in any language that I know of) because you can simply do this: ``` for n in range(15): if n == 100: print(n) break ``` If you have multiple `break`s, put `print(n)` in a function so you [Don't Repeat Yourself](http://en.wiki...
Case insensitive dictionary search with Python
3,296,499
13
2010-07-21T05:23:18Z
3,296,646
9
2010-07-21T05:57:56Z
[ "python", "dictionary" ]
I can use map to implement the case insensitive list search with Python. ``` a = ['xyz', 'wMa', 'Pma']; b = map(string.lower, a) if 'Xyz'.lower() in b: print 'yes' ``` How can I do the same thing with dictionary? I tried the following code, but ap has the list of ['a','b','c'], not the case insensitive dictiona...
Using dict comprehensions (Python2.7+) ``` a_lower = {k.lower():v for k,v in a.items()} ``` If your python is too old for dict comprehensions ``` a_lower = dict((k.lower(),v) for k,v in a.items()) ``` then look up the value with the lowercase version of the key ``` value = a_lower[key.lower()] ```
Case insensitive dictionary search with Python
3,296,499
13
2010-07-21T05:23:18Z
3,296,782
23
2010-07-21T06:29:49Z
[ "python", "dictionary" ]
I can use map to implement the case insensitive list search with Python. ``` a = ['xyz', 'wMa', 'Pma']; b = map(string.lower, a) if 'Xyz'.lower() in b: print 'yes' ``` How can I do the same thing with dictionary? I tried the following code, but ap has the list of ['a','b','c'], not the case insensitive dictiona...
Note that making a dictionary case-insensitive, by whatever mean, may well lose information: for example, how would you "case-insensitivize" `{'a': 23, 'A': 45}`?! If all you care is where a key is in the dict or not (i.e., don't care about what value corresponds to it), then make a `set` instead -- i.e. ``` theset = ...
How to pass an argument to event handler in tkinter?
3,296,893
13
2010-07-21T06:51:55Z
3,298,651
25
2010-07-21T11:20:53Z
[ "python", "events", "binding", "arguments", "tkinter" ]
``` widget.bind('<Button-1>',callback) # binding def callback(self,event) #do something ``` I need to pass an argument to `callback()` . The argument is a dictionary object.
You can use [`lambda`](https://docs.python.org/3/tutorial/controlflow.html#lambda-expressions) to define an anonymous function, such as: ``` data={"one": 1, "two": 2} widget.bind("<ButtonPress-1>", lambda event, arg=data: self.on_mouse_down(event, arg)) ``` Note that the `arg` passed in becomes just a normal argumen...
How to use MinGW's gcc compiler when installing Python package using Pip?
3,297,254
47
2010-07-21T07:56:07Z
5,051,281
78
2011-02-19T14:25:10Z
[ "python", "windows", "mingw", "pip", "distutils" ]
I configured MinGW and distutils so now I can compile extensions using this command: ``` setup.py install ``` MinGW's gcc complier will be used and package will be installed. For that I installed MinGW and [created distutils.cfg](https://docs.python.org/2/install/#location-and-names-of-config-files) file with followi...
* install MinGW with C++ Compiler option checked * add `C:\MinGW\bin` to your PATH * in `PYTHONPATH\Lib\distutils`, create a file `distutils.cfg` and add these lines: `[build] compiler=mingw32`
Python - How can I open a file and specify the offset in bytes?
3,299,213
9
2010-07-21T12:33:30Z
3,299,261
13
2010-07-21T12:38:33Z
[ "python", "file-io", "byte", "offset" ]
I'm writing a program that will parse an Apache log file periodically to log it's visitors, bandwidth usage, etc.. The problem is, I don't want to open the log and parse data I've already parsed. For example: ``` line1 line2 line3 ``` If I parse that file, I'll save all the lines then save that offset. That way, whe...
You can manage the position in the file thanks to the `seek` and `tell` methods of the `file` class see <http://docs.python.org/library/stdtypes.html#file-objects> The `tell` method will tell you where to seek next time you open
Python Compilation/Interpretation Process
3,299,648
26
2010-07-21T13:21:47Z
3,299,724
37
2010-07-21T13:28:54Z
[ "compiler-construction", "interpreter", "python" ]
I'm trying to understand the python compiler/interpreter process more clearly. Unfortunately, I have not taken a class in interpreters nor have I read much about them. Basically, what I understand right now is that Python code from .py files is first compiled into python bytecode (which i assume are the .pyc files i s...
The bytecode is not actually interpreted to machine code, unless you are using some exotic implementation such as pypy. Other than that, you have the description correct. The bytecode is loaded into the Python runtime and interpreted by a virtual machine, which is a piece of code that reads each instruction in the byt...
How can I get dict from sqlite query?
3,300,464
43
2010-07-21T14:42:20Z
3,300,514
74
2010-07-21T14:47:20Z
[ "python", "sql", "sqlite" ]
``` db = sqlite.connect("test.sqlite") res = db.execute("select * from table") ``` With iteration I get lists coresponding to the rows. ``` for row in res: print row ``` I can get name of the columns ``` col_name_list = [tuple[0] for tuple in res.description] ``` But is there some function or setting to get di...
You could use [row\_factory](http://docs.python.org/library/sqlite3.html#sqlite3.Connection.row_factory), as in the example in the docs: ``` import sqlite3 def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d con = sqlite3.connect(":me...
How can I get dict from sqlite query?
3,300,464
43
2010-07-21T14:42:20Z
9,538,363
13
2012-03-02T18:19:59Z
[ "python", "sql", "sqlite" ]
``` db = sqlite.connect("test.sqlite") res = db.execute("select * from table") ``` With iteration I get lists coresponding to the rows. ``` for row in res: print row ``` I can get name of the columns ``` col_name_list = [tuple[0] for tuple in res.description] ``` But is there some function or setting to get di...
Even using the sqlite3.Row class-- you still can't use string formatting in the form of: ``` print "%(id)i - %(name)s: %(value)s" % row ``` In order to get past this, I use a helper function that takes the row and converts to a dictionary. I only use this when the dictionary object is preferable to the Row object (e....
How do I set a breakpoint in a module other than the one I am running in Python IDLE?
3,300,665
5
2010-07-21T14:59:43Z
3,301,128
7
2010-07-21T15:42:27Z
[ "python", "python-idle" ]
If I edit two modules, eggs and ham, and module eggs imports ham, how do I run module eggs such that IDLE stops at breakpoints set in ham? So far, I have only been able to get IDLE to recognize breakpoints set in the module actually being run, not those being imported.
1. start IDLE 2. open eggs, open ham 3. set desired breakpoints in both files 4. go to IDLE's shell, select Debug=>Debugger 5. go back to eggs and to run. You should stop at break points in each file. (It works, I just tested it.)
Can I use Django F() objects with string concatenation?
3,300,944
12
2010-07-21T15:24:35Z
3,301,848
18
2010-07-21T17:02:17Z
[ "python", "mysql", "django" ]
I want to run a django update through the ORM that looks something like this: ``` MyModel.objects.filter(**kwargs).update(my_field=F('my_other_field')+'a string') ``` This causes MySQL to throw an exception. Is there anyway to do this without writing raw SQL?
What's happening is that Django is passing the '+' through to SQL - but SQL doesn't allow the use of '+' for concatenation, so it tries to add numerically. If you use an integer in place of 'a string', it does work in the sense that it adds the integer value of `my_other_field` to your variable. It's debatable whether...
Check if space is in a string
3,301,395
13
2010-07-21T16:10:44Z
3,301,453
29
2010-07-21T16:15:24Z
[ "python", "string" ]
``` ' ' in word == True ``` I'm writing a program that checks whether the string is a single word. Why doesn't this work and is there any better way to check if a string has no spaces/is a single word..
`==` takes precedence over `in`, so you're actually testing `word == True`. ``` >>> w = 'ab c' >>> ' ' in w == True 1: False >>> (' ' in w) == True 2: True ``` But you don't need `== True` at all. `if` requires [something that evalutes to True or False] and `' ' in word` will evalute to true or false. So, `if ' ' in ...
Check if space is in a string
3,301,395
13
2010-07-21T16:10:44Z
3,301,457
10
2010-07-21T16:15:37Z
[ "python", "string" ]
``` ' ' in word == True ``` I'm writing a program that checks whether the string is a single word. Why doesn't this work and is there any better way to check if a string has no spaces/is a single word..
Write `if " " in word:` instead of `if " " in word == True:`. Explanation: * In Python, for example `a < b < c` is equivalent to `(a < b) and (b < c)`. * The same holds for any chain of comparison operators, which include `in`! * Therefore `' ' in w == True` is equivalent to `(' ' in w) and (w == True)` which is *not...
Calling AutoIt Functions in Python
3,301,561
12
2010-07-21T16:28:12Z
3,302,050
9
2010-07-21T17:26:36Z
[ "python", "autoit" ]
I have seen [this post](http://stackoverflow.com/questions/151846/get-other-running-processes-window-sizes-in-python/155587#155587) mentioned there is an AutoIt3 COM version, and with it I can call AutoIt functions in Python. I couldn't find the COM version at the AutoIt website. Is it hidden somewhere? How can I get ...
`AutoItX.dll` and `AutoItX3_x64.dll` are included in the default installation, in a directory called "AutoItX". Check out the help file `AutoItX.chm` in that directory for more info.
Calling AutoIt Functions in Python
3,301,561
12
2010-07-21T16:28:12Z
9,371,563
27
2012-02-21T03:05:39Z
[ "python", "autoit" ]
I have seen [this post](http://stackoverflow.com/questions/151846/get-other-running-processes-window-sizes-in-python/155587#155587) mentioned there is an AutoIt3 COM version, and with it I can call AutoIt functions in Python. I couldn't find the COM version at the AutoIt website. Is it hidden somewhere? How can I get ...
# How to use AutoItX COM/DLL in python There are two methods for using AutoIt in Python: 1. [pyautoit module](https://pypi.python.org/pypi/PyAutoIt) 2. [python for windows extentions (pywin32)](http://sourceforge.net/projects/pywin32/) The pyautoit module will make use of the DLL while with pywin32 we can use the CO...
Celery - Get task id for current task
3,302,320
45
2010-07-21T18:02:58Z
3,303,443
9
2010-07-21T20:17:17Z
[ "python", "django", "celery" ]
How can I get the task\_id value for a task from within the task? Here's my code: ``` from celery.decorators import task from django.core.cache import cache @task def do_job(path): "Performs an operation on a file" # ... Code to perform the operation ... cache.set(current_task_id, operation_results) ```...
Celery does set some default keyword arguments if the task accepts them. (you can accept them by either using \*\*kwargs, or list them specifically) ``` @task def do_job(path, task_id=None): cache.set(task_id, operation_results) ``` The list of default keyword arguments is documented here: <http://ask.github.com/...
Celery - Get task id for current task
3,302,320
45
2010-07-21T18:02:58Z
8,096,086
85
2011-11-11T15:21:44Z
[ "python", "django", "celery" ]
How can I get the task\_id value for a task from within the task? Here's my code: ``` from celery.decorators import task from django.core.cache import cache @task def do_job(path): "Performs an operation on a file" # ... Code to perform the operation ... cache.set(current_task_id, operation_results) ```...
Since Celery 2.2.0, information related to the currently executed task is saved to task.request (it's called «the context»). So you should get task id from this context (not from keyword arguments, which are deprecated): ``` @task def do_job(path): cache.set(do_job.request.id, operation_results) ``` The list of...
Celery - Get task id for current task
3,302,320
45
2010-07-21T18:02:58Z
34,264,686
15
2015-12-14T10:27:40Z
[ "python", "django", "celery" ]
How can I get the task\_id value for a task from within the task? Here's my code: ``` from celery.decorators import task from django.core.cache import cache @task def do_job(path): "Performs an operation on a file" # ... Code to perform the operation ... cache.set(current_task_id, operation_results) ```...
As of celery 3.1, you can use the [`bind`](https://celery.readthedocs.org/en/latest/userguide/tasks.html#context) decorator argument, and have access to the current request: ``` @task(bind=True) def do_job(self, path): cache.set(self.request.id, operation_results) ```
Writing a CherryPy Decorator for Authorization
3,302,844
6
2010-07-21T19:08:00Z
3,304,067
13
2010-07-21T21:35:31Z
[ "python", "permissions", "authorization", "decorator", "cherrypy" ]
I have a cherrypy application and on some of the views I want to start only allowing certain users to view them, and sending anyone else to an authorization required page. Is there a way I can do this with a custom decorator? I think that would be the most elegant option. Here's a basic example of what I want to do: ...
You really don't want to be writing custom decorators for CherryPy. Instead, you want to write a new Tool: ``` def myauth(allowed_groups=None, debug=False): # Do your auth here... authlib.auth(...) cherrypy.tools.myauth = cherrypy.Tool("on_start_resource", myauth) ``` See <http://docs.cherrypy.org/dev/proggui...
Authentication in Facebook Canvas App using New Graph API
3,302,908
5
2010-07-21T19:14:34Z
4,152,929
13
2010-11-11T09:28:20Z
[ "javascript", "python", "django", "facebook" ]
I am building a Facebook canvas application that loads in an iframe with Django. I would like the login process to work similarly to the way Zynga does it. In this method, if you are not logged in you are redirected to a Facebook login page and then to a permissions request page for the app (without any popups). As fa...
> Is there a way to use the > javascript SDK to redirect to the > login page rather than loading it as a > popup? No. The JavaScript SDK will open a new window rather than redirect the current window. To present the user with a full-screen version of the authorization dialog, you need to redirect them to `https://gra...
how to base64 url decode in python
3,302,946
14
2010-07-21T19:18:34Z
3,303,364
19
2010-07-21T20:07:29Z
[ "python", "facebook", "base64", "decode" ]
for facebook fbml apps facebook is sending in a signed\_request parameter explained here <http://developers.facebook.com/docs/authentication/canvas> they have given the php version of decoding this signed request: <http://pastie.org/1054154> how to do the same in python? i tried base64 module but i am getting Inco...
Apparently you missed the last two characters when copying the original base64-encoded string. Suffix the input string with two is-equal (=) signs and it will be decoded correctly.
how to base64 url decode in python
3,302,946
14
2010-07-21T19:18:34Z
3,355,277
22
2010-07-28T16:48:37Z
[ "python", "facebook", "base64", "decode" ]
for facebook fbml apps facebook is sending in a signed\_request parameter explained here <http://developers.facebook.com/docs/authentication/canvas> they have given the php version of decoding this signed request: <http://pastie.org/1054154> how to do the same in python? i tried base64 module but i am getting Inco...
I have shared a code snippet for parsing signed\_request parameter in a python based facebook canvas application at <http://sunilarora.org/parsing-signedrequest-parameter-in-python-bas>
how to base64 url decode in python
3,302,946
14
2010-07-21T19:18:34Z
9,956,217
16
2012-03-31T13:16:19Z
[ "python", "facebook", "base64", "decode" ]
for facebook fbml apps facebook is sending in a signed\_request parameter explained here <http://developers.facebook.com/docs/authentication/canvas> they have given the php version of decoding this signed request: <http://pastie.org/1054154> how to do the same in python? i tried base64 module but i am getting Inco...
try ``` s = 'iEPX-SQWIR3p67lj_0zigSWTKHg' base64.urlsafe_b64decode(s + '=' * (4 - len(s) % 4)) ``` as it is written [here](http://fi.am/entry/urlsafe-base64-encodingdecoding-in-two-lines/)
What's the best way to assert for numpy.array equality?
3,302,949
44
2010-07-21T19:18:48Z
3,303,083
11
2010-07-21T19:34:59Z
[ "python", "unit-testing", "numpy" ]
I want to make some unittests for my app, and I need to compare two arrays. Since `array.__eq__` returns a new array (so `TestCase.assertEqual` fails), what is the best way to assert for equality? Currently I'm using ``` self.assertTrue((arr1 == arr2).all()) ``` but I don't really like it :\
I think `(arr1 == arr2).all()` looks pretty nice. But you could use: ``` numpy.allclose(arr1, arr2) ``` but it's not quite the same. An alternative, almost the same as your example is: ``` numpy.alltrue(arr1 == arr2) ``` Note that scipy.array is actually a reference numpy.array. That makes it easier to find the do...
What's the best way to assert for numpy.array equality?
3,302,949
44
2010-07-21T19:18:48Z
3,314,039
54
2010-07-22T22:33:43Z
[ "python", "unit-testing", "numpy" ]
I want to make some unittests for my app, and I need to compare two arrays. Since `array.__eq__` returns a new array (so `TestCase.assertEqual` fails), what is the best way to assert for equality? Currently I'm using ``` self.assertTrue((arr1 == arr2).all()) ``` but I don't really like it :\
check out the assert functions in [`numpy.testing`](http://docs.scipy.org/doc/numpy-dev/reference/routines.testing.html), e.g. `assert_array_equal` for floating point arrays equality test might fail and `assert_almost_equal` is more reliable. **update** A few versions ago numpy obtained `assert_allclose` which is n...
Pythonic way to turn a list of strings into a dictionary with the odd-indexed strings as keys and even-indexed ones as values?
3,303,213
8
2010-07-21T19:49:19Z
3,303,227
13
2010-07-21T19:50:55Z
[ "python", "list-comprehension" ]
I have a list of strings parsed from somewhere, in the following format: ``` [key1, value1, key2, value2, key3, value3, ...] ``` I'd like to create a dictionary based on this list, like so: ``` {key1:value1, key2:value2, key3:value3, ...} ``` An ordinary `for` loop with index offsets would probably do the trick, bu...
You can try: ``` dict(zip(l[::2], l[1::2])) ``` Explanation: we split the list into two lists, one of the even and one of the odd elements, by taking them by steps of two starting from either the first or the second element (that's the `l[::2]` and `l[1::2]`). Then we use the `zip` builtin to the two lists into one l...
how do I convert a string to a valid variable name in python?
3,303,312
9
2010-07-21T19:59:30Z
3,303,361
18
2010-07-21T20:07:01Z
[ "python", "validation", "string", "variables" ]
I need to convert an arbitrary string to a string that is a valid variable name in python. Here's a very basic example: ``` s1 = 'name/with/slashes' s2 = 'name ' def clean(s): s = s.replace('/','') s = s.strip() return s print clean(s1)+'_'#the _ is there so I can see the end of the string ``` That is ...
[According to Python](http://docs.python.org/reference/lexical_analysis.html#identifiers), an identifier is a letter or underscore, followed by an unlimited string of letters, numbers, and underscores: ``` import re def clean(s): # Remove invalid characters s = re.sub('[^0-9a-zA-Z_]', '', s) # Remove leadi...
how do I convert a string to a valid variable name in python?
3,303,312
9
2010-07-21T19:59:30Z
3,305,731
21
2010-07-22T04:12:47Z
[ "python", "validation", "string", "variables" ]
I need to convert an arbitrary string to a string that is a valid variable name in python. Here's a very basic example: ``` s1 = 'name/with/slashes' s2 = 'name ' def clean(s): s = s.replace('/','') s = s.strip() return s print clean(s1)+'_'#the _ is there so I can see the end of the string ``` That is ...
Well, I'd like to best Triptych's solution with ... a one-liner! ``` >>> clean = lambda varStr: re.sub('\W|^(?=\d)','_', varStr) >>> clean('32v2 g #Gmw845h$W b53wi ') '_32v2_g__Gmw845h_W_b53wi_' ``` This substitution replaces any non-variable appropriate character with underscore and inserts underscore in front if t...
how to loop through httprequest post variables in python
3,303,336
15
2010-07-21T20:03:20Z
3,303,396
51
2010-07-21T20:11:19Z
[ "python", "django", "post", "httprequest" ]
How can you loop through the HttpRequest post variables in Django? I have ``` for k,v in request.POST: print k,v ``` which is not working properly. Thanks!
`request.POST` is a dictionary-like object containing all given HTTP POST parameters. When you loop through `request.POST`, you only get the keys. ``` for key in request.POST: print(key) value = request.POST[key] print(value) ``` To retrieve the keys and values together, use the [`items`](https://docs.dj...
Use my own main loop in twisted
3,303,600
6
2010-07-21T20:36:27Z
3,304,043
8
2010-07-21T21:33:34Z
[ "python", "twisted" ]
I have an existing program that has its own main loop, and does computations based on input it receives - let's say from the user, to make it simple. I want to now do the computations remotely instead of locally, and I decided to implement the RPCs in Twisted. Ideally I just want to change one of my functions, say `do...
You have a couple of different options, depending on what sort of main loop your existing program has. If it's a mainloop from a GUI library, [Twisted may already have support for it](http://twistedmatrix.com/documents/current/core/howto/choosing-reactor.html). In that case, you can just go ahead and use it. You coul...
How to enumerate a range of numbers starting at 1
3,303,608
45
2010-07-21T20:37:35Z
3,303,640
53
2010-07-21T20:41:11Z
[ "python", "enums" ]
I am using Python 2.5, I want an enumeration like so (starting at 1 instead of 0): ``` [(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)] ``` I know in Python 2.6 you can do: h = enumerate(range(2000, 2005), 1) to give the above result but in python2.5 you cannot... Using python2.5: ``` >>> h = enumerate(range...
As you already mentioned, this is straightforward to do in Python 2.6 or newer: ``` enumerate(range(2000, 2005), 1) ``` Python 2.5 and older do not support the `start` parameter so instead you could create two range objects and zip them: ``` r = xrange(2000, 2005) r2 = xrange(1, len(r) + 1) h = zip(r2, r) print h ``...
How to enumerate a range of numbers starting at 1
3,303,608
45
2010-07-21T20:37:35Z
3,303,667
10
2010-07-21T20:44:33Z
[ "python", "enums" ]
I am using Python 2.5, I want an enumeration like so (starting at 1 instead of 0): ``` [(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)] ``` I know in Python 2.6 you can do: h = enumerate(range(2000, 2005), 1) to give the above result but in python2.5 you cannot... Using python2.5: ``` >>> h = enumerate(range...
Easy, just define your own function that does what you want: ``` def enum(seq, start=0): for i, x in enumerate(seq): yield i+start, x ```
How to enumerate a range of numbers starting at 1
3,303,608
45
2010-07-21T20:37:35Z
3,304,172
8
2010-07-21T21:48:25Z
[ "python", "enums" ]
I am using Python 2.5, I want an enumeration like so (starting at 1 instead of 0): ``` [(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)] ``` I know in Python 2.6 you can do: h = enumerate(range(2000, 2005), 1) to give the above result but in python2.5 you cannot... Using python2.5: ``` >>> h = enumerate(range...
Simplest way to do in Python 2.5 exactly what you ask about: ``` import itertools as it ... it.izip(it.count(1), xrange(2000, 2005)) ... ``` If you want a list, as you appear to, use `zip` in lieu of `it.izip`. (BTW, as a general rule, the best way to make a list out of a generator or any other iterable X is *not* ...
How to enumerate a range of numbers starting at 1
3,303,608
45
2010-07-21T20:37:35Z
14,736,201
85
2013-02-06T18:28:51Z
[ "python", "enums" ]
I am using Python 2.5, I want an enumeration like so (starting at 1 instead of 0): ``` [(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)] ``` I know in Python 2.6 you can do: h = enumerate(range(2000, 2005), 1) to give the above result but in python2.5 you cannot... Using python2.5: ``` >>> h = enumerate(range...
Just to put this here for posterity sake, in 2.6 the "start" parameter was added to enumerate like so: `enumerate(sequence, start=1)`
Unit Test Problem with assertRaises
3,304,642
9
2010-07-21T23:18:53Z
3,304,650
22
2010-07-21T23:19:54Z
[ "python", "unit-testing" ]
I am trying to test for an exception. I have: ``` def test_set_catch_status_exception(self): mro = self.mro NEW_STATUS = 'No such status' self.assertRaises(ValueError,mro.setStatus(NEW_STATUS)) ``` I get the following error: ``` ====================================================================== ERRO...
`self.assertRaises` expects a function `mro.setStatus`, followed by an arbitrary number of arguments: in this case, just `NEW_STATUS`. `self.assertRaises` assembles its arguments into the function call `mro.setStatus(NEW_STATUS)` inside a `try...except` block, thus catching and recording the `ValueError` if it occurs. ...
Python urllib vs httplib?
3,305,250
45
2010-07-22T01:58:47Z
3,305,261
38
2010-07-22T02:00:58Z
[ "python", "http", "urllib", "httplib" ]
When would someone use httplib and when urllib? What are the differences? I think I ready urllib uses httplib, I am planning to make an app that will need to make http request and so far I only used httplib.HTTPConnection in python for requests, and reading about urllib I see I can use that for request too, so whats ...
urllib (particularly urllib2) handles many things by default or has appropriate libs to do so. For example, urllib2 will follow redirects automatically and you can use cookiejar to handle login scripts. These are all things you'd have to code yourself if you were using httplib.
Python urllib vs httplib?
3,305,250
45
2010-07-22T01:58:47Z
7,485,000
36
2011-09-20T12:17:27Z
[ "python", "http", "urllib", "httplib" ]
When would someone use httplib and when urllib? What are the differences? I think I ready urllib uses httplib, I am planning to make an app that will need to make http request and so far I only used httplib.HTTPConnection in python for requests, and reading about urllib I see I can use that for request too, so whats ...
Try [requests](http://pypi.python.org/pypi/requests), the very simple and powerful module based on urllib2- docs [here](http://docs.python-requests.org/en/latest/index.html).
Python urllib vs httplib?
3,305,250
45
2010-07-22T01:58:47Z
19,973,568
13
2013-11-14T09:10:17Z
[ "python", "http", "urllib", "httplib" ]
When would someone use httplib and when urllib? What are the differences? I think I ready urllib uses httplib, I am planning to make an app that will need to make http request and so far I only used httplib.HTTPConnection in python for requests, and reading about urllib I see I can use that for request too, so whats ...
I would like to say something about `urllib`, `urllib2`, `httplib` and `httplib2`. The main different between `urllib*` and `httplib*` is that: **httplib and httplib2 handles HTTP/HTTPs request and response directly and give you more space to do your own job.** **urllib and urllib2 are build upon httplib, they are m...
Python strptime() and timezones?
3,305,413
76
2010-07-22T02:42:08Z
3,306,887
17
2010-07-22T08:08:36Z
[ "python", "datetime", "timezone" ]
I have a CSV dumpfile from a Blackberry IPD backup, created using IPDDump. The date/time strings in here look something like this (where `EST` is an Australian time-zone): ``` Tue Jun 22 07:46:22 EST 2010 ``` I need to be able to parse this date in Python. At first, I tried to use the `strptime()` function from datet...
The [`datetime` module documentation](http://docs.python.org/library/datetime.html#datetime.datetime.strptime) says: > Return a datetime corresponding to date\_string, parsed according to format. This is equivalent to `datetime(*(time.strptime(date_string, format)[0:6]))`. See that `[0:6]`? That gets you `(year, mont...
Python strptime() and timezones?
3,305,413
76
2010-07-22T02:42:08Z
8,525,115
193
2011-12-15T18:52:19Z
[ "python", "datetime", "timezone" ]
I have a CSV dumpfile from a Blackberry IPD backup, created using IPDDump. The date/time strings in here look something like this (where `EST` is an Australian time-zone): ``` Tue Jun 22 07:46:22 EST 2010 ``` I need to be able to parse this date in Python. At first, I tried to use the `strptime()` function from datet...
I recommend using [python-dateutil](http://labix.org/python-dateutil). Its parser has been able to parse every date format I've thrown at it so far. ``` >>> from dateutil import parser >>> parser.parse("Tue Jun 22 07:46:22 EST 2010") datetime.datetime(2010, 6, 22, 7, 46, 22, tzinfo=tzlocal()) >>> parser.parse("Fri, 11...
What is the difference between 'log' and 'symlog'?
3,305,865
48
2010-07-22T04:55:04Z
3,305,880
10
2010-07-22T04:58:50Z
[ "python", "matplotlib", "scale", "logarithm" ]
In [matplotlib](http://matplotlib.sourceforge.net/), I can set the axis scaling using either [`pyplot.xscale()`](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xscale) or [`Axes.set_xscale()`](http://matplotlib.sourceforge.net/api/axes_api.html#matplotlib.axes.Axes.set_xscale). Both functions a...
**symlog** is like log but allows you to define a range of values near zero within which the plot is linear, to avoid having the plot go to infinity around zero. From <http://matplotlib.sourceforge.net/api/axes_api.html#matplotlib.axes.Axes.set_xscale> In a log graph, you can never have a zero value, and if you have ...
What is the difference between 'log' and 'symlog'?
3,305,865
48
2010-07-22T04:55:04Z
3,513,150
94
2010-08-18T14:29:31Z
[ "python", "matplotlib", "scale", "logarithm" ]
In [matplotlib](http://matplotlib.sourceforge.net/), I can set the axis scaling using either [`pyplot.xscale()`](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.xscale) or [`Axes.set_xscale()`](http://matplotlib.sourceforge.net/api/axes_api.html#matplotlib.axes.Axes.set_xscale). Both functions a...
I finally found some time to do some experiments in order to understand the difference between them. Here's what I discovered: * `log` only allows positive values, and lets you choose how to handle negative ones (`mask` or `clip`). * `symlog` means *symmetrical log*, and allows positive and negative values. * `symlog`...
Static memory in python: do loops create new instances of variables in memory?
3,305,870
9
2010-07-22T04:56:29Z
3,306,310
10
2010-07-22T06:30:58Z
[ "python", "memory" ]
I've been running Python scripts that make several calls to some functions, say F1(x) and F2(x), that look a bit like this: ``` x = LoadData() for j in range(N): y = F1(x[j]) z[j] = F2(y) del y SaveData(z) ``` Performance is a lot faster if I keep the "del y" line. But I don't understand why this is tr...
Without the `del y` you might need twice as much memory. This is because for each pass through the loop, `y` is bound to the previous value of `F1` while the next one is calculated. once `F1` returns y is rebound to that new value and the old `F1` result can be released. This would mean that the object returned by `F...
Python csv string to array
3,305,926
75
2010-07-22T05:08:48Z
3,305,964
110
2010-07-22T05:18:14Z
[ "python", "string", "arrays", "csv" ]
Anyone know of a simple library or function to parse a csv encoded string and turn it into an array or dictionary? I don't think I want the built in [csv module](http://docs.python.org/library/csv.html) because in all the examples I've seen that takes filepaths, not strings.
I would use `StringIO`: ``` import StringIO import csv scsv = """1,2,3 a,b,c d,e,f""" f = StringIO.StringIO(scsv) reader = csv.reader(f, delimiter=',') for row in reader: print '\t'.join(row) ``` simplier version with `split()` on newlines: ``` reader = csv.reader(scsv.split('\n'), delimiter=',') for row in re...
Python csv string to array
3,305,926
75
2010-07-22T05:08:48Z
3,305,973
35
2010-07-22T05:20:22Z
[ "python", "string", "arrays", "csv" ]
Anyone know of a simple library or function to parse a csv encoded string and turn it into an array or dictionary? I don't think I want the built in [csv module](http://docs.python.org/library/csv.html) because in all the examples I've seen that takes filepaths, not strings.
Simple - the csv module works with lists, too: ``` >>> a=["1,2,3","4,5,6"] # or a = "1,2,3\n4,5,6".split('\n') >>> import csv >>> x = csv.reader(a) >>> list(x) [['1', '2', '3'], ['4', '5', '6']] ```
Python csv string to array
3,305,926
75
2010-07-22T05:08:48Z
3,312,418
7
2010-07-22T19:05:06Z
[ "python", "string", "arrays", "csv" ]
Anyone know of a simple library or function to parse a csv encoded string and turn it into an array or dictionary? I don't think I want the built in [csv module](http://docs.python.org/library/csv.html) because in all the examples I've seen that takes filepaths, not strings.
As others have already pointed out, Python includes a module to read and write CSV files. It works pretty well as long as the input characters stay within ASCII limits. In case you want to process other encodings, more work is needed. The [Python documentation for the csv module](http://docs.python.org/library/csv.htm...
Python csv string to array
3,305,926
75
2010-07-22T05:08:48Z
23,048,789
7
2014-04-13T21:43:06Z
[ "python", "string", "arrays", "csv" ]
Anyone know of a simple library or function to parse a csv encoded string and turn it into an array or dictionary? I don't think I want the built in [csv module](http://docs.python.org/library/csv.html) because in all the examples I've seen that takes filepaths, not strings.
``` >>> a = "1,2" >>> a '1,2' >>> b = a.split(",") >>> b ['1', '2'] ``` To parse a CSV file: ``` f = open(file.csv, "r") lines = f.read().split("\n") # "\r\n" if needed for line in lines: if line != "": # add other needed checks to skip titles cols = line.split(",") print cols ```
Cannot pass an argument to python with "#!/usr/bin/env python"
3,306,518
51
2010-07-22T07:07:15Z
3,306,575
11
2010-07-22T07:16:31Z
[ "python", "arguments", "shebang" ]
I needed to have a directly executable python script, so i started the file with `#!/usr/bin/env python`. However, I also need unbuffered output, so i tried `#!/usr/bin/env python -u`, but that fails with `python -u: no such file or directory`. I found out that `#/usr/bin/python -u` works, but I need it to get the `py...
Passing arguments to the shebang line is not standard and in as you have experimented do not work in combination with env in Linux. The solution with bash is to use the builtin command "set" to set the required options. I think you can do the same to set unbuffered output of stdin with a python command. my2c
Cannot pass an argument to python with "#!/usr/bin/env python"
3,306,518
51
2010-07-22T07:07:15Z
8,921,497
9
2012-01-19T05:34:29Z
[ "python", "arguments", "shebang" ]
I needed to have a directly executable python script, so i started the file with `#!/usr/bin/env python`. However, I also need unbuffered output, so i tried `#!/usr/bin/env python -u`, but that fails with `python -u: no such file or directory`. I found out that `#/usr/bin/python -u` works, but I need it to get the `py...
When you use shebang on Linux, the entire rest of the line after the interpreter name is interpreted as a single argument. The `python -u` gets passed to `env` as if you'd typed: `/usr/bin/env 'python -u'`. The `/usr/bin/env` searches for a binary called `python -u`, which there isn't one.
Cannot pass an argument to python with "#!/usr/bin/env python"
3,306,518
51
2010-07-22T07:07:15Z
9,051,635
29
2012-01-29T07:25:40Z
[ "python", "arguments", "shebang" ]
I needed to have a directly executable python script, so i started the file with `#!/usr/bin/env python`. However, I also need unbuffered output, so i tried `#!/usr/bin/env python -u`, but that fails with `python -u: no such file or directory`. I found out that `#/usr/bin/python -u` works, but I need it to get the `py...
In some environment, env doesn't split arguments. So your env is looking for "python -u" in your path. We can use sh to work around. Replace your shebang with the following code lines and everything will be fine. ``` #!/bin/sh ''''exec python -u -- "$0" ${1+"$@"} # ''' # vi: syntax=python ``` p.s. we need not worry a...
Cannot pass an argument to python with "#!/usr/bin/env python"
3,306,518
51
2010-07-22T07:07:15Z
16,956,043
15
2013-06-06T07:22:58Z
[ "python", "arguments", "shebang" ]
I needed to have a directly executable python script, so i started the file with `#!/usr/bin/env python`. However, I also need unbuffered output, so i tried `#!/usr/bin/env python -u`, but that fails with `python -u: no such file or directory`. I found out that `#/usr/bin/python -u` works, but I need it to get the `py...
It is better to use environment variable to enable this. See python doc : <http://docs.python.org/2/using/cmdline.html> for your case: ``` export PYTHONUNBUFFERED=1 script.py ```
Creating an event filter
3,308,013
7
2010-07-22T10:50:42Z
3,391,545
8
2010-08-02T20:38:17Z
[ "python", "qt", "events", "pyqt" ]
I am trying to enable the delete key in my treeview. This is what I have so far: ``` class delkeyFilter(QObject): delkeyPressed = pyqtSignal() def eventFilter(self, obj, event): if event.type() == QEvent.KeyPress: if event.key() == Qt.Key_Delete: self.delkeyPressed.emit()...
@balpha is correct. The simple answer is that if you don't pass in a parent or otherwise ensure that the `filter` instance has a live reference, it will be garbage collected. PyQt uses [SIP](http://www.riverbankcomputing.co.uk/software/sip/intro) to bind to Qt's C++ implementation. From the [SIP documentation](http://...
How to extract the n-th elements from a list of tuples in python?
3,308,102
37
2010-07-22T11:03:00Z
3,308,117
88
2010-07-22T11:04:42Z
[ "python", "list", "tuples" ]
I'm trying to obtain the n-th elements from a list of tuples. I have something like: ``` elements = [(1,1,1),(2,3,7),(3,5,10)] ``` I wish to extract only the second elements of each tuple into a list: ``` seconds = [1, 3, 5] ``` I know that it could be done with a `for` loop but I wanted to know if there's another...
``` [x[1] for x in elements] ```
How to extract the n-th elements from a list of tuples in python?
3,308,102
37
2010-07-22T11:03:00Z
3,308,136
19
2010-07-22T11:06:49Z
[ "python", "list", "tuples" ]
I'm trying to obtain the n-th elements from a list of tuples. I have something like: ``` elements = [(1,1,1),(2,3,7),(3,5,10)] ``` I wish to extract only the second elements of each tuple into a list: ``` seconds = [1, 3, 5] ``` I know that it could be done with a `for` loop but I wanted to know if there's another...
> I know that it could be done with a FOR but I wanted to know if there's another way There is another way. You can also do it with [map](http://docs.python.org/library/functions.html#map) and [itemgetter](http://docs.python.org/library/operator.html#operator.itemgetter): ``` >>> from operator import itemgetter >>> m...
How to extract the n-th elements from a list of tuples in python?
3,308,102
37
2010-07-22T11:03:00Z
3,308,805
14
2010-07-22T12:29:09Z
[ "python", "list", "tuples" ]
I'm trying to obtain the n-th elements from a list of tuples. I have something like: ``` elements = [(1,1,1),(2,3,7),(3,5,10)] ``` I wish to extract only the second elements of each tuple into a list: ``` seconds = [1, 3, 5] ``` I know that it could be done with a `for` loop but I wanted to know if there's another...
This also works: ``` zip(*elements)[1] ``` (I am mainly posting this, to prove to myself that I have groked `zip`...) See it in action: ``` >>> help(zip) ``` > Help on built-in function zip in module **builtin**: > > zip(...) > > zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)] > > Return a list of tupl...
How to extract the n-th elements from a list of tuples in python?
3,308,102
37
2010-07-22T11:03:00Z
13,470,505
7
2012-11-20T09:50:17Z
[ "python", "list", "tuples" ]
I'm trying to obtain the n-th elements from a list of tuples. I have something like: ``` elements = [(1,1,1),(2,3,7),(3,5,10)] ``` I wish to extract only the second elements of each tuple into a list: ``` seconds = [1, 3, 5] ``` I know that it could be done with a `for` loop but I wanted to know if there's another...
Found this as I was searching for which way is fastest to pull the second element of a 2-tuple list. Not what I wanted but ran same test as shown with a 3rd method plus test the zip method ``` setup = 'elements = [(1,1) for _ in range(100000)];from operator import itemgetter' method1 = '[x[1] for x in elements]' metho...
Proper use of mutexes in Python
3,310,049
27
2010-07-22T14:40:15Z
3,311,157
68
2010-07-22T16:35:04Z
[ "python", "multithreading", "mutex" ]
I am starting with multi-threads in python (or at least it is possible that my script creates multiple threads). would this algorithm be the right usage of a Mutex? I haven't tested this code yet and it probably won't even work. I just want processData to run in a thread (one at time) and the main while loop to keep ru...
I don't know why you're using the Window's Mutex instead of Python's. Using the Python methods, this is pretty simple: ``` from threading import Thread, Lock mutex = Lock() def processData(data): mutex.acquire() try: print('Do some stuff') finally: mutex.release() while True: t = Thr...
Insert binary file in SQLite database with Python
3,310,584
7
2010-07-22T15:30:47Z
3,311,116
22
2010-07-22T16:31:40Z
[ "python", "sql", "sqlite", "binary", "blob" ]
I trying to write a simple Python script that inserts .odt documents into an SQLite database. Here what I have so far, but it doesn't seem to work: ``` f=open('Loremipsum.odt', 'rb') k=f.read() f.close() cursor.execute="INSERT INTO notes (note) VALUES ('%s')" %(sqlite.Binary(k)) cursor.close() conn.close() ``` I don'...
Not sure what is that `sqlite.Binary` you're using, but, anyway, here's a working example: ``` import sqlite3 # let's just make an arbitrary binary file... with open('/tmp/abin', 'wb') as f: f.write(''.join(chr(i) for i in range(55))) # ...and read it back into a blob with open('/tmp/abin', 'rb') as f: ablob = f....
Remove whitespaces in XML string
3,310,614
14
2010-07-22T15:34:07Z
3,317,008
21
2010-07-23T09:39:29Z
[ "python", "xml", "xml-serialization", "python-2.6", "elementtree" ]
How can I remove the whitespaces and line breaks in an XML string in Python 2.6? I tried the following packages: etree: This snippet keeps the original whitespaces: ``` xmlStr = '''<root> <head></head> <content></content> </root>''' xmlElement = xml.etree.ElementTree.XML(xmlStr) xmlStr = xml.etree.ElementTre...
The easiest solution is probably using [lxml](http://codespeak.net/lxml/), where you can set a parser option to ignore white space between elements: ``` >>> from lxml import etree >>> parser = etree.XMLParser(remove_blank_text=True) >>> xml_str = '''<root> >>> <head></head> >>> <content></content> >>> </root>'...
Remove whitespaces in XML string
3,310,614
14
2010-07-22T15:34:07Z
16,919,069
14
2013-06-04T13:23:31Z
[ "python", "xml", "xml-serialization", "python-2.6", "elementtree" ]
How can I remove the whitespaces and line breaks in an XML string in Python 2.6? I tried the following packages: etree: This snippet keeps the original whitespaces: ``` xmlStr = '''<root> <head></head> <content></content> </root>''' xmlElement = xml.etree.ElementTree.XML(xmlStr) xmlStr = xml.etree.ElementTre...
Here's something quick I came up with because I didn't want to use lxml: ``` from xml.dom import minidom from xml.dom.minidom import Node def remove_blanks(node): for x in node.childNodes: if x.nodeType == Node.TEXT_NODE: if x.nodeValue: x.nodeValue = x.nodeValue.strip() ...
Finding blank regions in image
3,310,681
8
2010-07-22T15:43:11Z
3,313,087
16
2010-07-22T20:23:07Z
[ "python", "language-agnostic", "image-processing", "numpy", "python-imaging-library" ]
This question is somewhat language-agnostic, but my tool of choice happens to be a numpy array. What I am doing is taking the difference of two images via PIL: ``` img = ImageChops.difference(img1, img2) ``` And I want to find the rectangular regions that contain changes from one picture to another. Of course there'...
I believe [scipy's ndimage module](http://docs.scipy.org/doc/scipy/reference/ndimage.html) has everything you need... Here's a quick example ``` import numpy as np import scipy as sp import scipy.ndimage.morphology # The array you gave above data = np.array( [ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...
Python generator that returns the same thing forever
3,311,266
2
2010-07-22T16:50:13Z
3,311,285
8
2010-07-22T16:52:21Z
[ "python", "generator" ]
I'm looking for a standard function that does this: ``` def Forever(v): while True: yield v ``` It seems so trivial I can't believe there isn't a standard version. For that matter anyone know of a good link to a list of all the standard generator functions?
Your are looking for [`itertools.repeat(object[, times])`](http://docs.python.org/library/itertools.html#itertools.repeat): > Make an iterator that returns `object` over and over again. Runs indefinitely unless the `times` argument is specified.
Python generator that returns the same thing forever
3,311,266
2
2010-07-22T16:50:13Z
3,311,290
11
2010-07-22T16:52:42Z
[ "python", "generator" ]
I'm looking for a standard function that does this: ``` def Forever(v): while True: yield v ``` It seems so trivial I can't believe there isn't a standard version. For that matter anyone know of a good link to a list of all the standard generator functions?
`itertools.repeat(x[, count])` repeats x a finite number of times if told how many times, otherwise repeats forever. For a general list of all of the itertools generator functions, see here: <http://docs.python.org/library/itertools.html>
Why does an apostrophe in a python docstring break emacs syntax highlighting?
3,312,436
2
2010-07-22T19:07:02Z
3,312,522
7
2010-07-22T19:17:59Z
[ "python", "emacs" ]
Running GNU Emacs 22.2.1 on Ubuntu 9.04. When editing python code in emacs, if a docstring contains an apostrophe, emacs highlights all following code as a comment, until another apostrophe is used. Really annoying! In other words, if I have a docstring like this: ``` ''' This docstring has an apostrophe ' ''' ``` ...
This appears to work correctly in GNU Emacs 23.2.1. If it's not practical to upgrade, you might be able to copy `python.el` out of the Emacs 23 source code, or perhaps just the relevant pieces of it (python-quote-syntax, python-font-lock-syntactic-keywords, and the code that uses the latter, I think - I'm not much of a...
How can you get unittest2 and coverage.py working together?
3,312,451
8
2010-07-22T19:08:42Z
11,301,414
15
2012-07-02T21:25:07Z
[ "python", "code-coverage", "unittest2" ]
How can you get `unittest2` and `coverage.py` working together? In theory something like ``` coverage run unit2 discover ``` should work, but it currently just errors out. If you are a `nose` user that will be the equivalent of `nosetests --with-coverage`.
Try: ``` coverage run -m unittest discover ``` works for me.
PIL: Composite / merge two images as "Dodge"
3,312,606
3
2010-07-22T19:26:41Z
3,313,594
7
2010-07-22T21:19:26Z
[ "python", "image-processing", "python-imaging-library" ]
How do I use PIL to implement the equivalent of merging a layer in "dodge" mode with another layer (as done in Gimp/Photoshop)? I have my original image as well as the image I'd like to use as the layer to merge with, but I don't how to do the dodge merge/composite: ``` from PIL import Image, ImageFilter, ImageOps i...
There might be a pure-PIL way to do this; I don't know. However, if not, here is a way you could do it with numpy: ``` import numpy as np import Image import ImageFilter def dodge(front,back): # The formula comes from http://www.adobe.com/devnet/pdf/pdfs/blend_modes.pdf result=back*256.0/(256.0-front) re...
In Python, are single character strings guaranteed to be identical?
3,313,135
2
2010-07-22T20:28:44Z
3,313,144
14
2010-07-22T20:29:50Z
[ "python", "string", "identity" ]
I read somewhere (an SO post, I think, and probably somewhere else, too), that Python automatically references single character strings, so not only does `'a' == 'a'`, but `'a' is 'a'`. However, I can't remember reading if this is guaranteed behavior in Python, or is it just implementation specific? Bonus points for ...
It's implementation specific. It's difficult to tell, because (as the [reference](http://docs.python.org/reference/datamodel.html) says): > ... for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is ...
Check for presence of a sublist in Python
3,313,590
25
2010-07-22T21:19:14Z
3,313,605
16
2010-07-22T21:22:19Z
[ "python", "list" ]
I want to write a function that determines if a sublist exists in a larger list. ``` list1 = [1,0,1,1,1,0,0] list2 = [1,0,1,0,1,0,1] #Should return true sublistExists(list1, [1,1,1]) #Should return false sublistExists(list2, [1,1,1]) ``` Is there a Python function that can do this?
If you are sure that your inputs will only contain the single digits 0 and 1 then you can convert to strings: ``` def sublistExists(list1, list2): return ''.join(map(str, list2)) in ''.join(map(str, list1)) ``` This creates two strings so it is not the most efficient solution but since it takes advantage of the o...
Check for presence of a sublist in Python
3,313,590
25
2010-07-22T21:19:14Z
3,314,913
29
2010-07-23T02:10:38Z
[ "python", "list" ]
I want to write a function that determines if a sublist exists in a larger list. ``` list1 = [1,0,1,1,1,0,0] list2 = [1,0,1,0,1,0,1] #Should return true sublistExists(list1, [1,1,1]) #Should return false sublistExists(list2, [1,1,1]) ``` Is there a Python function that can do this?
Let's get a bit functional, shall we? :) ``` def contains_sublist(lst, sublst): n = len(sublst) return any((sublst == lst[i:i+n]) for i in xrange(len(lst)-n+1)) ``` Note that `any()` will stop on first match of sublst within lst - or fail if there is no match, after O(m\*n) ops
Django Celery implementation - OSError : [Errno 38] Function not implemented
3,314,031
10
2010-07-22T22:32:50Z
3,699,231
12
2010-09-13T09:36:40Z
[ "python", "django", "celery", "celery-task" ]
I installed django-celery and I tried to start up the worker server but I get an OSError that a function isn't implemented. I'm running CentOS release 5.4 (Final) on a VPS: ``` . broker -> amqp://guest@localhost:5672/ . queues -> . celery -> exchange:celery (direct) binding:celery . concurrency -> ...
same issue on ubuntu 10, even after full rights on shmem are given - problem still here... UP- finally done, /dev/shm was not mounted. so add shm to fstab mount shm set full 777 permissions on /dev/shm
How to call a static methods on a django model class during a south migration
3,314,173
19
2010-07-22T22:56:18Z
3,315,547
31
2010-07-23T05:20:37Z
[ "python", "django", "django-south" ]
I'm writing a data migration in south to fix some denormalized data I screwed up in earlier code. The way to figure out the right value for the incorrect field is to call a static method on the django model class. The code looks like this: ``` class Account(models.Model): name = models.CharField() @staticmeth...
You can't use methods from models.py in south migrations. The reason is that in the future models.py will evolve and sooner or later you will delete those methods, then migration will be broken. You should put all code needed by migration in migration file itself.
How do I do this replace regex in python?
3,314,517
3
2010-07-23T00:18:16Z
3,314,542
8
2010-07-23T00:28:27Z
[ "python", "regex", "string", "text" ]
Given a string of text, in Python: ``` s = "(((((hi abc )))))))" s = "***(((((hi abc ***&&&&" ``` How do I replace all non-alphabetic symbols that occur more than 3 times...as blank string For all the above, the result should be: ``` hi abc ```
This should work: `\W{3,}`: matching non-alphanumerics that occur *3 or more* times: ``` >>> s = "***(((((hi abc ***&&&&" >>> re.sub("\W{3,}", "", s) 'hi abc' >>> s = "(((((hi abc )))))))" >>> re.sub("\W{3,}", "", s) 'hi abc' ```
Python get subclass name
3,314,627
13
2010-07-23T00:50:03Z
3,314,646
9
2010-07-23T00:54:51Z
[ "python" ]
Is it possible to get the name of a subclass? For example: ``` class Foo: def bar(self): print type(self) class SubFoo(Foo): pass SubFoo().bar() ``` will print: < type 'instance' > I'm looking for a way to get "SubFoo". I know you can do `isinstance`, but I don't know the name of the class a prior...
you can use ``` SubFoo().__class__.__name__ ``` which might be off-topic, since it gives you a class name :)
Remove Last Path Component In a String
3,315,045
18
2010-07-23T02:44:34Z
3,315,066
36
2010-07-23T02:51:17Z
[ "python", "string" ]
I have a path: ``` myPath = "C:\Users\myFile.txt" ``` I would like to remove the end path so that the string only contains: ``` "C:\Users" ``` So far I am using split, but it just gives me a list, and im stuck at this point. ``` myPath = myPath.split(os.sep) ```
You should not manipulate paths directly, there is os.path module for that. ``` >>> import os.path >>> print os.path.dirname("C:\Users\myFile.txt") C:\Users >>> print os.path.dirname(os.path.dirname("C:\Users\myFile.txt")) C:\ ``` Like this.
sharing a :memory: database between different threads in python using sqlite3 package
3,315,046
9
2010-07-23T02:44:40Z
24,708,173
16
2014-07-11T23:49:45Z
[ "python", "sqlite", "sqlite3", "python-multithreading" ]
I would like to create a :memory: database in python and access it from different threads. Essentially something like: ``` class T(threading.Thread): def run(self): self.conn = sqlite3.connect(':memory:') # do stuff with the database for i in xrange(N): T().start() ``` and have all the connec...
SQLite had improved over last 4 years, so now shared in-memory databases are possible. Check the following code: ``` import sqlite3 foobar_uri = 'file:foobar_database?mode=memory&cache=shared' not_really_foobar_uri = 'file:not_really_foobar?mode=memory&cache=shared' # connect to databases in no particular order db2 ...
Summing Non-Integers in Python sum([[1],[2]]) = [1,2]
3,315,365
2
2010-07-23T04:16:43Z
3,315,386
8
2010-07-23T04:23:51Z
[ "python", "sum" ]
Is it possible to take the sum of non-integers in python? The command ``` sum([[1],[2]]) ``` for example, gives the error ``` Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> sum([[1,2,3],[2,3,4]]) TypeError: unsupported operand type(s) for +: 'int' and 'list' ``` I suspect sum tri...
It looks like you want this: ``` >>> sum([[1],[2]], []) [1, 2] ``` You're right that it's trying to add 0 to [1] and getting an error. The solution is to give `sum` an extra parameter giving the start value, which for you would be the empty list. Edit: As gnibbler says, though, `sum` is not a good way to concatenate...
Summing Non-Integers in Python sum([[1],[2]]) = [1,2]
3,315,365
2
2010-07-23T04:16:43Z
3,315,419
7
2010-07-23T04:33:53Z
[ "python", "sum" ]
Is it possible to take the sum of non-integers in python? The command ``` sum([[1],[2]]) ``` for example, gives the error ``` Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> sum([[1,2,3],[2,3,4]]) TypeError: unsupported operand type(s) for +: 'int' and 'list' ``` I suspect sum tri...
It's a bad idea to use `sum()` on anything other than numbers, as it has quadradic performance for sequences/strings/etc. Better to use a list comprehension to sum your lists ``` [j for i in [[1],[2]] for j in i] ```
How do I get a string format of the current date time, in python?
3,316,882
21
2010-07-23T09:24:07Z
3,316,916
71
2010-07-23T09:28:54Z
[ "python", "datetime" ]
For example, on July 5, 2010, I would like to calculate the string ``` July 5, 2010 ``` How should this be done?
You can use the [`datetime` module](http://docs.python.org/library/datetime.html) for working with dates and times in Python. The [`strftime` method](http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior) allows you to produce string representation of dates and times with a format you specify. ``...
How do I get a string format of the current date time, in python?
3,316,882
21
2010-07-23T09:24:07Z
3,316,918
9
2010-07-23T09:29:09Z
[ "python", "datetime" ]
For example, on July 5, 2010, I would like to calculate the string ``` July 5, 2010 ``` How should this be done?
``` >>> import datetime >>> now = datetime.datetime.now() >>> now.strftime("%B %d, %Y") 'July 23, 2010' ```
Nested loop comparison in Python,Java and C
3,318,012
4
2010-07-23T12:15:27Z
3,318,069
12
2010-07-23T12:23:21Z
[ "java", "python", "c", "performance" ]
The following code in python takes very long to run. (I couldn't wait until the program ended, though my friend told me for him it took 20 minutes.) But the equivalent code in Java runs in approximately 8 seconds and in C it takes 45 seconds. I expected Python to be slow but not this much, and in case of C which I ex...
Your test is not measuring anything meaningful. A language's performance in the real world has little to do with how quickly it executes a tight loop. Frankly, I'm intrigued that C and Java took as long as they did; I would have expected both of their compilers to realize that there was nothing happening inside the i...
Nested loop comparison in Python,Java and C
3,318,012
4
2010-07-23T12:15:27Z
3,318,106
8
2010-07-23T12:28:47Z
[ "java", "python", "c", "performance" ]
The following code in python takes very long to run. (I couldn't wait until the program ended, though my friend told me for him it took 20 minutes.) But the equivalent code in Java runs in approximately 8 seconds and in C it takes 45 seconds. I expected Python to be slow but not this much, and in case of C which I ex...
The lesson is: Performance is never what you expect. Therefore, always measure, never believe. Some reasons why you might see these numbers (and from the first sentence, some of these might be completely wrong): C is compiled for an "i586" processor (also called Pentium). That CPU was sold from 1993 to about 2000. Ha...
How can I extend Python's datetime.datetime with my own methods?
3,318,348
5
2010-07-23T13:03:46Z
14,214,646
12
2013-01-08T12:10:04Z
[ "python", "datetime", "subclass" ]
I'm trying to extend Python's `datetime.datetime` class with a couple of extra methods. So, for example I'm doing: ``` import datetime class DateTime(datetime.datetime): def millisecond(self): return self.microsecond/1000 ``` but then if I do ``` >>> d = DateTime(2010, 07, 11, microsecond=3000) >>> prin...
A bit late, but the following works: ``` import ctypes as c _get_dict = c.pythonapi._PyObject_GetDictPtr _get_dict.restype = c.POINTER(c.py_object) _get_dict.argtypes = [c.py_object] import datetime def millisecond(td): return (td.microsecond / 1000) d = _get_dict(datetime.datetime)[0] d['millisecond'] = millis...
Efficient bidirectional hash table in Python?
3,318,625
39
2010-07-23T13:38:21Z
3,318,648
27
2010-07-23T13:41:45Z
[ "python", "hashtable", "bidirectional" ]
Python dict is a very useful datastructure: ``` d = {'a': 1, 'b': 2} d['a'] # get 1 ``` Sometimes you'd also like to index by values. ``` d[1] # get 'a' ``` Which is the most efficient way to implement this datastructure? Any official recommend way to do it? Thanks!
A poor man's bidirectional hash table would be to use just two dictionaries (these are highly tuned datastructures already). There is also a [bidict](https://pypi.python.org/pypi/bidict) package on the index: * <https://pypi.python.org/pypi/bidict> The source for bidict can be found on github: * <https://github.com...
Efficient bidirectional hash table in Python?
3,318,625
39
2010-07-23T13:38:21Z
3,318,808
25
2010-07-23T13:59:45Z
[ "python", "hashtable", "bidirectional" ]
Python dict is a very useful datastructure: ``` d = {'a': 1, 'b': 2} d['a'] # get 1 ``` Sometimes you'd also like to index by values. ``` d[1] # get 'a' ``` Which is the most efficient way to implement this datastructure? Any official recommend way to do it? Thanks!
You can use the same dict itself by adding key,value pair in reverse order. ``` d={'a':1,'b':2} revd=dict([reversed(i) for i in d.items()]) d.update(revd) ```
Efficient bidirectional hash table in Python?
3,318,625
39
2010-07-23T13:38:21Z
21,894,086
20
2014-02-19T22:34:23Z
[ "python", "hashtable", "bidirectional" ]
Python dict is a very useful datastructure: ``` d = {'a': 1, 'b': 2} d['a'] # get 1 ``` Sometimes you'd also like to index by values. ``` d[1] # get 'a' ``` Which is the most efficient way to implement this datastructure? Any official recommend way to do it? Thanks!
Here is a class for a bidirectional `dict`. (inspired by [Finding key from value in Python dictionary:](http://stackoverflow.com/questions/7657457/finding-key-from-value-in-python-dictionary) and modified to allow 2) and 3)) Note that : * 1) The *inverse directory* `bd.inverse` auto-updates itself when the standard d...
mod_wsgi, mod_python, or just cgi?
3,319,545
35
2010-07-23T15:16:50Z
3,319,566
15
2010-07-23T15:19:08Z
[ "python", "apache", "cgi", "mod-wsgi" ]
I've been playing around with my own webserver (Apache+Ubuntu) and python. From what I've seen there are 3(?) main ways of doing this: 1. Apache configured to handle .py as cgi 2. Apache configured to use mod\_python that is now outdated(?) 3. Apache configured to use mod\_wsgi I recall reading that Django prefers mo...
1. Don't use CGI. It's inefficient. Spawning a new process for each request. No thanks 2. Dont't spend much time with mod\_python 3. Use mod\_wsgi. If you want to write CGI-like stuff without a framework, use mod\_wsgi anyway. The WSGI standard ([PEP 333](http://www.python.org/dev/peps/pep-0333/)) is essential for cre...
mod_wsgi, mod_python, or just cgi?
3,319,545
35
2010-07-23T15:16:50Z
3,319,585
25
2010-07-23T15:20:32Z
[ "python", "apache", "cgi", "mod-wsgi" ]
I've been playing around with my own webserver (Apache+Ubuntu) and python. From what I've seen there are 3(?) main ways of doing this: 1. Apache configured to handle .py as cgi 2. Apache configured to use mod\_python that is now outdated(?) 3. Apache configured to use mod\_wsgi I recall reading that Django prefers mo...
[mod\_python](http://blog.dscpl.com.au/2010/06/modpython-project-is-now-officially.html) is dead, so using mod\_python probably isn't a good idea for new projects. Personally, I prefer to use mod\_wsgi over CGI (or FastCGI). It's dead-simple to set up, and much more efficient.
mod_wsgi, mod_python, or just cgi?
3,319,545
35
2010-07-23T15:16:50Z
3,320,020
8
2010-07-23T16:03:20Z
[ "python", "apache", "cgi", "mod-wsgi" ]
I've been playing around with my own webserver (Apache+Ubuntu) and python. From what I've seen there are 3(?) main ways of doing this: 1. Apache configured to handle .py as cgi 2. Apache configured to use mod\_python that is now outdated(?) 3. Apache configured to use mod\_wsgi I recall reading that Django prefers mo...
I would go with mod\_wsgi too. If you want a deeper understanding about the question, have a look at this: * [Apache, FastCGI and Python](http://www.electricmonk.nl/docs/apache_fastcgi_python/apache_fastcgi_python.html), by Ferry Boender Good stuff!
mod_wsgi, mod_python, or just cgi?
3,319,545
35
2010-07-23T15:16:50Z
20,295,852
7
2013-11-30T02:34:20Z
[ "python", "apache", "cgi", "mod-wsgi" ]
I've been playing around with my own webserver (Apache+Ubuntu) and python. From what I've seen there are 3(?) main ways of doing this: 1. Apache configured to handle .py as cgi 2. Apache configured to use mod\_python that is now outdated(?) 3. Apache configured to use mod\_wsgi I recall reading that Django prefers mo...
# Mod\_Python mod\_python is alive and well. See here: <http://modpython.org/>. Furthermore, here's the documentation for the latest release, 3.5.0, with support for Python 3: <http://modpython.org/live/current/modpython.pdf>. Currently I use it. # Mod\_WSGI mod\_wsgi thinks of itself as not to be used barebones, bu...
join tables with django
3,319,632
2
2010-07-23T15:25:00Z
3,319,712
11
2010-07-23T15:32:41Z
[ "python", "django" ]
``` queryObj = Rating.objects.select_related( 'Candidate','State','RatingCandidate','Sig','Office','OfficeCandidate').get( rating_id = ratingId, ratingcandidate__rating = ratingId, ratingcandidate__rating_candidate_id = \ officecandidate__office_candidate_id) ``` This line giv...
> I'm trying to get many different tables that are linked by primary keys and regular ids. **Don't try to "join" tables. This isn't SQL.** You have to do multiple gets to get data from many different tables. Don't worry about `select_related` until you can prove that you have a bottle-neck. Just do the various GETs...
Problem with Python logging RotatingFileHandler in Django website
3,319,860
11
2010-07-23T15:47:38Z
5,314,460
7
2011-03-15T16:00:53Z
[ "python", "django", "logging" ]
I've a django powered website, and I use standard logging module to track web activity. The log is done via RotatingFileHandler which is configured with 10 log files, 1000000 byte each. The log system works, but this are the log files I get: ``` -rw-r--r-- 1 apache apache 83 Jul 23 13:30 hr.log -rw-r--r...
I've found this behavior when there are multiple precesses are running with your code. Unfortunatelly no perfect option exists. Some ideas, you can incorporate are: * use WatchedFileHandler (new in 2.6) and rotate with external programs as logrotate * use syslog or other log aggregating server * use python log aggre...
Fill OUTSIDE of polygon | Mask array where indicies are beyond a circular boundary?
3,320,311
11
2010-07-23T16:35:33Z
3,320,426
11
2010-07-23T16:47:45Z
[ "python", "matplotlib" ]
I use `plot(x,y,'r')` to plot a red circle. x and y are arrays such that when paired as (x,y) and plotted, all points form a circle-line. `fill(x,y,'r')` plots a red circle that is filled in (or colored in) red. How can I keep the circle white on the inside, but fill outside the circle out to the axis boundaries? I ...
> All I am really needing to do is mask > out numbers in a 2d array that are > located beyond this boundary of the > circle created with x and y, such that > when the 2D array is viewed as a color > plot, or contour, inside the circle > will be the image, and outside will be > white-ed out. You have two options: Firs...
How to check if a path is absolute path or relative path in cross platform way with Python?
3,320,406
64
2010-07-23T16:45:41Z
3,320,427
11
2010-07-23T16:47:49Z
[ "python", "path" ]
UNIX absolute path starts with '/', whereas Windows starts with alphabet 'C:' or '\'. Does python has a standard function to check if a path is absolute or relative?
Use [`os.path.isabs`](http://docs.python.org/library/os.path.html#os.path.isabs).