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
create & read from tempfile
5,344,287
23
2011-03-17T19:39:23Z
5,344,603
9
2011-03-17T20:06:39Z
[ "python" ]
Is there anyway I could write to tempfile and include it in a command, and then close/remove it. I would like to execute the command, eg: some\_command /tmp/some-temp-file. Many thanks in advance. ``` import tempfile temp = tempfile.TemporaryFile() temp.write('Some data') command=(some_command temp.name) temp.close(...
Try this: ``` import tempfile import commands import os commandname = "cat" f = tempfile.NamedTemporaryFile(delete=False) f.write("oh hello there") f.close() # file is not immediately deleted because we # used delete=False res = commands.getoutput("%s %s" % (commandname,f.name)) print res os.unlink(f.name...
create & read from tempfile
5,344,287
23
2011-03-17T19:39:23Z
9,396,740
42
2012-02-22T14:30:50Z
[ "python" ]
Is there anyway I could write to tempfile and include it in a command, and then close/remove it. I would like to execute the command, eg: some\_command /tmp/some-temp-file. Many thanks in advance. ``` import tempfile temp = tempfile.TemporaryFile() temp.write('Some data') command=(some_command temp.name) temp.close(...
Complete example. ``` import tempfile with tempfile.NamedTemporaryFile() as temp: temp.write('Some data') temp.flush() command=(some_command temp.name) ```
A loopless 3D matrix multiplication in python
5,344,843
4
2011-03-17T20:28:18Z
5,344,981
7
2011-03-17T20:39:01Z
[ "python", "matrix", "numpy", "operation" ]
I am looking to do the following operation in python (numpy). ``` Matrix A is M x N x R Matrix B is N x 1 x R ``` Matrix multiply AB = C, where C is a M x 1 x R matrix. Essentially each M x N layer of A (R of them) is matrix multiplied independently by each N x 1 vector in B. I am sure this is a one-liner. I have bee...
[numpy.tensordot()](http://docs.scipy.org/doc/numpy/reference/generated/numpy.tensordot.html) is the right way to do it: ``` a = numpy.arange(24).reshape(2, 3, 4) b = numpy.arange(12).reshape(3, 1, 4) c = numpy.tensordot(a, b, axes=[1, 0]).diagonal(axis1=1, axis2=3) ``` **Edit**: The first version of this was faulty,...
A loopless 3D matrix multiplication in python
5,344,843
4
2011-03-17T20:28:18Z
21,401,049
7
2014-01-28T09:01:40Z
[ "python", "matrix", "numpy", "operation" ]
I am looking to do the following operation in python (numpy). ``` Matrix A is M x N x R Matrix B is N x 1 x R ``` Matrix multiply AB = C, where C is a M x 1 x R matrix. Essentially each M x N layer of A (R of them) is matrix multiplied independently by each N x 1 vector in B. I am sure this is a one-liner. I have bee...
Sorry for the necromancy, but this answer can be substantially improved upon, using the invaluable np.einsum. ``` import numpy as np D,M,N,R = 1,2,3,4 A = np.random.rand(M,N,R) B = np.random.rand(N,D,R) print np.einsum('mnr,ndr->mdr', A, B).shape ``` Note that it has several advantages: first of all, its fast. np.e...
How to set GET parameters with PyCurl?
5,345,599
3
2011-03-17T21:39:14Z
5,345,691
9
2011-03-17T21:48:21Z
[ "python", "rest", "get", "pycurl" ]
I'm trying to make a GET request for a REST api using PycURL. I am able to successful make a request if I do not pass any parameters. I am also able to make a POST request by doing the following: curl.setopt(pycurl.POSTFIELDS, post\_data) I want to make a get request that includes login parameters. If I try to use th...
Just like a normal URL on the browser, GET parameters are encoded and appended after a `?` to the URL. Using python's [urllib.urlencode](http://docs.python.org/library/urllib.html#urllib.urlencode), you can do: ``` import urllib import pycurl url = 'http://www.google.com/search' params = {'q': 'stackoverflow answers'...
Can a Python Fabric task invoke other tasks and respect their hosts lists?
5,346,135
28
2011-03-17T22:37:16Z
8,173,504
28
2011-11-17T20:02:16Z
[ "python", "deployment", "ssh", "fabric" ]
I have a fabfile like the following: ``` @hosts('host1') def host1_deploy(): """Some logic that is specific to deploying to host1""" @hosts('host2') def host2_deploy(): """Some logic that is specific to deploying to host2""" def deploy(): """"Deploy to both hosts, each using its own logic""" host1_de...
Since Fabric 1.3, the `execute` helper is now available to do just this. The documentation is available here: [Intelligently executing tasks with execute](http://docs.fabfile.org/en/1.8/usage/execution.html#intelligently-executing-tasks-with-execute). Here is the example they use: ``` from fabric.api import run, role...
Python Pyramid & Chameleon templating language escapes html
5,346,295
3
2011-03-17T22:55:37Z
5,348,881
9
2011-03-18T06:42:11Z
[ "python", "pyramid", "chameleon", "template-tal" ]
I can't make sense of chameleon's tags. I'm a django user, but decided to introduce my CompSci course mates and myself to Pyramid, since I though more lightweight = easier to learn. At the moment the ${} tag is escaping any html tags I'm trying to output through it. In django there was some way to specify that a varia...
Chameleon is based on the [Zope Page Templates](http://docs.zope.org/zope2/zope2book/ZPT.html) library, so if you find the Chameleon documentation lacking, you might wish to check out the zpt docs. In any case, there are two main ways to do this. If you are rendering using a tal:replace or tal:content tag attribute, y...
Python Pyramid & Chameleon templating language escapes html
5,346,295
3
2011-03-17T22:55:37Z
10,369,248
14
2012-04-29T02:32:32Z
[ "python", "pyramid", "chameleon", "template-tal" ]
I can't make sense of chameleon's tags. I'm a django user, but decided to introduce my CompSci course mates and myself to Pyramid, since I though more lightweight = easier to learn. At the moment the ${} tag is escaping any html tags I'm trying to output through it. In django there was some way to specify that a varia...
Chameleon also allows ${structure: markup}.
savetxt How change the type from float64 to int or double
5,346,362
5
2011-03-17T23:04:53Z
5,349,447
12
2011-03-18T08:07:43Z
[ "python", "numpy", "scipy" ]
I have been trying to use the `savetxt` function in numpy. The problem I am running into is that even thought I define my variables accordingly, i.e. int() or double(), the text file i am getting out has floats in them. How can I change that? Input is as follows: `pNoise=[int(i), around(pNoise[0], decimals=3), around(...
You can define how the output has to be formatted with the `fmt` keyword of `np.savetxt`, eg: ``` np.savetxt("file.txt", output, fmt='%10.5f', delimiter='\t') ``` for floats rounded to five decimals, or `fmt='%i'` to have the output as integers. Here you can find more information about the possibilities of `fmt`: <...
Python, logging: use custom handler with dictionary configuration?
5,346,661
4
2011-03-17T23:52:19Z
5,346,703
8
2011-03-17T23:58:56Z
[ "python", "logging", "configuration", "dictionary", "handler" ]
this is about the logging module on Python 3.2 (GNU/Linux x86\_64): is it possible to set a custom handler with dictionary configuration? This is the code I'm trying: ``` import logging import logging.config class CustomHandler(logging.StreamHandler): pass logconfig = { 'version': 1, 'handlers': { ...
You need to tell it where to find the `CustomHandler` class. The string should contain the module (and possibly package) where it can be found. If you are running this script directly, you can use `__main__.CustomHandler`. Otherwise, use `your_module.CustomHandler`, Where you replace `your_module` with the name of the ...
Python: how to find value in list smaller than target
5,347,003
3
2011-03-18T01:07:23Z
5,347,702
9
2011-03-18T03:20:15Z
[ "python" ]
For example I have a non-ordered list of values [10, 20, 50, 200, 100, 300, 250, 150] I have this code which returns the next greater value: ``` def GetNextHighTemp(self, temp, templist): target = int(temp) list = [] for t in templist: if t != "": list.append(int(t)) return str(m...
A better and much faster (code and cpu wise) way is to use bisect module which does binary search but for that you will need to sort the list first, here is the sample usage: ``` import bisect mylist = [10, 20, 50, 200, 100, 300, 250, 150] mylist.sort() index = bisect.bisect(mylist, 55) print "Greater than target", ...
Interweaving two numpy arrays
5,347,065
25
2011-03-18T01:20:51Z
5,347,082
18
2011-03-18T01:24:08Z
[ "python", "arrays", "numpy" ]
Assume the following arrays are given: ``` a = array([1,3,5]) b = array([2,4,6]) ``` How would one interweave them efficiently so that one gets a third array like this ``` c = array([1,2,3,4,5,6]) ``` It can be assumed that `length(a)==length(b)`.
Here is a one-liner: ``` c = numpy.vstack((a,b)).reshape((-1,),order='F') ```
Interweaving two numpy arrays
5,347,065
25
2011-03-18T01:20:51Z
5,347,492
40
2011-03-18T02:41:13Z
[ "python", "arrays", "numpy" ]
Assume the following arrays are given: ``` a = array([1,3,5]) b = array([2,4,6]) ``` How would one interweave them efficiently so that one gets a third array like this ``` c = array([1,2,3,4,5,6]) ``` It can be assumed that `length(a)==length(b)`.
I like Josh's answer. I just wanted to add a more mundane, usual, and slightly more verbose solution. I don't know which is more efficient. I expect they will have similar performance. ``` import numpy as np a = np.array([1,3,5]) b = np.array([2,4,6]) c = np.empty((a.size + b.size,), dtype=a.dtype) c[0::2] = a c[1::2...
How to preallocate a list of lists?
5,347,108
8
2011-03-18T01:27:56Z
5,347,126
8
2011-03-18T01:32:12Z
[ "python" ]
I am creating a list of lists using this code: ``` zeroArray = [0]*Np zeroMatrix = [] for i in range(Np): zeroMatrix.append(zeroArray[:]) ``` Is there a more efficient way to do this? I'm hoping for something along the lines of zeroArray = [0]\*Np; zeroMat = zeroArray\*Np but can't find anything similar.
You could do this: ``` zeroMatrix = [[0] * Np for i in range(Np)] ``` --- **Update**: Well if we're going to make it into a race, I've found something faster (on my computer) than Omnifarious' method. This doesn't beat numpy of course; but this is all academic anyway right? I mean we're talking about microseconds he...
How to preallocate a list of lists?
5,347,108
8
2011-03-18T01:27:56Z
5,347,252
9
2011-03-18T01:59:04Z
[ "python" ]
I am creating a list of lists using this code: ``` zeroArray = [0]*Np zeroMatrix = [] for i in range(Np): zeroMatrix.append(zeroArray[:]) ``` Is there a more efficient way to do this? I'm hoping for something along the lines of zeroArray = [0]\*Np; zeroMat = zeroArray\*Np but can't find anything similar.
Maybe you should consider using [NumPy](http://numpy.scipy.org/). It seems like you're doing numerical work, which is what it's made for. This is the fastest so far, not including the import statement: ``` import numpy Np = 80 zeroMatrix = numpy.zeros((Np, Np)) ``` Times: ``` >python -m timeit -s "import numpy; Np =...
Is it possible to colour a specific item in a Listbox widget?
5,348,454
4
2011-03-18T05:28:51Z
5,349,373
12
2011-03-18T07:56:33Z
[ "python", "user-interface", "colors", "listbox", "tkinter" ]
I'm referring to a specific element in the `Listbox` widget. Colouring the background is most desired but any form of colouring for a specific cell would be fantastic.
According to the `effbot.org` documentation regarding the [`Listbox`](http://effbot.org/tkinterbook/listbox.htm#Tkinter.Listbox) widget you cannot change the color of spefic items: > The listbox can only contain text items, and all items must have the same font and color But actually you can change both the font and ...
How can I get the product of all elements in a one dimensional numpy array
5,349,570
8
2011-03-18T08:25:41Z
5,349,616
11
2011-03-18T08:32:58Z
[ "python", "numpy" ]
I have a one dimensional NumPy array: ``` a = numpy.array([2,3,3]) ``` I would like to have the product of all elements, 18 in this case. The only way I could find to do this would be: ``` b = reduce(lambda x,y: x*y, a) ``` Which looks pretty, but is not very fast (I need to do this a lot). Is there a numpy metho...
In NumPy you can try: ``` numpy.prod(a) ``` For a larger array `numpy.arange(1,40) / 10.`: ``` array([ 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. , 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2, 3.3, ...
Google App Engine Static Files GET 404
5,349,671
7
2011-03-18T08:40:16Z
5,353,989
7
2011-03-18T15:15:00Z
[ "python", "google-app-engine", "http-status-code-404" ]
The following app.yaml works great on my local dev server.. but when I deploy it to production all static files throw 404. Server isn't able to locate any static files. Have been searching for hours couldn't find a valid solution. Note: I am developing with mac, so aware of the case sensitive nature of the system. ``...
Take a look at the app.yaml in this gist: <https://gist.github.com/873098> It successfully serves a static site. The main differences I see are the lack of the './' as noted by @Wooble above, and the use of (.\*) instead of (.+) as the main regular expression. (.+) should work in theory though.
Do list comprehensions in Python reduce in a memory efficient manner?
5,349,755
8
2011-03-18T08:49:26Z
5,349,793
14
2011-03-18T08:52:21Z
[ "python", "list", "reduce" ]
I am a beginner at Python, and this is my first post, so don't be too harsh :). I've been playing around with Python lately and was wondering if something like ``` max([x for x in range(25)]) ``` would result in Python first creating a list of all the elements and then finding the max, resulting in O(2n) time, or it ...
Your example will result in Python first building the entire list. If you want to avoid that, you can use a generator expression instead: ``` max((x for x in range(25))) ``` or simply: ``` max(x for x in range(25)) ``` Of course (in Python 2), `range` itself builds an entire list, so what you really want in this ca...
Usage of "aliased" in SQLAlchemy ORM
5,350,033
4
2011-03-18T09:18:52Z
5,350,982
12
2011-03-18T11:00:11Z
[ "python", "orm", "sqlalchemy" ]
From the [SQLAlchemy ORM Tutorial](http://www.sqlalchemy.org/docs/orm/tutorial.html): > You can control the names using the label() construct for scalar attributes and aliased for class constructs: ``` >>> from sqlalchemy.orm import aliased >>> user_alias = aliased(User, name='user_alias') >>> for row in session.quer...
`aliased()` or `alias()` are used whenever you need to use the `SELECT ... FROM my_table my_table_alias ...` construct in SQL, mostly when using the same table more than once in a query (self-joins, with or without extra tables). You also need to alias subqueries in certain cases. There's an example in the documentati...
Can i set float128 as the standard float-array in numpy
5,350,342
10
2011-03-18T09:56:04Z
5,351,486
15
2011-03-18T11:43:12Z
[ "python", "numpy" ]
So i have a problem with my numerical program, and i'm curious about whether it is a precision problem (i.e. round-off error). Is there a quick way to change all the float arrays in my program into float128 arrays, without going through my code and typing dtype='float128' all over the place. My arrays are all float64, ...
I don't think there is a central "configuration" you could change to achieve this. Some options what you could do: 1. If you are creating arrays only by very few of NumPy's factory functions, substitute these functions by your own versions. If you import these functions like ``` from numpy import empty ``` ...
Is there implementation of Git in pure Python?
5,350,518
12
2011-03-18T10:13:15Z
5,350,644
12
2011-03-18T10:25:25Z
[ "python", "git", "dvcs" ]
Is there implementation of Git in pure Python?
Found [Dulwich](http://samba.org/~jelmer/dulwich/): > Dulwich is a pure-Python > implementation of the Git file formats > and protocols. > > The project is named after the village > in which Mr. and Mrs. Git live in the > Monty Python sketch. Looks like a low-level library, the API did not appear friendly to my eyes,...
Generate a django queryset based on dict keys
5,350,846
2
2011-03-18T10:44:56Z
5,350,915
8
2011-03-18T10:51:50Z
[ "python", "django", "dictionary", "django-queryset" ]
I have a dict like: ``` { 'key1' : val1, 'key2' : val2 } ``` And I need a queryset like ``` Q(key1__icontains = val1) | Q(key2__icontains = val2) ``` Thanks
``` reduce(operator.or_, Q(**{key + '__icontains': val}) for (key, val) in D.iteritems()) ```
Is this a safe use of python eval()?
5,351,059
4
2011-03-18T11:07:18Z
5,351,110
11
2011-03-18T11:11:15Z
[ "python", "security" ]
If an attacker can control the value of `attacker_controlled_nasty_variable`, is this segment of code vulnerable? ``` dic={"one":1, "nasty":attacker_controlled_nasty_variable, } store=str(dict) ... dic=eval(store) ```
Use `ast.literal_eval()` instead of `eval()`.
Column default value persisted to the table
5,351,739
5
2011-03-18T12:06:14Z
5,358,795
13
2011-03-18T23:27:16Z
[ "python", "sqlalchemy" ]
I am currently using a `Column` that has the following signature: `Column('my_column', DateTime, default=datetime.datetime.utcnow)` I am trying to figure out how to change that in order to be able to do vanilla sql inserts (`INSERT INTO ...`) rather than through sqlalchemy. Basically I want to know how to persist the...
There are multiple ways to have SQLAlchemy define how a value should be set on insert/update. You can view them in the [documentation](http://docs.sqlalchemy.org/en/latest/core/defaults.html). The way you're doing it right now (defining a `default` argument for the column) will only affect when SQLAlchemy is generatin...
Use fnmatch.filter to filter files by more than one possible file extension
5,351,766
20
2011-03-18T12:09:17Z
5,351,876
7
2011-03-18T12:19:20Z
[ "python", "filesystems" ]
Given the following piece of python code: ``` for root, dirs, files in os.walk(directory): for filename in fnmatch.filter(files, '*.png'): pass ``` How can I filter for more than one extension? In this special case I want to get all files ending with \*.png, \*.gif, \*.jpg or \*.jpeg. For now I came up w...
I think your code is actually fine. If you want to touch every filename only once, define your own filtering function: ``` def is_image_file(filename, extensions=['.jpg', '.jpeg', '.gif', '.png']): return any(filename.endswith(e) for e in extensions) for root, dirs, files in os.walk(directory): for filename i...
Use fnmatch.filter to filter files by more than one possible file extension
5,351,766
20
2011-03-18T12:09:17Z
5,351,968
24
2011-03-18T12:27:14Z
[ "python", "filesystems" ]
Given the following piece of python code: ``` for root, dirs, files in os.walk(directory): for filename in fnmatch.filter(files, '*.png'): pass ``` How can I filter for more than one extension? In this special case I want to get all files ending with \*.png, \*.gif, \*.jpg or \*.jpeg. For now I came up w...
If you only need to check extensions (i.e. no further wildcards), why don't you simply use basic string operations? ``` for root, dirs, files in os.walk(directory): for filename in files: if filename.endswith(('.jpg', '.jpeg', '.gif', '.png')): pass ```
Obtain the first part of an URL from Django template
5,352,455
7
2011-03-18T13:12:50Z
5,352,902
45
2011-03-18T13:48:46Z
[ "python", "django", "templates", "url", "django-templates" ]
I use `request.path` to obtain the current URL. For example if the current URL is "/test/foo/baz" I want to know if it starts with a string sequence, let's say /test. If I try to use: ``` {% if request.path.startswith('/test') %} Test {% endif %} ``` I get an error saying that it could not parse the remainder of ...
You can use the slice filter to get the first part of the url ``` {% if request.path|slice:":5" == '/test' %} Test {% endif %} ``` Cannot try this now, and don't know if filters work inside 'if' tag, if doesn't work you can use the 'with' tag ``` {% with request.path|slice:":5" as path %} {% if path == '/test'...
Obtain the first part of an URL from Django template
5,352,455
7
2011-03-18T13:12:50Z
11,871,181
17
2012-08-08T18:51:00Z
[ "python", "django", "templates", "url", "django-templates" ]
I use `request.path` to obtain the current URL. For example if the current URL is "/test/foo/baz" I want to know if it starts with a string sequence, let's say /test. If I try to use: ``` {% if request.path.startswith('/test') %} Test {% endif %} ``` I get an error saying that it could not parse the remainder of ...
Instead of checking for the prefix with startswith, you can get the same thing by checking for membership with the builtin `in` tag. ``` {% if '/test' in request.path %} Test {% endif %} ``` This will pass cases where the string is not strictly in the beginning, but you can simply avoid those types of URLs.
best way to extract subset of key-value pairs from python dictionary object
5,352,546
112
2011-03-18T13:21:03Z
5,352,630
156
2011-03-18T13:28:01Z
[ "python", "dictionary" ]
I have a big dictionary object that has several key value pairs (about 16), I am only interested in 3 of them. What is the best way (shortest/efficient/elegant) to achieve that? The best I know is: ``` bigdict = {'a':1,'b':2,....,'z':26} subdict = {'l':bigdict['l'], 'm':bigdict['m'], 'n':bigdict['n']} ``` I am sure...
You could try: ``` dict((k, bigdict[k]) for k in ('l', 'm', 'n')) ``` ... or in ~~Python 3~~ Python versions 2.7 or later *(thanks to [Fábio Diniz](http://stackoverflow.com/users/541842/fabio-diniz) for pointing that out that it works in 2.7 too)*: ``` {k: bigdict[k] for k in ('l', 'm', 'n')} ``` *Update: As [Håv...
best way to extract subset of key-value pairs from python dictionary object
5,352,546
112
2011-03-18T13:21:03Z
5,352,649
44
2011-03-18T13:28:55Z
[ "python", "dictionary" ]
I have a big dictionary object that has several key value pairs (about 16), I am only interested in 3 of them. What is the best way (shortest/efficient/elegant) to achieve that? The best I know is: ``` bigdict = {'a':1,'b':2,....,'z':26} subdict = {'l':bigdict['l'], 'm':bigdict['m'], 'n':bigdict['n']} ``` I am sure...
A bit shorter, at least: ``` wanted_keys = ['l', 'm', 'n'] # The keys you want dict((k, bigdict[k]) for k in wanted_keys if k in bigdict) ```
best way to extract subset of key-value pairs from python dictionary object
5,352,546
112
2011-03-18T13:21:03Z
5,352,658
14
2011-03-18T13:29:39Z
[ "python", "dictionary" ]
I have a big dictionary object that has several key value pairs (about 16), I am only interested in 3 of them. What is the best way (shortest/efficient/elegant) to achieve that? The best I know is: ``` bigdict = {'a':1,'b':2,....,'z':26} subdict = {'l':bigdict['l'], 'm':bigdict['m'], 'n':bigdict['n']} ``` I am sure...
``` interesting_keys = ('l', 'm', 'n') subdict = {x: bigdict[x] for x in interesting_keys if x in bigdict} ```
How to set class names dynamically?
5,352,781
26
2011-03-18T13:39:02Z
5,353,609
25
2011-03-18T14:43:50Z
[ "python" ]
I have a function that creates classes derived from it's arguments: ``` def factory(BaseClass) : class NewClass(BaseClass) : pass return NewClass ``` Now when I use it to create new classes, the classes are all named the same, and the instances look like they have the same type: ``` NewA = factory(ClassA) Ne...
Yes, setting `__name__` is the correct thing to do; you don't need to set anything else to adjust the class name. For example: ``` def factory(BaseClass) : class NewClass(BaseClass): pass NewClass.__name__ = "factory_%s" % BaseClass.__name__ return NewClass ``` `type` is the *wrong* thing to use here. It...
Python multiple comparisons style?
5,354,048
8
2011-03-18T15:19:28Z
5,354,074
16
2011-03-18T15:21:08Z
[ "python", "coding-style", "comparison", "readability" ]
I am wondering if there is a way to do the following in a more compact style: ``` if (text == "Text1" or text=="Text2" or text=="Text3" or text=="Text4"): do_something() ``` The problem is i have more than just 4 comparisons in the if statement and it's starting to look rather long, ambiguous, and ugly. Any ideas...
How about this: ``` if text in ( 'Text1', 'Text2', 'Text3', 'Text4' ): do_something() ``` I've always found that simple and elegant.
Python multiple comparisons style?
5,354,048
8
2011-03-18T15:19:28Z
5,354,168
7
2011-03-18T15:27:12Z
[ "python", "coding-style", "comparison", "readability" ]
I am wondering if there is a way to do the following in a more compact style: ``` if (text == "Text1" or text=="Text2" or text=="Text3" or text=="Text4"): do_something() ``` The problem is i have more than just 4 comparisons in the if statement and it's starting to look rather long, ambiguous, and ugly. Any ideas...
The "if text in" answer is good, but you might also think about the re (regular expressions) package if your text strings fit a pattern. For example, taking your example literally, "Text" followed by a digit would be a simple regular expression. Here's an example that should work for "Text" followed by a digit. the \Z...
Multiple different results returned on case-sensitive 'exact' query in django
5,354,061
4
2011-03-18T15:20:21Z
5,354,305
11
2011-03-18T15:35:49Z
[ "python", "django", "django-models", "case-sensitive" ]
I have an instance of django 1.2.1 running on ubuntu with a mysql 5 backend. I am trying to make a case-sensitive query that should only return one result, but I am getting two results back that have the same content but with different cases. I want to get an entry with the following title: Cat on the Internet syndrom...
<http://code.djangoproject.com/ticket/2170> > To get the functionally correctly, > change the Collation of the MySql? > database to latin1\_swedish\_cs or > utf8\_bin for case sensitive > comparisons.
How can I add attributes to a module at run time?
5,354,676
9
2011-03-18T16:04:08Z
5,355,549
10
2011-03-18T17:16:52Z
[ "python" ]
I have a need to add module attributes at run time. For example, when a module is loaded, it reads the file where the data is contained. I would like that data to be available as a module attribute, but the data is only available at run time. How can I add module attributes at run time?
If you don't know the attribute name until runtime, use `setattr`: ``` >>> import mymodule >>> setattr(mymodule, 'point', (1.0, 4.0)) >>> mymodule.point (1.0, 4.0) ```
How can I add attributes to a module at run time?
5,354,676
9
2011-03-18T16:04:08Z
5,356,035
13
2011-03-18T18:03:02Z
[ "python" ]
I have a need to add module attributes at run time. For example, when a module is loaded, it reads the file where the data is contained. I would like that data to be available as a module attribute, but the data is only available at run time. How can I add module attributes at run time?
Thanks @Dharmesh. That was what I needed. There is only one change that needs to be made. The module won't be importing itself so to get the module object I can do: `setattr(sys.modules[__name__], 'attr1', 'attr1')`
Programatically Save Draft in Gmail drafts folder
5,355,067
5
2011-03-18T16:37:05Z
5,358,289
9
2011-03-18T22:02:59Z
[ "java", "python", "api", "gmail" ]
Preferably using Python or Java, I want to compose an email and save it into gmail drafts without user intervention,
Here's a Python script to access a Gmail account. First you need to generate an OAuth token. Download [Google's xoauth.py module](http://code.google.com/p/google-mail-xoauth-tools/wiki/XoauthDotPyRunThrough) and run it. It will walk you through the steps. You'll get a url to obtain a verification code -- paste this int...
Passing dict to constructor?
5,355,121
10
2011-03-18T16:42:04Z
5,355,152
20
2011-03-18T16:44:14Z
[ "python", "dictionary", "constructor" ]
I'd like to pass a dict to an object's constructor for use as kwargs. Obviously: ``` foo = SomeClass(mydict) ``` Simply passes a single argument, rather than the dict's contents. Alas: ``` foo = SomeClass(kwargs=mydict) ``` Which seems more sensible doesn't work either. What am I missing?
Use : ``` foo = SomeClass(**mydict) ``` this will unpack the dict value and pass them to the function. For example: ``` mydict = {'a': 1, 'b': 2} SomeClass(**mydict) # Equivalent to : SomeClass(a=1, b=2) ```
python: can executable zip files include data files?
5,355,694
15
2011-03-18T17:29:25Z
5,356,563
10
2011-03-18T18:55:31Z
[ "python" ]
Being fairly new to python I only recently discovered the ability to directly execute a .zip file by placing a `__main__.py` file at the top of the file. This works great for python code, but can I bundle other types of files and access them with my scripts? If so, how? My ultimate goal would be to bundle some image f...
You could use [`pkg_resources`](http://packages.python.org/setuptools/pkg_resources.html#basic-resource-access) functions to access files: ``` # __main__.py import pkg_resources from PIL import Image print pkg_resources.resource_string(__name__, 'README.txt') im = Image.open(pkg_resources.resource_stream('app', 'im....
Numpy: Joining structured arrays?
5,355,744
15
2011-03-18T17:33:54Z
5,355,974
9
2011-03-18T17:56:03Z
[ "python", "numpy" ]
## Input I have many [numpy structured arrays](http://docs.scipy.org/doc/numpy/user/basics.rec.html) in a list like this example: ``` import numpy a1 = numpy.array([(1, 2), (3, 4), (5, 6)], dtype=[('x', int), ('y', int)]) a2 = numpy.array([(7,10), (8,11), (9,12)], dtype=[('z', int), ('w', float)]) arrays = [a1, a2...
Here is an implementation that should be faster. It converts everything to arrays of `numpy.uint8` and does not use any temporaries. ``` def join_struct_arrays(arrays): sizes = numpy.array([a.itemsize for a in arrays]) offsets = numpy.r_[0, sizes.cumsum()] n = len(arrays[0]) joint = numpy.empty((n, off...
Numpy: Joining structured arrays?
5,355,744
15
2011-03-18T17:33:54Z
5,356,137
26
2011-03-18T18:13:41Z
[ "python", "numpy" ]
## Input I have many [numpy structured arrays](http://docs.scipy.org/doc/numpy/user/basics.rec.html) in a list like this example: ``` import numpy a1 = numpy.array([(1, 2), (3, 4), (5, 6)], dtype=[('x', int), ('y', int)]) a2 = numpy.array([(7,10), (8,11), (9,12)], dtype=[('z', int), ('w', float)]) arrays = [a1, a2...
You can also use the function `merge_arrays` of `numpy.lib.recfunctions`: ``` import numpy.lib.recfunctions as rfn rfn.merge_arrays(arrays, flatten = True, usemask = False) Out[52]: array([(1, 2, 7, 10.0), (3, 4, 8, 11.0), (5, 6, 9, 12.0)], dtype=[('x', '<i4'), ('y', '<i4'), ('z', '<i4'), ('w', '<f8')]) ```
How do I give focus to a python Tkinter text widget?
5,356,655
7
2011-03-18T19:04:20Z
5,356,756
12
2011-03-18T19:13:51Z
[ "python", "text", "widget", "tkinter" ]
I'd like to be able to open the App GUI and have it automatically place the cursor into a particular text widget. Best case scenario is: as soon as the app is launched someone can start typing without having to click on the text widget. This is just a small example displaying the issue: ``` from Tkinter import * root ...
You use the `focus_set` method. For example: ``` from Tkinter import * root = Tk() Window = Frame(root) TextWidget = Text(Window) TextWidget.pack() Window.pack() TextWidget.focus_set() root.mainloop() ```
Python: get string representation of PyObject?
5,356,773
21
2011-03-18T19:15:29Z
8,215,231
25
2011-11-21T16:39:58Z
[ "python", "string", "pyobject" ]
I've got a C python extension, and I would like to print out some diagnostics. I'm receiving a string as a PyObject\*. What's the canonical way to obtain a string rep of this object, such that it usable as a const char \*? **update:** clarified to emphasize access as const char \*.
Use `PyObject_Repr` (to mimic Python's `repr` function) or `PyObject_Str` (to mimic `str`), and then call `PyString_AsString` to get `char *` (you can, and usually should, use it as `const char*`, for example: ``` PyObject* objectsRepresentation = PyObject_Repr(yourObject); const char* s = PyString_AsString(objectsRep...
Python regex: matching a parenthesis within parenthesis
5,357,460
9
2011-03-18T20:23:58Z
5,357,617
15
2011-03-18T20:41:35Z
[ "python", "regex" ]
I've been trying to match the following string: ``` string = "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))" ``` But unfortunately my knowledge of regular expressions is very limited, as you can see there are two parentheses that need to be matched, along with the content inside the second one I tried ...
Try this: ``` import re w = "TEMPLATES = ( ('index.html', 'home'), ('base.html', 'base'))" # find outer parens outer = re.compile("\((.+)\)") m = outer.search(w) inner_str = m.group(1) # find inner pairs innerre = re.compile("\('([^']+)', '([^']+)'\)") results = innerre.findall(inner_str) for x,y in results: prin...
__coerce__ vs. __ihook__ difference?
5,357,648
2
2011-03-18T20:45:09Z
5,357,886
7
2011-03-18T21:13:22Z
[ "python" ]
in python, you have `__coerce__` and `__ihook__`. According to [PEP 203](http://www.python.org/dev/peps/pep-0203/) (Augmented Assigments) they are both invoked, in this order to perform in place operations on objects, with `__coerce__` called first, and `__ihook__` next. I don't know if these methods have been made spe...
The `__ihook__` in that PEP stands for one of the following methods: ``` __iadd__ __isub__ __imul__ __idiv__ __imod__ __ipow__ __ilshift__ __irshift__ __iand__ __ixor__ __ior__ ``` They are *in place* operations of their respective `__hook__`s. For example, `a+=b` does some...
What's the easiest way to iterate on a file's lines, keeping a counter?
5,357,948
4
2011-03-18T21:21:19Z
5,357,956
9
2011-03-18T21:22:27Z
[ "python" ]
What's the cleanest code that iterates on the lines of a text file, while simultaniously increamenting a counter? I understand that with multiple assignment, there's a cleaner syntax than ``` i = 0 for line in f: ... ++i ```
``` for count, line in enumerate(f): ``` Enumerate starts at index 0 unless told otherwise providing a counter iterated at the same time as each item of your for loop EDIT: As a side note you can change where enumerate starts from with the second argument e.g. `for count, line in enumerate(f, 11)` would cause it to s...
What's the easiest way to iterate on a file's lines, keeping a counter?
5,357,948
4
2011-03-18T21:21:19Z
5,357,957
12
2011-03-18T21:22:47Z
[ "python" ]
What's the cleanest code that iterates on the lines of a text file, while simultaniously increamenting a counter? I understand that with multiple assignment, there's a cleaner syntax than ``` i = 0 for line in f: ... ++i ```
``` for i, line in enumerate(f): print i, line ``` As seen here: <http://docs.python.org/library/functions.html#enumerate>
Establishing an IPv6 connection using sockets in python
5,358,021
4
2011-03-18T21:28:57Z
5,358,510
7
2011-03-18T22:41:51Z
[ "python", "sockets", "networking", "ipv6" ]
I am trying to run this very basic socket example: ``` import socket host = 'ipv6hostnamegoeshere' port=9091 ourSocket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM, 0) ourSocket.connect((host, port)) ``` Yet, I get the error: ``` ourSocket.connect((host, port)) File "<string>", line 1, in connect socke...
As the [socket.connect docs](http://docs.python.org/library/socket.html#socket.socket.connect) says, `AF_INET6` expects a 4-tuple: > sockaddr is a tuple describing a > socket address, whose format depends > on the returned family (a (address, > port) 2-tuple for AF\_INET, a (address, > port, flow info, scope id) 4-tup...
Python: Creating a number of lists depending on the count
5,358,530
2
2011-03-18T22:44:31Z
5,358,549
10
2011-03-18T22:47:05Z
[ "python" ]
Im trying to create a number of lists depending on the number in my header\_count. The code below should generate 3 lists but i get a syntax error instead. ``` header_count = 4 for i in range(1, header_count): header_%s = [] % i ```
This is my interpretation of what you want, I hope I guessed it right (you weren't very clear). ``` header_count = 4 headers = [[] for i in range(1, header_count)] ``` Now you can use it like this: ``` headers[1].append("this goes in the first header") headers[2].append("this goes in the second header") ```
Numpy table - advanced multiple criteria selection
5,359,235
5
2011-03-19T00:50:47Z
5,359,351
7
2011-03-19T01:19:15Z
[ "python", "table", "numpy", "selection" ]
I have a table that goes something like this: ``` IDs Timestamp Values 124 300.6 1.23 124 350.1 -2.4 309 300.6 10.3 12 123.4 9.00 18 350.1 2.11 309 350.1 8.3 ... ``` and I'd like to select all the rows that belong to a group of I...
You can do it like this: ``` subset = table[np.array([i in id_list for i in table.IDs])] ``` If you have a more recent version of numpy, you can use the `in1d` function to make it a bit more compact: ``` subset = table[np.in1d(table.IDs, id_list)] ``` See also this question: [numpy recarray indexing based on inters...
What is a good database for low-memory use?
5,359,638
3
2011-03-19T02:30:10Z
5,359,712
9
2011-03-19T02:48:07Z
[ "python", "database", "django" ]
I'm looking for a database with a low memory footprint to use with Django. I only have these requirements: * Usable with Django (even if the use isn't well documented) * Runs on Ubuntu or CentOS (packages preferred, installing from source is OK) * Free and open source * Low memory footprint * Able to serve about 50 co...
[SQLite](http://www.sqlite.org/)
Python class accessible by iterator and index
5,359,679
14
2011-03-19T02:41:43Z
5,359,693
21
2011-03-19T02:43:41Z
[ "python", "list", "iterator" ]
Might be a n00b question, but I currently have a class that implements an iterator so I can do something like ``` for i in class(): ``` but I want to be able to access the class by index as well like ``` class()[1] ``` How can I do that? Thanks!
Implement both [`__iter__()`](http://docs.python.org/reference/datamodel.html#object.__iter__) and [`__getitem__()`](http://docs.python.org/reference/datamodel.html#object.__getitem__) et alia methods.
Python class accessible by iterator and index
5,359,679
14
2011-03-19T02:41:43Z
27,803,404
22
2015-01-06T16:55:35Z
[ "python", "list", "iterator" ]
Might be a n00b question, but I currently have a class that implements an iterator so I can do something like ``` for i in class(): ``` but I want to be able to access the class by index as well like ``` class()[1] ``` How can I do that? Thanks!
The current [accepted answer](http://stackoverflow.com/a/5359693/2437514) from @Ignacio Vazquez-Abrams is sufficient. However, others interested in this question may want to consider inheriting their class from an [abstract base class](https://www.python.org/dev/peps/pep-3119/) (such as those found in the [standard mod...
How to split a list into pairs in all possible ways
5,360,220
22
2011-03-19T05:07:05Z
5,360,340
26
2011-03-19T05:32:37Z
[ "python" ]
I have a list (say 6 elements for simplicity) ``` L = [0, 1, 2, 3, 4, 5] ``` and I want to chunk it into pairs in **ALL** possible ways. I show some configurations: ``` [(0, 1), (2, 3), (4, 5)] [(0, 1), (2, 4), (3, 5)] [(0, 1), (2, 5), (3, 4)] ``` and so on. Here `(a, b) = (b, a)` and the order of pairs is not impo...
Take a look at [`itertools.combinations`](http://docs.python.org/library/itertools.html#itertools.combinations). ``` matt@stanley:~$ python Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import itertools >>> list(iterto...
How to split a list into pairs in all possible ways
5,360,220
22
2011-03-19T05:07:05Z
5,360,442
16
2011-03-19T05:56:04Z
[ "python" ]
I have a list (say 6 elements for simplicity) ``` L = [0, 1, 2, 3, 4, 5] ``` and I want to chunk it into pairs in **ALL** possible ways. I show some configurations: ``` [(0, 1), (2, 3), (4, 5)] [(0, 1), (2, 4), (3, 5)] [(0, 1), (2, 5), (3, 4)] ``` and so on. Here `(a, b) = (b, a)` and the order of pairs is not impo...
I don't think there's any function in the standard library that does exactly what you need. Just using `itertools.combinations` can get you a list of all possible individual pairs, but doesn't actually solve the problem of all valid pair combinations. You could solve this easily with: ``` import itertools def all_pai...
How to Run multiple classes in Single Test Suite in Python Unit testing?
5,360,833
8
2011-03-19T07:40:44Z
5,822,577
8
2011-04-28T17:24:35Z
[ "python", "unit-testing" ]
How to Run multiple Classes in Single Test Suite in Python Unit testing .....
I'm a bit unsure at what you're asking here, but if you want to know how to test multiple classes in the same suite, usually you just create multiple testclasses in the same python file and run them together: ``` import unittest class TestSomeClass(unittest.TestCase): def testStuff(self): # your testc...
How to Run multiple classes in Single Test Suite in Python Unit testing?
5,360,833
8
2011-03-19T07:40:44Z
16,823,869
13
2013-05-29T21:11:47Z
[ "python", "unit-testing" ]
How to Run multiple Classes in Single Test Suite in Python Unit testing .....
If you want to run tests from multiple test classes, but not all of the test classes in a module, just a specific list of test classes, you can use a `TestLoader` to get a `TestSuite` of tests for each class, and then put all those suites together in one big suite to run: ``` import unittest class TestClassA(unittest...
How do I package a python application to make it pip-installable?
5,360,873
85
2011-03-19T07:53:53Z
5,364,844
80
2011-03-19T20:54:30Z
[ "python", "django", "dependencies", "pip" ]
I'm writing a django application in my spare time for a footy-tipping competition we're running at work. I figured I'd use this time wisely, and get up to speed on virtualenv, pip, packaging, django 1.3, and how to write an easily redistributable application. So far, so good. I'm up to the packaging part. A lot of the...
Yes, `MANIFEST.in` and `setup.py` should be sufficient. This blog post really has some good information on this topic: [Packaging a Django reusable app](http://bruno.im/2010/may/05/packaging-django-reusable-app/) And here's another good, detailed overview that helped me a lot: [Python Packaging User Guide](https://pa...
DictReader, No quotes, tabbed file
5,360,932
8
2011-03-19T08:09:28Z
5,360,978
12
2011-03-19T08:22:15Z
[ "python", "csv" ]
I have a csv file that looks like this: Please note, there are no quotes, a tab (\t) is the delimiter, and there is a blank line between the header and the actual content. ``` Facility No Testing No Name Age 252 2351 Jackrabbit, Jazz 15 345 257 Aardvark, Ethel 41 ``` I think I've tr...
What is your `csvFile`? Is it a string representing your filename starting with 'F'? `csv.DictReader` needs an opened file object, not a filename. Try: ``` with open(csvFile, 'rb') as f: reader = csv.DictReader(f, delimiter='\t', quoting=csv.QUOTE_NONE) print reader.fieldnames ``` **EDIT** If your `csvFile...
The influence of ? in the regex string
5,361,205
4
2011-03-19T09:16:50Z
5,361,215
11
2011-03-19T09:19:10Z
[ "python", "regex" ]
Consider the following Python code: ``` >>> re.search(r'.*(99)', 'aa99bb').groups() ('99',) >>> re.search(r'.*(99)?', 'aa99bb').groups() (None,) ``` I don't understand why I don't catch 99 in the second example.
This is because the `.*` first matches the entire string. At that point, it's not possible to match `99` any more, and since the group is optional, the regex engine stops because it has found a successful match. If on the other hand the group is mandatory, the regex engine has to backtrack into the `.*`. Compare the ...
What does __setattr__ do in this python code?
5,361,291
2
2011-03-19T09:35:04Z
5,361,323
7
2011-03-19T09:47:03Z
[ "python", "get", "set" ]
this is my code: ``` class fun: def __getattr__(self,key): return self[key] def __setattr__(self,key,value): self[key] = value+1 a = fun() a['x']=1 print a['x'] ``` and the error is : ``` AttributeError: fun instance has no attribute '__getitem__' ``` when i change it to : ``` class fun: ...
The problem is that `self.key = ...` invokes `__setattr__`, so you end up in an infinite recursion. To use `__setattr__`, you have to access the object's field some other way. There are two common solutions: ``` def __setattr__(self,key,value): # Access the object's fields through the special __dict__ field se...
Why does (()) equal ()?
5,361,416
7
2011-03-19T10:06:35Z
5,361,435
12
2011-03-19T10:08:38Z
[ "python" ]
``` >>> (()) == () True >>> (()) () ```
`()` is a 0-tuple. `(foo)` results in the value of `foo`. Hence, `(())` results in a 0-tuple. From [the tutorial](http://docs.python.org/tutorial/datastructures.html): > ; a tuple with one item is constructed > by following a value with a comma (it > is not sufficient to enclose a single > value in parentheses).
Load module from string in python
5,362,771
19
2011-03-19T14:43:34Z
7,548,190
39
2011-09-25T19:57:23Z
[ "python" ]
I have some code in the form of a string and would like to make a module out of it without writing to disk. When I try using imp and a StringIO object to do this, I get: ``` >>> imp.load_source('my_module', '', StringIO('print "hello world"')) Traceback (most recent call last): File "<stdin>", line 1, in <module> T...
Here is how to import a string as a module (**Python 2.x**): ``` import sys,imp my_code = 'a = 5' mymodule = imp.new_module('mymodule') exec my_code in mymodule.__dict__ ``` In **Python 3**, exec is a function, so this should work: ``` import sys,imp my_code = 'a = 5' mymodule = imp.new_module('mymodule') exec(my_...
Numpy NdArray Memoization
5,362,781
8
2011-03-19T14:45:44Z
5,362,876
8
2011-03-19T15:02:21Z
[ "python", "multidimensional-array", "matrix", "numpy", "memoization" ]
I'm working on some fairly computational intensive calculations that deal with numpy matrices and ndarrays, and from some digging around, there are about a dozen ways **not** to implement memoization, generally full of collisions, and issues with ndarrays being mutable objects. Has anyone come across a fairly general ...
How about this package: <http://packages.python.org/joblib/memory.html>
In the Inline "open and write file" is the close() implicit?
5,362,901
13
2011-03-19T15:06:35Z
5,362,917
23
2011-03-19T15:09:34Z
[ "python", "file" ]
In Python (>2.7) does the code : ``` open('tick.001', 'w').write('test') ``` has the same result as : ``` ftest = open('tick.001', 'w') ftest.write('test') ftest.close() ``` and where to find documentation about the 'close' for this inline functionnality ?
The `close()` here happens when the `file` object is deallocated from memory, as part of its deletion logic. Because modern Pythons on other virtual machines — like Java and .NET — cannot control when an object is deallocated from memory, it is no longer considered good Python to `open()` like this without a `close...
Reloading submodules in IPython
5,364,050
192
2011-03-19T18:39:10Z
5,368,413
16
2011-03-20T12:16:13Z
[ "python", "numpy", "ipython" ]
Currently I am working on a python project that contains sub modules and uses numpy/scipy. Ipython is used as interactive console. Unfortunately I am not very happy with workflow that I am using right now, I would appreciate some advice. In IPython, the framework is loaded by a simple `import` command. However, it is ...
IPython offers [`dreload()`](http://ipython.github.com/ipython-doc/rel-0.10.1/html/interactive/reference.html#dreload) to recursively reload all submodules. Personally, I prefer to use the [`%run()`](http://ipython.github.com/ipython-doc/rel-0.10.1/html/interactive/tutorial.html#the-run-magic-command) magic command (th...
Reloading submodules in IPython
5,364,050
192
2011-03-19T18:39:10Z
5,399,339
283
2011-03-22T23:55:41Z
[ "python", "numpy", "ipython" ]
Currently I am working on a python project that contains sub modules and uses numpy/scipy. Ipython is used as interactive console. Unfortunately I am not very happy with workflow that I am using right now, I would appreciate some advice. In IPython, the framework is loaded by a simple `import` command. However, it is ...
IPython comes with some automatic reloading magic: ``` %load_ext autoreload %autoreload 2 ``` It will reload all changed modules every time before executing a new line. The way this works is slightly different than `dreload`. Some caveats apply, type `%autoreload?` to see what can go wrong. --- If you want to alway...
Reloading submodules in IPython
5,364,050
192
2011-03-19T18:39:10Z
9,179,917
18
2012-02-07T16:27:09Z
[ "python", "numpy", "ipython" ]
Currently I am working on a python project that contains sub modules and uses numpy/scipy. Ipython is used as interactive console. Unfortunately I am not very happy with workflow that I am using right now, I would appreciate some advice. In IPython, the framework is loaded by a simple `import` command. However, it is ...
In IPython 0.12 (and possibly earlier), you can use this: ``` %load_ext autoreload %autoreload 2 ``` This is essentially the same as the answer by [pv.](http://stackoverflow.com/users/108184/pv), except that the extension has been renamed and is now loaded using `%load_ext`.
Lemmatizing POS tagged words with NLTK?
5,364,493
13
2011-03-19T19:49:16Z
5,365,755
24
2011-03-19T23:47:27Z
[ "python", "nlp", "nltk" ]
I have POS tagged some words with nltk.pos\_tag(), so they are given treebank tags. I would like to lemmatize these words using the known POS tags, but I am not sure how. I was looking at Wordnet lemmatizer, but I am not sure how to convert the treebank POS tags to tags accepted by the lemmatizer. How can I perform thi...
The wordnet lemmatizer only knows four parts of speech (ADJ, ADV, NOUN, and VERB) and only the NOUN and VERB rules do anything especially interesting. The noun parts of speech in the treebank tagset all start with NN, the verb tags all start with VB, the adjective tags start with JJ, and the adverb tags start with RB. ...
Python JSON decoding
5,365,132
4
2011-03-19T21:49:37Z
5,365,156
8
2011-03-19T21:52:29Z
[ "python", "json", "simplejson" ]
I'm having some trouble decoding this json in python. From basehttpserver I'm getting back ``` [ { "changed_aspect": "media", "object": "geography", "object_id": "1306", "subscription_id": 1326, "time": 1300570688 } ] ``` which I'm putting into simplejsondecoder with ``` data = simplejson....
When you decode the JSON you get exactly what it looks like, a list containing a single item. `data[0]` should be the dictionary you expected to see.
Can zope.interface define how a class' __init__ method should look?
5,365,348
3
2011-03-19T22:26:55Z
5,367,884
7
2011-03-20T10:25:13Z
[ "python", "zope" ]
I have several similar classes which will all be initialised by the same code, and thus need to have the same "constructor signature." (Are there really constructors and signatures in the dynamic Python? I digress.) What is the best way to define a classes \_\_ init \_\_ parameters using zope.interface? I'll paste so...
First of all: there is a big difference between the concepts of *providing* and *implementing* an interface. Basically, classes *implement* an interface, instances of those classes *provide* that interface. After all, classes are the blueprints for instances, detailing their implementations. Now, an interface describ...
Problem with regexp python and sqlite
5,365,451
8
2011-03-19T22:48:08Z
5,365,533
17
2011-03-19T23:07:22Z
[ "python", "regex", "sqlite3" ]
I try to check a string with a pattern using a regex with python on a sqlite database. I have problem when I try de search string having " with a patern using " For exemple: ``` cur.execute("insert into articles(id,subject) values (1,'aaa\"test\"')") cur.execute("select id,subject from articles where id = 1") print (c...
Use parametrized sql. Then you don't need to escape the quotes yourself: ``` import sqlite3 import re def regexp(expr, item): reg = re.compile(expr) return reg.search(item) is not None conn = sqlite3.connect(':memory:') conn.create_function("REGEXP", 2, regexp) cursor = conn.cursor() cursor.execute('CREATE T...
Numpy converting array from float to strings
5,365,520
12
2011-03-19T23:05:12Z
5,379,916
21
2011-03-21T15:34:35Z
[ "python", "numpy", "matplotlib" ]
I have an array of floats that I have normalised to one (i.e. the largest number in the array is 1), and I wanted to use it as colour indices for a graph. In using matplotlib to use grayscale, this requires using strings between 0 and 1, so I wanted to convert the array of floats to an array of strings. I was attemptin...
You seem a bit confused as to how numpy arrays work behind the scenes. Each item in an array must be the *same size*. The string representation of a float doesn't work this way. For example, `repr(1.3)` yields `'1.3'`, but `repr(1.33)` yields `'1.3300000000000001'`. A accurate string representation of a floating poin...
Why is the value of __name__ changing after assignment to sys.modules[__name__]?
5,365,562
12
2011-03-19T23:13:49Z
5,365,733
20
2011-03-19T23:43:50Z
[ "python", "module" ]
While trying to do something similar to what's in the ActiveState recipe titled [Constants in Python](http://code.activestate.com/recipes/65207-constants-in-python/) by Alex Martelli, I ran into the unexpected side-effect (in Python 2.7) that assigning a class instance to an entry in `sys.modules` has -- namely that do...
This happens because you have overwrite your module when you did `sys.modules[__name__] = _test()` so your module was deleted (because the module didn't have any references to it anymore and the reference counter went to zero so it's deleted) but in the mean time the interpreter still have the byte code so it will stil...
Is it possible to override Sphinx autodoc for specific functions?
5,365,684
9
2011-03-19T23:35:17Z
5,368,194
12
2011-03-20T11:29:56Z
[ "python", "python-sphinx", "autodoc" ]
I'm using Sphinx's autodoc plugin to automatically document a set of modules. I have a function that accepts `*args`, and I'd like to override the documentation to show the slightly nicer `funcname(arg1[, arg2[, ...]])` style that the Python stdlib docs use. Is it possible to override the autodoc output for a specific...
It is possible to override a signature by using `autofunction`: ``` .. automodule:: yourmodule :members: :exclude-members: funcname .. autofunction:: funcname(arg1[, arg2[, ...]]) ``` However, the function with the overridden signature is not sorted with the other functions pulled in with `automodule`. Using e...
In PyTables, how to create nested array of variable length?
5,366,099
10
2011-03-20T01:12:25Z
9,876,449
8
2012-03-26T17:01:19Z
[ "python", "pytables" ]
I'm using PyTables 2.2.1 w/ Python 2.6, and I would like to create a table which contains nested arrays of variable length. I have searched the PyTables documentation, and the tutorial example ([PyTables Tutorial 3.8](http://www.pytables.org/docs/manual/ch03.html#id332794)) shows how to create a nested array of length...
I have a similar task: to dump fixed size data with arrays of a variable length. I first tried using fixed size StringCol(64\*1024) fields to store my variable length data (they are always < 64K). But it was rather slow and wasted a lot of disk space, despite blosc compression. After days of investigation I ended wit...
Installing PIL on OS X Snow Leopard w/Xcode4 (no PPC support)
5,366,882
18
2011-03-20T05:10:50Z
5,369,871
39
2011-03-20T16:45:20Z
[ "python", "xcode", "python-imaging-library", "ppc" ]
Xcode4 dropped PPC support, so when I try building PIL, it throws hate: ``` Bens-MacBook-Air:Imaging-1.1.7 bkeating$ python setup.py build running buildrunning build_pyrunning build_ext --- using frameworks at /System/Library/Frameworks building '_imaging' extension /usr/bin/gcc-4.0 -fno-strict-aliasing -fno-common -d...
The solution has nothing to do with PIL but rather setting gcc's ARCHFLAGS: ``` ARCHFLAGS="-arch i386 -arch x86_64" sudo pip install PIL ```
Installing PIL on OS X Snow Leopard w/Xcode4 (no PPC support)
5,366,882
18
2011-03-20T05:10:50Z
5,524,205
16
2011-04-02T15:57:54Z
[ "python", "xcode", "python-imaging-library", "ppc" ]
Xcode4 dropped PPC support, so when I try building PIL, it throws hate: ``` Bens-MacBook-Air:Imaging-1.1.7 bkeating$ python setup.py build running buildrunning build_pyrunning build_ext --- using frameworks at /System/Library/Frameworks building '_imaging' extension /usr/bin/gcc-4.0 -fno-strict-aliasing -fno-common -d...
ARCHFLAGS doesn't seem to get passed into sudo. I had to do ``` sudo -s ``` then `ARCHFLAGS="-arch i386 -arch x86_64" pip install PIL` to make it work.
Installing PIL on OS X Snow Leopard w/Xcode4 (no PPC support)
5,366,882
18
2011-03-20T05:10:50Z
5,912,697
14
2011-05-06T14:14:55Z
[ "python", "xcode", "python-imaging-library", "ppc" ]
Xcode4 dropped PPC support, so when I try building PIL, it throws hate: ``` Bens-MacBook-Air:Imaging-1.1.7 bkeating$ python setup.py build running buildrunning build_pyrunning build_ext --- using frameworks at /System/Library/Frameworks building '_imaging' extension /usr/bin/gcc-4.0 -fno-strict-aliasing -fno-common -d...
A better way to solve this issue, in my opinion, would be to edit your ~/.profile or /etc/bashrc and add the line: ``` export ARCHFLAGS="-arch i386 -arch x86_64" ``` Will save messing around with any future installations (I've just had to do this for installing lots of Perl modules in CPAN)!
Python DFS and BFS
5,368,326
4
2011-03-20T11:56:01Z
5,368,496
8
2011-03-20T12:32:14Z
[ "python", "graph", "breadth-first-search" ]
Here <http://www.python.org/doc/essays/graphs/> is DFS right ? I try to do something with 'siblings', but it does not work. Can anyone write BFS similar to code from this site.
Yes, it is DFS. To write a BFS you just need to keep a "todo" queue. You probably also want to turn the function into a generator because often a BFS is deliberately ended before it generates all possible paths. Thus this function can be used to be find\_path or find\_all\_paths. ``` def paths(graph, start, end): ...
Django DateTimeField Defined as blank=True, null=True but doesn't allow null
5,368,345
6
2011-03-20T12:01:26Z
5,368,498
9
2011-03-20T12:32:18Z
[ "python", "django" ]
I have a DateTimeField in one of my Django models. ``` completed_date = models.DateTimeField('date completed', blank=True, null=True) ``` I've defined it to allow blank and null values. However, when I try to create an instance of the model, I get the following error: > IntegrityError at > /admin/tasks/project/a...
[django syncdb and an updated model](http://stackoverflow.com/questions/1605662/django-syncdb-and-an-updated-model) from that question/answer: > Django doesn't support migrations out > of the box. There is a pluggable app > for Django that does exactly that > though, and it works great. It's > called South. [`http:/...
Convert base64 to Image in Python
5,368,669
5
2011-03-20T13:07:57Z
6,781,529
18
2011-07-21T19:21:45Z
[ "python", "image", "base64" ]
I have a mongoDB database and I recover base64 data which corresponds to my Image. I don't know how to convert base64 data to an Image.
Building on Christians answer, here the full circle: ``` import base64 jpgtxt = base64.encodestring(open("in.jpg","rb").read()) f = open("jpg1_b64.txt", "w") f.write(jpgtxt) f.close() # ---- newjpgtxt = open("jpg1_b64.txt","rb").read() g = open("out.jpg", "w") g.write(base64.decodestring(newjpgtxt)) g.close() ``` ...
similar tools in Python? (tools from Ruby)
5,368,960
4
2011-03-20T14:08:01Z
5,368,977
9
2011-03-20T14:10:51Z
[ "python", "ruby" ]
1. gem: package management. 2. bundler: dependency management 3. rspec: test framework. 4. watchr: autotest tool 5. yard: documentation tool. 6. rdoc Markdown: markdown for writing code's comment. 7. rvm: Ruby version Manager. 8. rake: task tool. I want to find some tools in Python can do the job describe above.
1. gem == easy\_install, a part of setuptools 2. setuptools 3. for testing framework see nosetest 4. [autonose](http://github.com/gfxmonk/autonose/tree/master) 5. epydoc or sphinx 6. use [docstrings](http://www.python.org/dev/peps/pep-0257/) 7. [virtualenv](http://pypi.python.org/pypi/virtualenv) along with [virtualenv...
Multi-level defaultdict with variable depth?
5,369,723
30
2011-03-20T16:20:00Z
5,369,814
9
2011-03-20T16:37:14Z
[ "python", "dictionary" ]
I have a large list like: ``` [A][B1][C1]=1 [A][B1][C2]=2 [A][B2]=3 [D][E][F][G]=4 ``` I want to build a multi-level dict like: ``` A --B1 -----C1=1 -----C2=1 --B2=3 D --E ----F ------G=4 ``` I know that if I use recursive defaultdict I can write `table[A][B1][C1]=1`, `table[A][B2]=2`, but this works only if I hard...
Your example says that at any level there can be a value, and also a dictionary of sub-elements. That is called a **tree**, and there are many implementations available for them. This is one: ``` from collections import defaultdict class Tree(defaultdict): def __init__(self, value=None): super(Tree, self)....
Multi-level defaultdict with variable depth?
5,369,723
30
2011-03-20T16:20:00Z
5,369,984
7
2011-03-20T17:02:16Z
[ "python", "dictionary" ]
I have a large list like: ``` [A][B1][C1]=1 [A][B1][C2]=2 [A][B2]=3 [D][E][F][G]=4 ``` I want to build a multi-level dict like: ``` A --B1 -----C1=1 -----C2=1 --B2=3 D --E ----F ------G=4 ``` I know that if I use recursive defaultdict I can write `table[A][B1][C1]=1`, `table[A][B2]=2`, but this works only if I hard...
I'd do it with a subclass of `dict` that defines `__missing__`: ``` >>> class NestedDict(dict): ... def __missing__(self, key): ... self[key] = NestedDict() ... return self[key] ... >>> table = NestedDict() >>> table['A']['B1']['C1'] = 1 >>> table {'A': {'B1': {'C1': 1}}} ``` You can't do ...
Multi-level defaultdict with variable depth?
5,369,723
30
2011-03-20T16:20:00Z
8,702,435
63
2012-01-02T15:18:33Z
[ "python", "dictionary" ]
I have a large list like: ``` [A][B1][C1]=1 [A][B1][C2]=2 [A][B2]=3 [D][E][F][G]=4 ``` I want to build a multi-level dict like: ``` A --B1 -----C1=1 -----C2=1 --B2=3 D --E ----F ------G=4 ``` I know that if I use recursive defaultdict I can write `table[A][B1][C1]=1`, `table[A][B2]=2`, but this works only if I hard...
you can even do it without defining your own classes: ``` from collections import defaultdict l=lambda:defaultdict(l) table=l() table[0][1][2][3][4][5]=6 ```
How to merge similar items in a list
5,370,294
3
2011-03-20T17:51:27Z
5,370,486
7
2011-03-20T18:27:10Z
[ "python", "arrays", "algorithm", "string", "list" ]
I haven't found anything relevant on Google, so I'm hoping to find some help here :) I've got a Python list as follows: ``` [['hoose', 200], ["Bananphone", 10], ['House', 200], ["Bonerphone", 10], ['UniqueValue', 777] ...] ``` I have a function that returns the Levenshtein distance between 2 strings, for House and h...
To bring home the point from my comment, I just grabbed an implementation of that distance from [here](http://code.activestate.com/recipes/576874-levenshtein-distance/), and calculated some distances: ``` d('House', 'hoose') = 2 d('House', 'trousers') = 4 d('trousers', 'hoose') = 5 ``` Now, suppose your threshold is ...
How to hide Firefox window (Selenium WebDriver)?
5,370,762
23
2011-03-20T19:10:05Z
5,506,230
13
2011-03-31T20:55:45Z
[ "java", "python", "firefox", "selenium", "webdriver" ]
When I execute multiple test simultaneously, i don't want to keep Firefox browser window visible.. I can minimize it using `selenium.minimizeWindow()` but I don't want to do it. Is there any way to hide Firefox window? I am using FireFox WebDriver.
Finally I found the solution for those who is using windows Machine for running the Tests using any method. Well, implementation is not in java but you can do it very easily. Use `AutoIt` tool. It has all the capability to handle windows. It is free Tool. 1. Install AutoIt: **<http://www.autoitscript.com/site/auto...
How to hide Firefox window (Selenium WebDriver)?
5,370,762
23
2011-03-20T19:10:05Z
15,663,596
9
2013-03-27T16:07:23Z
[ "java", "python", "firefox", "selenium", "webdriver" ]
When I execute multiple test simultaneously, i don't want to keep Firefox browser window visible.. I can minimize it using `selenium.minimizeWindow()` but I don't want to do it. Is there any way to hide Firefox window? I am using FireFox WebDriver.
I used xvfb to solve the problem like this. First, install Xvfb: ``` # apt-get install xvfb ``` on Debian/Ubuntu; or ``` # yum install xorg-x11-Xvfb ``` on Fedora/RedHat. Then, choose a display number that is unlikely to ever clash (even if you add a real display later) – something high like 99 should do. Run Xv...
How to hide Firefox window (Selenium WebDriver)?
5,370,762
23
2011-03-20T19:10:05Z
23,898,148
40
2014-05-27T20:17:56Z
[ "java", "python", "firefox", "selenium", "webdriver" ]
When I execute multiple test simultaneously, i don't want to keep Firefox browser window visible.. I can minimize it using `selenium.minimizeWindow()` but I don't want to do it. Is there any way to hide Firefox window? I am using FireFox WebDriver.
### Python The easiest way to hide the browser is to [install PhantomJS](http://phantomjs.org/download.html). Then, change this line: ``` driver = webdriver.Firefox() ``` to: ``` driver = webdriver.PhantomJS() ``` The rest of your code won't need to be changed and no browser will open. For debugging purposes, use ...
django: documented way to get an object's fields? / Meta documentation?
5,371,531
7
2011-03-20T21:12:59Z
5,371,831
9
2011-03-20T22:01:50Z
[ "python", "database", "django", "orm", "documentation" ]
I'm making a function to convert a model object into a dictionary (and all foreignkeys into more dictionaries, recursively). I learned from a friend that I can get a model's fields by looking at `obj._meta.fields`, but I can't find documentation for this anywhere... is there a documented way to get a model's fields? Is...
This seemed fairly interesting, so I went looking through the django.forms source, looking specifically for the ModelForm implementation. I figured a ModelForm would be quite good at introspecting a given instance, and it just so happens that there is a handy function available that may help you on your way. ``` >>> f...
Python: check if value is in a list no matter the CaSE
5,371,935
10
2011-03-20T22:18:33Z
5,371,960
16
2011-03-20T22:23:03Z
[ "python", "loops" ]
I want to check if a value is in a list, no matter what the case of the letters are, and I need to do it efficiently. This is what I have: ``` if val in list: ``` But I want it to ignore case
``` check = "asdf" checkLower = check.lower() print any(checkLower == val.lower() for val in ["qwert", "AsDf"]) # prints true ``` Using the [any()](http://docs.python.org/library/functions.html#any) function. This method is nice because you aren't recreating the list to have lowercase, it is iterating over the list,...
List comprehension to extract a list of tuples from dictionary
5,372,282
11
2011-03-20T23:20:06Z
5,372,331
23
2011-03-20T23:25:32Z
[ "python", "list", "list-comprehension", "tuples" ]
I'd like to use list comprehension on the following list; ``` movie_dicts = [{'title':'A Boy and His Dog', 'year':1975, 'rating':6.6}, {'title':'Ran', 'year':1985, 'rating': 8.3}, {'title':'True Grit', 'year':2010, 'rating':8.0}, {'title':'Scanners', 'year':1981, 'rating': 6.7}] ``` u...
``` movie_dicts = [ {'title':'A Boy and His Dog', 'year':1975, 'rating':6.6}, {'title':'Ran', 'year':1985, 'rating': 8.3}, {'title':'True Grit', 'year':2010, 'rating':8.0}, {'title':'Scanners', 'year':1981, 'rating': 6.7} ] title_year = [(i['title'],i['year']) for i in movie_dicts] ``` gives ``` [('A...
python: force non-relative import?
5,372,590
10
2011-03-21T00:16:00Z
5,372,602
18
2011-03-21T00:19:09Z
[ "python", "module", "path", "import", "importerror" ]
I wanted to make a module called `utils/django.py` in my project. On the top I have the line: ``` from django.db import models ``` However, it tries to import from itself, and that causes an error. I know I can force a relative import with a prepended `.`: ``` from .django.db import models ``` is there any way to f...
No. You need to explicitly enable [absolute imports](http://www.python.org/dev/peps/pep-0328/). ``` from __future__ import absolute_import ```
Getting command line arguments as tuples in python
5,372,697
4
2011-03-21T00:36:55Z
5,440,418
7
2011-03-26T05:07:37Z
[ "python", "command-line-arguments", "optparse" ]
Here is an example of how I would like to call my script: ``` python script.py -f file1.txt "string1" "string2" -f file2.txt "string3" "string4" ``` Every file that goes as input will have 2 strings associated with that file. There can be any number of files. To simplify, I am trying to get a print like this: ``` (...
I think you want to use the `action=append` argument of the `add_argument` method ``` import argparse parser= argparse.ArgumentParser() parser.add_argument ('-f', '--file', nargs=3, action='append') files = parser.parse_args('-f file1 string1 string2 -f file2 string3 string4 -f file3 string5 string6'.split()).file ...
Multiple positional arguments with Python and argparse
5,373,474
11
2011-03-21T03:17:12Z
5,373,550
11
2011-03-21T03:32:34Z
[ "python", "argparse" ]
I'm trying to use argparse to parse the command line arguments for a program I'm working on. Essentially, I need to support multiple positional arguments spread within the optional arguments, but cannot get argparse to work in this situation. In the actual program, I'm using a custom action (I need to store a snapshot ...
You can't interleave the switches (i.e. `-a` and `-b`) with the positional arguments (i.e. fileone, filetwo and filethree) in this way. The switches must appear before or after the positional arguments, not in-between. Also, in order to have multiple positional arguments, you need to specify the `nargs` parameter to `...
Multiple positional arguments with Python and argparse
5,373,474
11
2011-03-21T03:17:12Z
5,374,229
8
2011-03-21T05:42:21Z
[ "python", "argparse" ]
I'm trying to use argparse to parse the command line arguments for a program I'm working on. Essentially, I need to support multiple positional arguments spread within the optional arguments, but cannot get argparse to work in this situation. In the actual program, I'm using a custom action (I need to store a snapshot ...
srgerg was right about the definition of positional arguments. In order to get the result you want, You have to accept them as optional arguments, and modify the resulted namespace according to your need. You can use a custom action: ``` class MyAction(argparse.Action): def __call__(self, parser, namespace, value...
Changing the Django data type in models without droping the table
5,373,906
4
2011-03-21T04:46:35Z
5,375,191
18
2011-03-21T08:11:50Z
[ "python", "mysql", "django", "postgresql", "django-models" ]
I have created a Django application. Now i wanted to change the field type for 1 of my db field in models. Since there are some records already in the database with the present type, i guess its not possible to change the type by simply changing it in models.py. By googling i came to know that it can be changed without...
The app you need is [South](http://south.aeracode.org/) Here are the steps (refer to the doc for more details) : ``` ./manage.py convert_to_south yourapp ``` this will create a migration folder and fake a first migration Then add a `new_dateOfJoin` DateField in your models.py : ``` ./manage.py migrate yourapp ```...