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
How do I copy a directory to a remote machine using Fabric?
5,314,711
63
2011-03-15T16:23:02Z
5,314,770
79
2011-03-15T16:28:08Z
[ "python", "fabric" ]
I have a directory on my local machine that I would like to copy to a remote machine (and rename it) using Fabric. I know I can copy file using `put()`, but what about a directory. I know it's easy enough using **scp**, but I would prefer to do it from within my `fabfile.py` if possible.
You can use `put` for that as well (at least in 1.0.0): > `local_path` may be a relative or absolute local file or **directory path**, and may contain **shell-style wildcards**, as understood by the Python **glob** module. Tilde expansion (as implemented by os.path.expanduser) is also performed. See: <http://docs.fab...
How do I copy a directory to a remote machine using Fabric?
5,314,711
63
2011-03-15T16:23:02Z
20,006,798
20
2013-11-15T17:14:31Z
[ "python", "fabric" ]
I have a directory on my local machine that I would like to copy to a remote machine (and rename it) using Fabric. I know I can copy file using `put()`, but what about a directory. I know it's easy enough using **scp**, but I would prefer to do it from within my `fabfile.py` if possible.
I would also look at the Project Tools module: fabric.contrib.project [Documentation](http://docs.fabfile.org/en/1.4.0/api/contrib/project.html) This has an upload\_project function which takes a source and target directory. Even better, there is an rsync\_project function that uses rsync. This is nice because it only...
Functional append/extend
5,314,820
6
2011-03-15T16:32:07Z
5,314,925
9
2011-03-15T16:39:38Z
[ "python" ]
The methods `append` and `extend` in Python are not functional by nature, they modify the callee and return `None`. Is there an alternative way to do what these methods do and get a new list as a returned value? Consider this example: ``` def myfun(first, *args): for elem in [first].extend(args): print elem ``...
``` >>> def append(lst, elem): ... return lst + [elem] ... >>> append([1, 2, 3], 4) [1, 2, 3, 4] >>> def extend(lst1, lst2): ... return lst1 + lst2 ... >>> extend([1, 2], [3, 4]) [1, 2, 3, 4] ``` Is that what you wanted? You may also define your own type, which returns the list itself on these operations, in ...
Quick overview OOP php to python?
5,315,078
3
2011-03-15T16:51:15Z
5,315,178
8
2011-03-15T16:58:24Z
[ "python" ]
I am from PHP and quick learn OOP Python base PHP 's knowledge for example I have a class ``` <?php class Cat{ private $name; private $age; private $color; public function getName() { return $this->name; } public function setName($value) { $this->name = $value; } ...
``` class Cat(object): def __init__(self, name, age, color): self.name = name self.age = age self.color = color ``` No, I'm not joking. 1. Cut that getter/setter stuff, we have properties for a reason. 2. If you're going to have an attribute, you better have it all the time (i.e. from crea...
How do I get the file / key size in boto S3?
5,315,603
24
2011-03-15T17:29:53Z
5,498,841
50
2011-03-31T11:07:14Z
[ "python", "amazon-s3", "boto" ]
There must be an easy way to get the file size (key size) without pulling over a whole file. I can see it in the Properties of the AWS S3 browser. And I think I can get it off the "Content-length" header of a "HEAD" request. But I'm not connecting the dots about how to do this with boto. Extra kudos if you post a link ...
This would work: ``` bk = conn.get_bucket('my_bucket_name') key = bk.lookup('my_key_name') print key.size ``` The lookup method simply does a HEAD request on the bucket for the keyname so it will return all of the headers (including content-length) for the key but will not transfer any of the actual content of the ke...
What's the difference between /usr/local/lib/python2.6 and /usr/lib/python2.6?
5,315,714
5
2011-03-15T17:37:43Z
5,315,734
9
2011-03-15T17:39:34Z
[ "python", "ubuntu" ]
I'm using Ubuntu and noticed these two directories: ``` /usr/local/lib/python2.6/dist-packages /usr/lib/python2.6/dist-packages ``` Which one should be used for installing Python packages? Thanks.
Ubuntu packages in `.deb` format should use ``` /usr/lib/python2.6/dist-packages ``` Files you install outside the package management, i.e. files `dpkg` is unaware of, should go into ``` /usr/local/lib/python2.6/dist-packages ``` Se also the [file system hierarchy standard](http://manpages.ubuntu.com/manpages/gutsy...
What is the best way of hide a password?
5,315,829
11
2011-03-15T17:48:39Z
5,315,927
9
2011-03-15T17:57:03Z
[ "python", "passwords" ]
I have a Python script that is connecting to the database. To that, obviously, I need the password. I need to hide it somewhere. My problem is that this code is stored in a folder that everybody who has access to the server can look. So, if I write this password encrypted in a file, in the code will appear the key to ...
You're using a scripting language and accessing a database directly with a password. No matter what you do, at some level that password is going to be easily accessible. Obscuring it doesn't really buy you much. You have to rely on the machine's security and permissions, and perhaps the database (restricting access fr...
Converting dot to png in python
5,316,206
5
2011-03-15T18:20:50Z
5,316,267
9
2011-03-15T18:25:40Z
[ "python" ]
I have a dot file generated from my code and want to render it in my output. For this i have seen on the net that the command is something like this on `cmd` ``` dot -Tpng InputFile.dot -o OutputFile.png for Graphviz ``` But my problem is that I want to use this inbuilt in my python program. How can i do so ?? I l...
[pydot](http://code.google.com/p/pydot/) needs the GraphViz binaries to be installed anyway, so if you've already generated your dot file you might as well just invoke dot directly yourself. For example: ``` from subprocess import check_call check_call(['dot','-Tpng','InputFile.dot','-o','OutputFile.png']) ```
Converting dot to png in python
5,316,206
5
2011-03-15T18:20:50Z
5,316,307
12
2011-03-15T18:29:37Z
[ "python" ]
I have a dot file generated from my code and want to render it in my output. For this i have seen on the net that the command is something like this on `cmd` ``` dot -Tpng InputFile.dot -o OutputFile.png for Graphviz ``` But my problem is that I want to use this inbuilt in my python program. How can i do so ?? I l...
Load the file with `pydot.graph_from_dot_file` to get a `pydot.Dot` class instance. Then write it to a PNG file with the `write_png` method. ``` import pydot (graph,) = pydot.graph_from_dot_file('somefile.dot') graph.write_png('somefile.png') ```
Python: run one function until another function finishes
5,316,284
5
2011-03-15T18:26:56Z
5,316,315
7
2011-03-15T18:30:38Z
[ "python", "function", "background" ]
I have two functions, `draw_ascii_spinner` and `findCluster(companyid)`. I would like to: 1. Run `findCluster(companyid)` in the backround and while its processing.... 2. Run `draw_ascii_spinner` until `findCluster(companyid)` finishes How do I begin to try to solve for this (Python 2.7)?
You can use [multiprocessing](http://docs.python.org/library/multiprocessing.html). Or, if `findCluster(companyid)` has sensible stopping points, you can turn it into a generator along with `draw_ascii_spinner`, to do something like this: ``` for tick in findCluster(companyid): ascii_spinner.next() ```
Python: How to convert a list of dictionaries' values into int/float from string?
5,316,720
16
2011-03-15T19:10:52Z
5,316,753
12
2011-03-15T19:13:17Z
[ "python", "string", "list", "dictionary", "int" ]
I have a list of dictionaries as follows: ``` list = [ { 'a':'1' , 'b':'2' , 'c':'3' }, { 'd':'4' , 'e':'5' , 'f':'6' } ] ``` How do I convert the values of each dictionary inside the list to int/float? So it becomes: ``` list = [ { 'a':1 , 'b':2 , 'c':3 }, { 'd':4 , 'e':5 , 'f':6 } ] ``` Thanks.
``` for sub in the_list: for key in sub: sub[key] = int(sub[key]) ``` Gives it a casting as an int instead of as a string.
Python: How to convert a list of dictionaries' values into int/float from string?
5,316,720
16
2011-03-15T19:10:52Z
5,317,657
21
2011-03-15T20:29:18Z
[ "python", "string", "list", "dictionary", "int" ]
I have a list of dictionaries as follows: ``` list = [ { 'a':'1' , 'b':'2' , 'c':'3' }, { 'd':'4' , 'e':'5' , 'f':'6' } ] ``` How do I convert the values of each dictionary inside the list to int/float? So it becomes: ``` list = [ { 'a':1 , 'b':2 , 'c':3 }, { 'd':4 , 'e':5 , 'f':6 } ] ``` Thanks.
Gotta love list comprehensions. ``` [dict([a, int(x)] for a, x in b.iteritems()) for b in list] ```
Django-piston: How can I get app_label + model_name?
5,317,050
6
2011-03-15T19:40:38Z
5,318,273
11
2011-03-15T21:25:43Z
[ "python", "django", "django-piston" ]
Before I was just using the build-in django serializers and it added a model field. ``` { pk: 1 model: "zoo.cat" } ``` How can I get the same model field using django-piston? I tried fields = ('id', 'model') but that didn't work.
Added this to my model: ``` def model(self): return "{0}.{1}".format(self._meta.app_label, self._meta.object_name).lower() ``` And this to my BaseHandler: ``` fields = ('id', 'model') ``` Seems to work. If anybody has other solutions feel free to post them.
Guidelines to write fast code for PyPy's JIT
5,318,157
12
2011-03-15T21:14:04Z
5,318,386
11
2011-03-15T21:37:35Z
[ "python", "compilation", "jit", "pypy", "optimization" ]
PyPy's JIT can make Python code execute much faster than CPython. Are there a set of guidelines for writing code that can be optimised better by the JIT compiler? For example, Cython can compile some static code into C++, and it has [guidelines](http://docs.cython.org/src/quickstart/cythonize.html) to write efficient c...
[PyPy wiki's at BitBucket](https://bitbucket.org/pypy/pypy/wiki/Home) has a section on [JIT Friendliness](https://bitbucket.org/pypy/pypy/wiki/JitFriendliness). Some blog posts offer [further advice](http://blog.vrplumber.com/index.php?/archives/2488-PyPy-hits-3x-speed-or-112th,-or-2.5x-depending-on-the-sign-post.html)...
Is it possible to modify PYTHONPATH at runtime?
5,318,441
9
2011-03-15T21:43:11Z
8,187,612
7
2011-11-18T18:55:18Z
[ "c++", "python", "boost-python", "python-c-api", "python-embedding" ]
I have a C++ application dynamically linked to the Python interpreter. I want to be able to import python modules from a particular directory. I want to modify the PYTHONPATH for my process so that sys.path will include the paths that I added to the PYTHONPATH. That seems to be the way it works according to this docume...
I found cross-platform solution. Before invoke any other python code just execute following python lines: ``` import sys sys.path.append("C:\\source\\\\modules") ```
Using Python to extract dictionary keys within a list
5,318,747
8
2011-03-15T22:14:23Z
5,318,852
18
2011-03-15T22:28:41Z
[ "python", "json", "list", "dictionary", "twitter" ]
I received a list when inputting the following URL - <http://api.twitter.com/1/trends/44418.json> The list contains multiple dictionaries, and I'm a bit confused with the list structure. I'm trying to obtain the values associated with the 'name' key. For example: "name":"#throwagrenade" "name":"Rebecca Black" "name"...
The first thing I would do when working with a big lump of json, is try to get it into a more readable format. [This online json formatting tool](http://jsonformatter.curiousconcept.com) should do the job. Here's some code that will get all the trend names: ``` import urllib2 import json url = 'http://api.twitter.co...
Constructor B is not called in an A -> B -> C inheritance chain
5,318,849
2
2011-03-15T22:28:19Z
5,318,933
9
2011-03-15T22:38:40Z
[ "python", "oop", "inheritance", "constructor" ]
I have the following inheritance chain: ``` class Foo(object): def __init__(self): print 'Foo' class Bar(Foo): def __init__(self): print 'Bar' super(Foo, self).__init__() class Baz(Bar): def __init__(self): print 'Baz' super(Bar, self).__init__() ``` When instanti...
The call to `super()` takes the current class as the first argument, not the super class (`super()` works that out for itself). In this case, the following should fix it... note the change to both `super()` calls: ``` class Foo(object): def __init__(self): print 'Foo' class Bar(Foo): def __init__(self...
Python Multiprocessing.Pool lazy iteration
5,318,936
39
2011-03-15T22:39:07Z
5,326,207
27
2011-03-16T13:43:47Z
[ "python", "multiprocessing" ]
I'm wondering about the way that python's Multiprocessing.Pool class works with map, imap, and map\_async. My particular problem is that I want to map on an iterator that creates memory-heavy objects, and don't want all these objects to be generated into memory at the same time. I wanted to see if the various map() fun...
Let's look at the end of the program first. The multiprocessing module uses `atexit` to call `multiprocessing.util._exit_function` when your program ends. If you remove `g2.next()`, your program ends quickly. The `_exit_function` eventually calls `Pool._terminate_pool`. The main thread changes the state of `pool._ta...
Mercurial CGI (hgweb.cgi) fails
5,318,970
10
2011-03-15T22:43:47Z
5,662,125
18
2011-04-14T10:52:40Z
[ "python", "mercurial", "windows-server-2008" ]
I have Mercurial 1.8.1, Python 2.6.6 installed on Win 2k8 R2 running on a vm. I have tried installing from msi, source and using tortisehg. Command-line Hg works fine but I get the same error when running the hgweb.cgi: ``` Traceback (most recent call last): File ".\hgweb.cgi", line 17, in application = hgweb(c...
I had the same error using following system configuration * Python-2.6.6 installed as msi * mercurial-1.8.2-x86 installed as msi * IIS7 I solved this problem simply: 1. Python has been installed early 2. Uninstall Mercurial msi package 3. Download and install "Mercurial-1.8.2 (32-bit py2.6)" installer from [mercuria...
Structuring Sphinx documentation
5,319,210
9
2011-03-15T23:19:17Z
5,322,306
11
2011-03-16T07:41:32Z
[ "python", "python-sphinx" ]
I have started documenting a Python project using Sphinx. It is the first time I use it - I am used to tools which work with a JavaDoc-like syntax, and I have some doubts. Since I want the documentation to appear near the code, I make use of the `.. automodule::`, `.. autoclass::` and `.. automethod::` directives. So ...
I found this [autopackage script](https://bitbucket.org/etienned/sphinx-autopackage-script) from a comment [here](http://stackoverflow.com/questions/4616693/automatically-generating-documentation-for-all-python-package-contents/4617804#4617804). It generates the necessary .rst files according to the structure of your p...
How do I have python httplib accept untrusted certs?
5,319,430
5
2011-03-15T23:51:34Z
32,189,376
12
2015-08-24T18:38:14Z
[ "python", "httplib" ]
How do I have python httplib accept untrusted certs? I created a snake oil/self signed cert on my webserver, and my python client fails to connect as I am using a untrusted cert. I'd rather problematically fix this in my client code rather than have it trusted on my system. ``` import httplib def main(): conn =...
Some of my scripts stopped working after updating my computer. Turns out, this was the problem: <https://docs.python.org/2/library/httplib.html#httplib.HTTPSConnection> > Changed in version 2.7.9: context was added. > > This class now performs all the necessary certificate and hostname checks by default. To revert to ...
What is the most efficient way to move/rename a node in NetworkX?
5,319,707
11
2011-03-16T00:33:03Z
5,319,934
7
2011-03-16T01:12:14Z
[ "python", "graph", "networkx" ]
I am using the NetworkX graph library for Python. At some point in my program I would like to "consolidate" my nodeIDs into a sequence of numbers. Here's my naive approach: ``` start = 1 # could be anything for i, n in enumerate(g.nodes()): if i+start == n: continue g.add_node(i+start, attr_dict=g.node...
Would this work? <http://networkx.github.io/documentation/latest/reference/generated/networkx.relabel.convert_node_labels_to_integers.html> ``` import networkx as nx G = nx.Graph() G.add_node(1) G.add_nodes_from('spam') print G.nodes() ``` returns: ``` ['a', 1, 's', 'm', 'p'] ``` now: ``` start = 1 G = nx.convert...
Decode json and Iterate through items in django template
5,319,896
6
2011-03-16T01:05:58Z
5,320,085
11
2011-03-16T01:38:39Z
[ "python", "django", "json", "loops", "simplejson" ]
Hi I am using simplejson to import some json and then decode for use within a django template, this is the decoded json: ``` {u'ServerID': 1, u'Cache': {u'CacheBusted': False, u'FromCache': True}, u'Result': [{u'Url': u'http://listen.grooveshark.com/playlist/Soul_Power/399134', u'Cache': {u'FromCache': True}, u'Playl...
Once you've used Python's `json` or `simplejson` module to `load` the JSON data into Python objects, everything should just work in your template. Before sending things to your template I would pull out the results like so... ``` def foo_view(request): .... decoded_json = json.loads(json_string) return re...
Python - Check If Word Is In A String
5,319,922
64
2011-03-16T01:10:17Z
5,319,942
139
2011-03-16T01:13:09Z
[ "python", "string" ]
I'm working with Python v2, and I'm trying to find out if you can tell if a word is in a string. I have found some information about identifying if the word is in the string - using .find, but is there a way to do an IF statement. I would like to have something like the following: ``` if string.find(word): print ...
What is wrong with: ``` if word in mystring: print 'success' ```
Python - Check If Word Is In A String
5,319,922
64
2011-03-16T01:10:17Z
5,319,943
10
2011-03-16T01:13:14Z
[ "python", "string" ]
I'm working with Python v2, and I'm trying to find out if you can tell if a word is in a string. I have found some information about identifying if the word is in the string - using .find, but is there a way to do an IF statement. I would like to have something like the following: ``` if string.find(word): print ...
find returns an integer representing the index of where the search item was found. If it isn't found, it returns -1. ``` haystack = 'asdf' haystack.find('a') # result: 0 haystack.find('s') # result: 1 haystack.find('g') # result: -1 if haystack.find(needle) >= 0: print 'Needle found.' else: print 'Needle not fou...
Python - Check If Word Is In A String
5,319,922
64
2011-03-16T01:10:17Z
5,320,179
83
2011-03-16T01:52:56Z
[ "python", "string" ]
I'm working with Python v2, and I'm trying to find out if you can tell if a word is in a string. I have found some information about identifying if the word is in the string - using .find, but is there a way to do an IF statement. I would like to have something like the following: ``` if string.find(word): print ...
``` if 'seek' in 'those who seek shall find': print('Success!') ``` but keep in mind that this matches a sequence of characters, not necessarily a whole word - for example, `'word' in 'swordsmith'` is True. If you only want to match whole words, you ought to use regular expressions: ``` import re def findWholeWo...
Python - Check If Word Is In A String
5,319,922
64
2011-03-16T01:10:17Z
11,165,138
8
2012-06-22T22:51:30Z
[ "python", "string" ]
I'm working with Python v2, and I'm trying to find out if you can tell if a word is in a string. I have found some information about identifying if the word is in the string - using .find, but is there a way to do an IF statement. I would like to have something like the following: ``` if string.find(word): print ...
This small function compares all search words in given text. If all search words are found in text, returns length of search, or `False` otherwise. Also supports unicode string search. ``` def find_words(text, search): """Find exact words""" dText = text.split() dSearch = search.split() found_word ...
Matplotlib text dimensions
5,320,205
14
2011-03-16T01:56:03Z
5,333,206
8
2011-03-16T23:50:49Z
[ "python", "matplotlib" ]
Is it possible to determine the dimensions of a matplotlib text object? How can I find the width and height in pixels? Thanks **Edit**: I think I figured out a way to do this. I've included an example below. ``` import matplotlib as plt f = plt.figure() r = f.canvas.get_renderer() t = plt.text(0.5, 0.5, 'test') bb...
I could not find a way to get the text extents as rendered on a plot even after a draw() event. But here's a way to render just the text and get all kinds of geometric information from it: ``` t = matplotlib.textpath.TextPath((0,0), 'hello', size=9, prop='WingDings') bb = t.get_extents() #bb: #Bbox(array([[ 0.75937...
testing if a numpy array is symmetric?
5,320,324
8
2011-03-16T02:16:11Z
5,324,586
13
2011-03-16T11:27:22Z
[ "python", "matrix", "numpy" ]
Is there a better pythonic way of checking if a ndarray is diagonally symmetric in a particular dimension? i.e for all of x ``` (arr[:,:,x].T==arr[:,:,x]).all() ``` I'm sure I'm missing an (duh) answer but its 2:15 here... :) EDIT: to clarify, I'm looking for a more 'elegant' way to do : ``` for x in range(xmax): ...
If I understand you correctly, you want to do the check ``` all((arr[:,:,x].T==arr[:,:,x]).all() for x in range(arr.shape[2])) ``` without the Python loop. Here is how to do it: ``` (arr.transpose(1, 0, 2) == arr).all() ```
testing if a numpy array is symmetric?
5,320,324
8
2011-03-16T02:16:11Z
20,474,059
8
2013-12-09T15:16:59Z
[ "python", "matrix", "numpy" ]
Is there a better pythonic way of checking if a ndarray is diagonally symmetric in a particular dimension? i.e for all of x ``` (arr[:,:,x].T==arr[:,:,x]).all() ``` I'm sure I'm missing an (duh) answer but its 2:15 here... :) EDIT: to clarify, I'm looking for a more 'elegant' way to do : ``` for x in range(xmax): ...
If your array contains floats (especially if they're the result of a computation), use [`allclose`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.allclose.html) ``` np.allclose(arr.transpose(1, 0, 2), arr) ``` If some of your values might be `NaN`, set those to a marker value before the test. ``` arr[np....
re.match() multiple times in the same string with Python
5,320,554
3
2011-03-16T02:57:24Z
5,320,627
7
2011-03-16T03:10:28Z
[ "python", "regex" ]
I have a regular expression to find :ABC:`hello` pattern. This is the code. ``` format =r".*\:(.*)\:\`(.*)\`" patt = re.compile(format, re.I|re.U) m = patt.match(l.rstrip()) if m: ... ``` It works well when the pattern happens once in a line, but with an example ":tagbox:`Verilog` :tagbox:`Multiply` :tagbox:`VHDL...
Yeah, dcrosta suggested looking at the `re` module docs, which is probably a good idea, but I'm betting you actually wanted the `finditer` function. Try this: ``` format = r"\:(.*)\:\`(.*)\`" patt = re.compile(format, re.I|re.U) for m in patt.finditer(l.rstrip()): tag, value = m.groups() .... ``` Your current...
In List of Dicts, find min() value of a common Dict field
5,320,871
23
2011-03-16T03:56:39Z
5,320,893
19
2011-03-16T04:00:59Z
[ "python", "list", "dictionary", "max", "min" ]
I have a list of dicts like so: ``` [{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}] ``` I want to find the min() and max() prices. Now, I can sort this easily enough using a key with a lambda expression (as found in another SO article), so if there is no other way I'm not stuck. However, fr...
I think the most direct (and most Pythonic) expression would be something like: ``` min_price = min(item['price'] for item in items) ``` This avoids the overhead of sorting the list -- and, by using a generator expression, instead of a list comprehension -- actually avoids creating any lists, as well. Efficient, dire...
In List of Dicts, find min() value of a common Dict field
5,320,871
23
2011-03-16T03:56:39Z
5,320,895
20
2011-03-16T04:01:25Z
[ "python", "list", "dictionary", "max", "min" ]
I have a list of dicts like so: ``` [{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}] ``` I want to find the min() and max() prices. Now, I can sort this easily enough using a key with a lambda expression (as found in another SO article), so if there is no other way I'm not stuck. However, fr...
There are several options. Here is a straight-forward one: ``` seq = [x['the_key'] for x in dict_list] min(seq) max(seq) ``` [Edit] If you only wanted to iterate through the list once, you could try this (assuming the values could be represented as `int`s): ``` import sys lo,hi = sys.maxint,-sys.maxint-1 for x in ...
In List of Dicts, find min() value of a common Dict field
5,320,871
23
2011-03-16T03:56:39Z
5,326,622
52
2011-03-16T14:20:56Z
[ "python", "list", "dictionary", "max", "min" ]
I have a list of dicts like so: ``` [{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}] ``` I want to find the min() and max() prices. Now, I can sort this easily enough using a key with a lambda expression (as found in another SO article), so if there is no other way I'm not stuck. However, fr...
``` lst = [{'price': 99, 'barcode': '2342355'}, {'price': 88, 'barcode': '2345566'}] maxPricedItem = max(lst, key=lambda x:x['price']) minPricedItem = min(lst, key=lambda x:x['price']) ``` This tells you not just what the max price is but also which item is most expensive.
Speed comparisons between Chameleon and Jinja2
5,321,789
10
2011-03-16T06:28:19Z
5,324,691
17
2011-03-16T11:39:24Z
[ "python", "performance", "jinja2", "pyramid" ]
Has anyone here done any benchmarking of Chameleon versus Jinja2, in respect to performance? I'm more used to the Jinja syntax, since I come from Django, but as Pyramid suggests to use Chameleon, I'm thinking if it would be nice to give it a try - despite having an awkward syntax, IMO.
Template engines are rarely the cause of performance problems, even if chameleon is slightly faster than Jinja2 I doubt the effort of learning a new template language etc. is worth it. Optimization of database queries and caching will probably result in more performance than you could gain by switching the template en...
How to erase everything from the tkinter text widget?
5,322,027
9
2011-03-16T07:04:58Z
5,324,483
7
2011-03-16T11:14:35Z
[ "python", "tkinter" ]
Im working on a GUI for some chat programme. For user's input I have Text() widget, messages are sent via "Return" and after that I clean the Text(). But as hard as I tried I cant remove the last "\n" which Return button creates. Here is my code for this part: ``` def Send(Event): MSG_to_send=Tex2.get("1.0",END) ...
Most likely your problem is that your binding is happening *before* the newline is inserted. You delete everything, but then the newline is inserted. This is due to the nature of how the text widget works -- widget bindings happen before class bindings, and class bindings are where user input is actually inserted into ...
how to detect quickly if a string is zlib compressed?
5,322,860
7
2011-03-16T08:48:57Z
5,322,885
9
2011-03-16T08:53:02Z
[ "python", "zlib" ]
What's the quickest way in python to determine if a string was compressed by zlib. I am using this currently. ``` def iscompressed(data): result = True try: s =zlib.decompress(data) except: result = False return result ``` I am sure there is a more elegant way.
You can check the first 2 Byte for the header information - it is, however, not 100% safe. See <http://www.faqs.org/rfcs/rfc1950.html>, chapter 2.2
Condensed matrix function to find pairs
5,323,818
6
2011-03-16T10:16:57Z
14,839,010
13
2013-02-12T18:13:04Z
[ "python", "algorithm", "math", "statistics", "scipy" ]
For a set of observations: ``` [a1,a2,a3,a4,a5] ``` their pairwise distances ``` d=[[0,a12,a13,a14,a15] [a21,0,a23,a24,a25] [a31,a32,0,a34,a35] [a41,a42,a43,0,a45] [a51,a52,a53,a54,0]] ``` Are given in a condensed matrix form (upper triangular of the above, calculated from `scipy.spatial.distance.pdist`...
The formula for an index of the condensed matrix is ``` index = d*(d-1)/2 - (d-i)*(d-i-1)/2 + j - i - 1 ``` Where `i` is the row index, `j` is the column index, and `d` is the row length of the original (d X d) upper triangular matrix. Consider the case when the index refers to the leftmost, non-zero entry of some r...
WindowsError: [Error 2] The system cannot find the file specified
5,324,107
10
2011-03-16T10:39:46Z
5,325,343
7
2011-03-16T12:34:47Z
[ "python", "renaming" ]
I am having a problem with this code. I am trying to rename all of the filenames within a folder so that they no longer have `+'s` in them! This has worked many times before but suddenly I get the error: `WindowsError: [Error 2] The system cannot find the file specified at line 26` Line 26 is the last line in the cod...
I suspect that you may be having issues with subdirectories. If you have a directory with files "`a`", "`b`" and subdirectory "`dir`" with files "`sub+1`" and "`sub+2`", the call to `os.walk()` will yield the following values: ``` (('.',), ('dir',), ('a', 'b')) (('dir',), (,), ('sub+1', 'sub+2')) ``` When you proces...
Task queue works from view, but UnknownQueueError when run from unit tests
5,324,515
13
2011-03-16T11:18:21Z
5,417,998
10
2011-03-24T10:51:22Z
[ "python", "unit-testing", "google-app-engine" ]
**Updated**: Originally I didn't realize this only fails when run from unit tests. I have a working task queue in AppEngine with Python. - When calling a view manually, the task is added to the queue and runs - When called from unit tests, adding the task to the queue fails with an **UnknownQueueError**. When reading...
Edit: working answer. My problem was adding the stub fix in an individual unit test: moving it to setUp() fixed things. In tests.py ``` from google.appengine.api import apiproxy_stub_map import os class BlahTest(MyAppTestCase) def setUp(self): '''Ensure dev appserver task queue knows where to find queue....
How to merge a transparent png image with another image using PIL
5,324,647
57
2011-03-16T11:33:59Z
5,324,782
115
2011-03-16T11:48:21Z
[ "python", "image", "image-processing", "python-imaging-library" ]
I have a transparent png image "foo.png" and I've opened another image with ``` im = Image.open("foo2.png"); ``` now what i need is to merge foo.png with foo2.png. ( foo.png contains some text and I want to print that text on foo2.png )
``` import Image background = Image.open("test1.png") foreground = Image.open("test2.png") background.paste(foreground, (0, 0), foreground) background.show() ``` First parameter to `.paste()` is the image to paste. Second are coordinates, and the secret sauce is the third parameter. It indicates a **mask** that will...
How to merge a transparent png image with another image using PIL
5,324,647
57
2011-03-16T11:33:59Z
15,919,897
33
2013-04-10T07:45:28Z
[ "python", "image", "image-processing", "python-imaging-library" ]
I have a transparent png image "foo.png" and I've opened another image with ``` im = Image.open("foo2.png"); ``` now what i need is to merge foo.png with foo2.png. ( foo.png contains some text and I want to print that text on foo2.png )
`Image.paste` does not work as expected when the background image also contains transparency. You need to use real [Alpha Compositing](http://en.wikipedia.org/wiki/Alpha_compositing). Pillow 2.0 contains an `alpha_composite` function that does this. ``` background = Image.open("test1.png") foreground = Image.open("te...
python Returning data from a threaded def
5,324,718
5
2011-03-16T11:42:41Z
5,324,739
9
2011-03-16T11:45:11Z
[ "python", "multithreading" ]
I have a bit of code that gets the title of a .MP3 file ``` def getTitle(fileName): print "getTitle" audio = MP3(fileName) try: sTitle = str(audio["TIT2"]) except KeyError: sTitle = os.path.basename(fileName) sTitle = replace_all(sTitle) #remove special chars return sTitle ``...
One way to do it is to use a wrapper storing the result: ``` def wrapper(func, args, res): res.append(func(*args)) res = [] t = threading.Thread( target=wrapper, args=(getTitle, ("SomeSong.mp3",), res)) t.start() t.join() print res[0] ```
python Returning data from a threaded def
5,324,718
5
2011-03-16T11:42:41Z
5,324,893
12
2011-03-16T11:58:13Z
[ "python", "multithreading" ]
I have a bit of code that gets the title of a .MP3 file ``` def getTitle(fileName): print "getTitle" audio = MP3(fileName) try: sTitle = str(audio["TIT2"]) except KeyError: sTitle = os.path.basename(fileName) sTitle = replace_all(sTitle) #remove special chars return sTitle ``...
I would make a new object that extends thread so that you can get anything you want out of it at any time. ``` from threading import Thread class GetTitleThread(Thread): def __init__(self, fileName): self.sTitle = None self.fileName = fileName super(GetTitleThread, self).__init__(...
How to round each item in a list of floats to 2 decmial places
5,326,112
10
2011-03-16T13:37:06Z
5,326,139
23
2011-03-16T13:39:07Z
[ "python" ]
I have a list which consists of float values but they're too detailed to proceed. I know we can shorten them by using ("%.f" % variable) operator like: ``` result = [359.70000000000005] result = "%.2f" % result result = [359.70] ``` My question is how can we turn a list of values without using an iterator. ``` list ...
`"%.2f"` does not return a *clean* float. It returns a **string** representing this float with two decimals. ``` myList = [0.30000000000000004, 0.5, 0.20000000000000001] myFormattedList = [ '%.2f' % elem for elem in myList ] ``` returns: ``` ['0.30', '0.50', '0.20'] ``` Also, don't call your variable `list`. This i...
Understanding the "tail -f in python"
5,326,405
3
2011-03-16T14:01:46Z
5,326,456
8
2011-03-16T14:06:17Z
[ "python", "file-io", "file", "tail" ]
I have created a very simple python script: ``` def read_then_follow(file): for line in file: yield line while True: line = file.readline() if not line: time.sleep(1.0) continue yield line for line in read_then_follow("some_file.txt"): print line ``` Th...
(I'm assuming you are on some Unix-like operating system.) Saving in vim will actually create a *new* file with the same name on the disk. The file handle held by your script still points to the *old* file, which does not have a directory entry anymore. If your script terminates, the reference counter of the old file ...
Python introspection - how to check current module / line of call from within function
5,326,539
6
2011-03-16T14:13:05Z
5,326,621
13
2011-03-16T14:20:56Z
[ "python", "introspection" ]
I have a function: ``` # utils.py def hello(name='World'): # Detect where I'm being called from. print('Hi, %s. You called this from %s at line # %d.' % (name, mod, lineno)) # ``mod`` and ``lineno`` on previous line would have been set in real use. ``` I import that function and run it elsewhere ``` # ot...
Access the enclosing frame of `inspect.currentframe()`: ``` import inspect def hello(name='World'): f = inspect.currentframe().f_back mod = f.f_code.co_filename lineno = f.f_lineno print('Hi, %s. You called this from %s at line # %d.' % (name, mod, lineno)) ```
Django: Force a field to be unique for all model objects with the same foreign key
5,326,727
5
2011-03-16T14:29:26Z
5,326,770
9
2011-03-16T14:32:28Z
[ "python", "django", "django-models" ]
Suppose I have the following Models defined in django (not tested): ``` class CarMaker(models.Model): name = models.CharField("Name of car maker", max_length=40) class Car(models.Model): car_id = models.IntegerField("ID for this particular car") maker = models.ForeignKey("Maker o...
You can use the model options `unique_together` to create this type of constraint. See the Django docs: <http://docs.djangoproject.com/en/1.2/ref/models/options/#unique-together> ``` class Car(models.Model): car_id = models.IntegerField("ID for this particular car") maker = models.ForeignKey("Maker of this car...
Using an SSH keyfile with Fabric
5,327,465
70
2011-03-16T15:20:01Z
5,327,496
118
2011-03-16T15:22:29Z
[ "python", "fabric" ]
How do you configure fabric to connect to remote hosts using SSH keyfiles (for example, Amazon EC2 instances)?
Finding a simple fabfile with a working example of SSH keyfile usage isn't easy for some reason. I wrote a [blog post](http://blog.y3xz.com/post/3898560556/fabric-ssh-with-keyfile) about it ([with a matching gist](https://gist.github.com/872506)). Basically, the usage goes something like this: ``` from fabric.api imp...
Using an SSH keyfile with Fabric
5,327,465
70
2011-03-16T15:20:01Z
5,333,091
52
2011-03-16T23:35:24Z
[ "python", "fabric" ]
How do you configure fabric to connect to remote hosts using SSH keyfiles (for example, Amazon EC2 instances)?
Also worth mentioning here that you can use the command line args for this: ``` fab command -i /path/to/key.pem [-H [user@]host[:port]] ```
Using an SSH keyfile with Fabric
5,327,465
70
2011-03-16T15:20:01Z
9,887,656
48
2012-03-27T10:21:58Z
[ "python", "fabric" ]
How do you configure fabric to connect to remote hosts using SSH keyfiles (for example, Amazon EC2 instances)?
Another cool feature available as of Fabric 1.4 - [Fabric now supports SSH configs](http://docs.fabfile.org/en/1.4.0/usage/execution.html#ssh-config). If you already have all the SSH connection parameters in your `~/.ssh/config` file, Fabric will natively support it, all you need to do is add: ``` env.use_ssh_config ...
Using an SSH keyfile with Fabric
5,327,465
70
2011-03-16T15:20:01Z
21,846,493
7
2014-02-18T07:04:21Z
[ "python", "fabric" ]
How do you configure fabric to connect to remote hosts using SSH keyfiles (for example, Amazon EC2 instances)?
For me, the following didn't work: ``` env.user=["ubuntu"] env.key_filename=['keyfile.pem'] env.hosts=["xxx-xx-xxx-xxx.ap-southeast-1.compute.amazonaws.com"] ``` or ``` fab command -i /path/to/key.pem [-H [user@]host[:port]] ``` However, the following did: ``` env.key_filename=['keyfile.pem'] env.hosts=["ubuntu@xx...
Image aspect ratio using Reportlab in Python
5,327,670
6
2011-03-16T15:34:02Z
5,328,770
22
2011-03-16T16:53:38Z
[ "python", "image", "pdf", "reportlab" ]
I want to insert an image inside a frame. I found two ways to do this: 1. drawImage(self, image, x, y, width=None, height=None, mask=None, preserveAspectRatio=False, anchor='c') 2. Image(filename, width=None, height=None) My question is: how can I add an image in a frame while preserving its aspect ratio? ``` from r...
You can use the original image's size to calculate its aspect ratio, then use that to scale your target width, height. You can wrap this up in a function to make it reusable: ``` from reportlab.lib import utils def get_image(path, width=1*cm): img = utils.ImageReader(path) iw, ih = img.getSize() aspect = ...
How could I get the user name from a process id in python on Linux?
5,327,707
2
2011-03-16T15:37:03Z
5,327,812
9
2011-03-16T15:46:05Z
[ "python", "linux", "process" ]
I want to get the user name from a process id in python on Linux, so I can show it like this: ``` name user name pid Chrome wong2 123 ```
You can read the uid(s) from `/proc/`*pid*`/status`. They're in a line that starts with `Uid:`. From the uid, you can derive the username with [`pwd.getpwuid(pid).pw_name`](http://docs.python.org/library/pwd.html). ``` UID = 1 EUID = 2 def owner(pid): '''Return username of UID of process pid''' for ln in o...
For python is there a way to print variables scope from context where exception happens?
5,327,919
10
2011-03-16T15:52:34Z
5,328,124
7
2011-03-16T16:06:30Z
[ "python", "exception" ]
Is there a way to print variables scope from context where exception happens? For example: ``` def f(): a = 1 b = 2 1/0 try: f() except: pass # here I want to print something like "{'a': 1, 'b': 2}" ```
You have to first extract traceback, in your example something like this would print it: ``` except: print sys.exc_traceback.tb_next.tb_frame.f_locals ``` I'm not sure about the tb\_next, I would guess you have to go through the complete traceback, so something like this (untested): ``` except: tb_last = sys...
For python is there a way to print variables scope from context where exception happens?
5,327,919
10
2011-03-16T15:52:34Z
5,328,139
12
2011-03-16T16:07:36Z
[ "python", "exception" ]
Is there a way to print variables scope from context where exception happens? For example: ``` def f(): a = 1 b = 2 1/0 try: f() except: pass # here I want to print something like "{'a': 1, 'b': 2}" ```
You can use the function `sys.exc_info()` to get the last exception that occurred in the current thread in you except clause. This will be a tuple of exception type, exception instance and traceback. The traceback is a linked list of frame. This is what is used to print the backtrace by the interpreter. It does contain...
how to restore dropped table with django-south?
5,328,053
20
2011-03-16T16:01:03Z
7,199,228
26
2011-08-26T01:46:52Z
[ "python", "database", "django", "django-south", "django-syncdb" ]
I wanted to clear out a table in my DB, so I dropped the table. Normally I would do `manage.py syncdb` to re-create it. However, the answer [here](http://stackoverflow.com/questions/1590944/currently-using-django-evolution-is-south-better-and-worth-switching) says not to use `syncdb` anymore. So, what do I do instead?
Had the identical problem. Not sure this works in all circumstances, but here's what I did: 1. comment out "south" from INSTALLED\_APPS 2. run manage.py syncdb 3. uncomment "south" in INSTALLED\_APPS 4. run manage.py migrate Voila! Your mileage may vary....
how to restore dropped table with django-south?
5,328,053
20
2011-03-16T16:01:03Z
13,532,570
38
2012-11-23T16:12:39Z
[ "python", "database", "django", "django-south", "django-syncdb" ]
I wanted to clear out a table in my DB, so I dropped the table. Normally I would do `manage.py syncdb` to re-create it. However, the answer [here](http://stackoverflow.com/questions/1590944/currently-using-django-evolution-is-south-better-and-worth-switching) says not to use `syncdb` anymore. So, what do I do instead?
It's a pretty late response but for people who will run into the same issue (like I did). Normally to drop the db\_tables for the app that is managed by south you should use: ``` python manage.py migrate appname zero ``` But if you dropped them manually in the db let south know about it ``` python manage.py migrate...
LLVM, Parrot, JVM, PyPy + python
5,328,295
15
2011-03-16T16:20:01Z
5,331,313
7
2011-03-16T20:25:34Z
[ "python", "jvm", "llvm", "pypy", "parrot" ]
What is the problem in developing some languages, for example python for some optimized techniques with some of LLVM / Parrot. PyPy, LLVM, Parrot are the main technologies for common platform development. I see this like: * **PyPy** - framework to build VM with build in optimized VM for python So it quite gen...
The main reason? Because VM design is *not* a settled technology, and having a variety of VMs with different goals and objectives allows a variety of mechnisms to be tried in parallel rather than all having to be tried in series. The JVM, CLR, PyPy, Parrot, LLVM and the rest all target different kinds of problems in d...
LLVM, Parrot, JVM, PyPy + python
5,328,295
15
2011-03-16T16:20:01Z
5,331,682
11
2011-03-16T20:59:19Z
[ "python", "jvm", "llvm", "pypy", "parrot" ]
What is the problem in developing some languages, for example python for some optimized techniques with some of LLVM / Parrot. PyPy, LLVM, Parrot are the main technologies for common platform development. I see this like: * **PyPy** - framework to build VM with build in optimized VM for python So it quite gen...
What are you trying to implement? Your question is very confusingly worded (I realize English is likely not your first language). LLVM and PyPy are both mature, useful projects, but really don't overlap much at this point. (At one point, PyPy could generate LLVM bytecode—which was statically compiled to an interpret...
LLVM, Parrot, JVM, PyPy + python
5,328,295
15
2011-03-16T16:20:01Z
5,863,042
25
2011-05-02T22:11:58Z
[ "python", "jvm", "llvm", "pypy", "parrot" ]
What is the problem in developing some languages, for example python for some optimized techniques with some of LLVM / Parrot. PyPy, LLVM, Parrot are the main technologies for common platform development. I see this like: * **PyPy** - framework to build VM with build in optimized VM for python So it quite gen...
That not stuff anybody can possible answer in a stackoverflow questions but i give it a minmal shot. First what problems do the 3 projects solve? 1. pypy allows you to implement an interpreter in a high level language and you get a generated jit for free. The good thing about this is that you don't have a dependence ...
Saving many Django objects with one big INSERT statement
5,328,301
3
2011-03-16T16:20:18Z
5,328,535
7
2011-03-16T16:37:16Z
[ "python", "django" ]
Imagine you have the following situation: ``` for i in xrange(100000): account = Account() account.foo = i account.save ``` Obviously, the 100,000 `INSERT` statements executed by Django are going to take some time. It would be nicer to be able to combine all those `INSERT`s into one big `INSERT`. Here's the kin...
As shown [in this related question](http://stackoverflow.com/q/1136106/115845), one can use [@transaction.commit\_manually](http://docs.djangoproject.com/en/dev/topics/db/transactions/#django.db.transaction.commit_manually) to combine all the `.save()` operations as a single commit to greatly improve performance. ``` ...
Histogram Matplotlib
5,328,556
63
2011-03-16T16:38:32Z
5,328,669
157
2011-03-16T16:46:19Z
[ "python", "numpy", "matplotlib", "scipy" ]
So I have a little problem. I have a data set in scipy that is already in the histogram format, so I have the center of the bins and the number of events per bin. How can I now plot is as a histogram. I tried just doing ``` bins, n=hist() ``` but it didn't like that. Any recommendations?
``` import matplotlib.pyplot as plt import numpy as np mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) hist, bins = np.histogram(x, bins=50) width = 0.7 * (bins[1] - bins[0]) center = (bins[:-1] + bins[1:]) / 2 plt.bar(center, hist, align='center', width=width) plt.show() ``` ![enter image description her...
Histogram Matplotlib
5,328,556
63
2011-03-16T16:38:32Z
18,611,135
10
2013-09-04T10:15:41Z
[ "python", "numpy", "matplotlib", "scipy" ]
So I have a little problem. I have a data set in scipy that is already in the histogram format, so I have the center of the bins and the number of events per bin. How can I now plot is as a histogram. I tried just doing ``` bins, n=hist() ``` but it didn't like that. Any recommendations?
If you don't want bars you can plot it like this: ``` import numpy as np import matplotlib.pyplot as plt mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) bins, edges = np.histogram(x, 50, normed=1) left,right = edges[:-1],edges[1:] X = np.array([left,right]).T.flatten() Y = np.array([bins,bins]).T.flatten...
How to parse unicode strings with minidom?
5,329,668
9
2011-03-16T18:02:48Z
5,329,681
7
2011-03-16T18:04:18Z
[ "python", "unicode", "minidom" ]
I'm trying to parse a bunch of xml files with the library xml.dom.minidom, to extract some data and put it in a text file. Most of the XMLs go well, but for some of them I get the following error when calling minidom.parsestring(): > UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 5189: ...
Try to decode it: ``` > print u'abcdé'.encode('utf-8') > abcdé > print u'abcdé'.encode('utf-8').decode('utf-8') > abcdé ```
Can pip use existing packages rather than downloading again?
5,329,684
11
2011-03-16T18:04:23Z
5,338,383
13
2011-03-17T11:29:14Z
[ "python", "virtualenv", "pip" ]
I'm working on a new project that needs a new virtualenv. When I do pip install -r requirements.txt, it downloads the packages all over again even though those packages already exist on the previous project's virtualenv. Is there any way to tell pip to get the packages from the other virtualenv instead?
It's not the answer to your question but I guess it's what you want, i.e. avoiding the download: you can specify the environment variable PIP\_DOWNLOAD\_CACHE=/path/to/directory/where/downloaded/packages/will/be/stored Packages will be downloaded into this directory and if they are to be installed again, taken from thi...
Making Django Readonly ForeignKey Field in Admin Render as a Link
5,330,598
9
2011-03-16T19:20:36Z
5,331,032
31
2011-03-16T19:57:33Z
[ "python", "django", "django-admin" ]
I have a model exposed in Django's admin, which uses ModelAdmin's readonly\_fields list to show a "user" field, which is a ForiegnKey linking to Django's User model. By default, readonly\_fields causes this field to be rendered as simple text containing the user's email (e.g. `someuser@domain.com`). How would I change ...
Digging into the source code, I found you can essentially define your own fields as methods within your ModelAdmin subclass, and you can get the field to render as a link by simply returning the link html from the method. e.g. ``` from django.contrib import admin from django.utils.safestring import mark_safe from dja...
Why does Python let me define a variable in one scope, but use it in another?
5,331,047
7
2011-03-16T19:58:40Z
5,331,073
17
2011-03-16T20:00:16Z
[ "python" ]
I see that it's possible to define a variable inside a scope, but then refer to it outside that scope. For instance, the following code works: ``` if condition: x = 5 else: x = 10 print x ``` However, this strikes me as a bit weird. If you tried to do this in C, the variable X would not be scoped properly: `...
Blocks do not create a new scope in Python. Modules, classes, and functions do. Also: ``` x = 10 if condition: x = 5 print x ``` or: ``` x = 5 if not condition: x = 10 print x ```
Optimizing NumPy with Cython
5,331,275
3
2011-03-16T20:21:12Z
5,339,300
7
2011-03-17T12:56:33Z
[ "python", "numpy", "cython", "matrix-multiplication", "optimization" ]
I am currently trying to optimize the code that I had written in pure Python. This code uses [NumPy](http://en.wikipedia.org/wiki/NumPy) very heavily as I am working with NumPy arrays. Below you can see the simplest of my classes that I converted to [Cython](http://en.wikipedia.org/wiki/Cython). Which only does a multi...
For simple matrix multiplications, the NumPy code is already doing only the looping and multiplying natively, so it would be hard to beat that in Cython. Cython is great for situations where you are replacing loops in Python with those in Cython. One of the reasons your code is slower than NumPy is because every time y...
How to replace pairs of tokens in a string?
5,331,514
6
2011-03-16T20:45:48Z
5,331,726
7
2011-03-16T21:03:30Z
[ "python", "regex", "token" ]
New to python, competent in a few languages, but can't see a 'snazzy' way of doing the following. I'm sure it's screaming out for a regex, but any solution I can come up with (using regex groups and what not) becomes insane quite quickly. So, I have a string with html-like tags that I want to replace with actual html ...
Maybe something like this can help : ``` import re def text2html(text): """ Convert a text in a certain format to html. Examples: >>> text2html('Hello, my name is /bJane/b') 'Hello, my name is <b>Jane</b>' >>> text2html('/iHello/i, my /uname/u is /b/i/uJane/u/i/b') '<i>Hello</i>, my <u>name<...
I can't get Python's executemany for sqlite3 to work properly
5,331,894
6
2011-03-16T21:18:03Z
5,331,961
9
2011-03-16T21:24:08Z
[ "python", "sqlite3", "pysqlite" ]
I was trying to use executemany to insert values into a database, but it just won't work for me. Here is a sample: ``` clist = [] clist.append("abc") clist.append("def") clist.append("ghi") cursor.executemany("INSERT INTO myTable(data) values (?) ", clist) ``` This gives me the following error: `sqlite3.ProgrammingE...
From what I know of executemany, you meant, ``` clist = [("abc", ), ("def", ), ("ghi", )] cursor.executemany("INSERT INTO myTable(data) values(?)", clist) ``` Or something similar. Don't quote me on the syntax for sqlite, I haven't used it in an app in a while, but you need an iterable of tuples (more generally itera...
How to sub with matched groups and variables in Python
5,331,985
6
2011-03-16T21:26:00Z
5,332,421
15
2011-03-16T22:06:24Z
[ "python", "regex" ]
new to python. This is probably simple but I haven't found an answer. ``` rndStr = "20101215" rndStr2 = "20101216" str = "Looking at dates between 20110316 and 20110317" outstr = re.sub("(.+)([0-9]{8})(.+)([0-9]{8})",r'\1'+rndStr+r'\2'+rndStr2,str) ``` The output I'm looking for is: ``` Looking at dates between 2010...
Your backreferences are ambiguous. Your replacement string becomes ``` \120101215\220101216 ``` which is two rather large numbers to be backreferencing :) To solve it, use this syntax: ``` r'\g<1>'+rndStr+r'\g<2>'+rndStr2 ``` You also have too many sets of brackets - you don't need brackets around the [0-9]{8} par...
How to determine the bitrate of mp3 files with Python?
5,332,151
4
2011-03-16T21:39:25Z
5,332,367
9
2011-03-16T21:59:11Z
[ "python", "mp3", "bitrate" ]
How to determine the type of the bitrate - CBR, VBR or ABR?
[mutagen](http://code.google.com/p/mutagen/) works for me. Here is an excerpt from one of my scripts. ``` from mutagen.mp3 import MP3 f = MP3(musicfile) bitrate = f.info.bitrate / 1000 ```
Yapsy minimal example
5,333,128
15
2011-03-16T23:39:40Z
5,344,300
38
2011-03-17T19:41:06Z
[ "python", "plugins" ]
Can anyone provide a minimal working example using the [Yapsy plugin framework](http://yapsy.sourceforge.net)?
Here's a very simple example. It has three files: * plugins\plugin1.py - the plugin. This has to contain a class inherited from IPlugin. * plugins\plugin1.yapsy-plugin - information about the plugin. * yapsy-example.py - the main script. This just loads all the plugins it can find in the "plugins" directory, and calls...
Why is this not a fixed width pattern?
5,333,200
5
2011-03-16T23:49:28Z
5,333,314
11
2011-03-17T00:08:29Z
[ "python", "regex" ]
I'm trying to split English sentences correctly, and I came up with the unholy regex below: ``` (?<!\d|([A-Z]\.)|(\.[a-z]\.)|(\.\.\.)|etc\.|[Pp]rof\.|[Dd]r\.|[Mm]rs\.|[Mm]s\.|[Mm]z\.|[Mm]me\.)(?<=([\.!?])|(?<=([\.!?][\'\"])))[\s]+?(?=[\S])' ``` The problem is, Python keeps raising the following error: ``` Traceback ...
Consider this subexpression: ``` (?<=([\.!?])|(?<=([\.!?][\'\"]))) ``` The left side of the | is one character, while the right size is zero. You have the same issue in your larger negative look-behind too, it could be 1, 2, 3, 4, or 5 characters. Logically, a negative look-behind of `(?<!A|B|C)` should be equivalen...
Python lxml XPath problem
5,333,236
4
2011-03-16T23:54:29Z
5,333,345
10
2011-03-17T00:13:04Z
[ "python", "xpath", "lxml" ]
I'm trying to print/save a certain element's HTML from a web-page. I've retrieved the requested element's XPath from firebug. All I wish is to save this element to a file. I don't seem to succeed in doing so. (tried the XPath with and without a `/text()` at the end) I would appreciate any help, or past experience...
Your XPath is obviously a bit too long, why don't you try shorter ones and see if they match. One problem might be "tbody" which gets automatically created in the DOM by browsers but the HTML markup usually does not contain it. Here's an example of how to use XPath results: ``` >>> from lxml import etree >>> from Str...
Extended tuple unpacking in Python 2
5,333,680
22
2011-03-17T01:05:06Z
5,333,760
12
2011-03-17T01:14:45Z
[ "python", "tuples", "iterable-unpacking" ]
Is it possible to simulate extended tuple unpacking in Python 2? Specifically, I have a for loop: ``` for a, b, c in mylist: ``` which works fine when mylist is a list of tuples of size three. I want the same for loop to work if I pass in a list of size four. I think I will end up using named tuples, but I was wond...
You could define a wrapper function that converts your list to a four tuple. For example: ``` def wrapper(thelist): for item in thelist: yield(item[0], item[1], item[2], item[3:]) mylist = [(1,2,3,4), (5,6,7,8)] for a, b, c, d in wrapper(mylist): print a, b, c, d ``` The code prints: ``` 1 2 3 (4,)...
Extended tuple unpacking in Python 2
5,333,680
22
2011-03-17T01:05:06Z
5,333,816
8
2011-03-17T01:23:14Z
[ "python", "tuples", "iterable-unpacking" ]
Is it possible to simulate extended tuple unpacking in Python 2? Specifically, I have a for loop: ``` for a, b, c in mylist: ``` which works fine when mylist is a list of tuples of size three. I want the same for loop to work if I pass in a list of size four. I think I will end up using named tuples, but I was wond...
For the heck of it, generalized to unpack any number of elements: ``` lst = [(1, 2, 3, 4, 5), (6, 7, 8), (9, 10, 11, 12)] def unpack(seq, n=2): for row in seq: yield [e for e in row[:n]] + [row[n:]] for a, rest in unpack(lst, 1): pass for a, b, rest in unpack(lst, 2): pass for a, b, c, rest in ...
Extended tuple unpacking in Python 2
5,333,680
22
2011-03-17T01:05:06Z
5,333,829
20
2011-03-17T01:25:10Z
[ "python", "tuples", "iterable-unpacking" ]
Is it possible to simulate extended tuple unpacking in Python 2? Specifically, I have a for loop: ``` for a, b, c in mylist: ``` which works fine when mylist is a list of tuples of size three. I want the same for loop to work if I pass in a list of size four. I think I will end up using named tuples, but I was wond...
You can't do that directly, but it isn't terribly difficult to write a utility function to do this: ``` >>> def unpack_list(a, b, c, *d): ... return a, b, c, d ... >>> unpack_list(*range(100)) (0, 1, 2, (3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,...
best way to pop many element in a python dict
5,333,898
7
2011-03-17T01:36:08Z
5,333,919
13
2011-03-17T01:39:39Z
[ "python", "dictionary" ]
this is my code : ``` a = {'aa':'aaaa','bb':'bbbbb','cc':'ccccc'....} print a.pop(['cc'...]) ``` but it shows error. which is the best simple way to pop many element from a python dictionary.
How about the simple: ``` for e in ['cc', 'dd',...]: a.pop(e) ```
best way to pop many element in a python dict
5,333,898
7
2011-03-17T01:36:08Z
5,333,947
16
2011-03-17T01:43:58Z
[ "python", "dictionary" ]
this is my code : ``` a = {'aa':'aaaa','bb':'bbbbb','cc':'ccccc'....} print a.pop(['cc'...]) ``` but it shows error. which is the best simple way to pop many element from a python dictionary.
Using list comprehension: ``` a = {'key1':'value1','key2':'value2','key3':'value3'} print [a.pop(key) for key in ['key1', 'key3']] ```
Optimizing my Cython/Numpy code? Only a 30% performance gain so far
5,334,012
3
2011-03-17T01:56:24Z
5,423,866
7
2011-03-24T18:38:41Z
[ "python", "numpy", "cython" ]
Is there anything I've forgotten to do here in order to speed things up a bit? I'm trying to implement an algorithm described in a book called Tuning Timbre Spectrum Scale. Also---if all else fails, is there a way for me to just write this part of the code in C, then be able to call it from python? ``` import numpy as...
Here are some things that I noticed: 1. Use `t1.shape[0]` instead of `np.shape(t1)[0]` and in so on in other places. 2. Don't use `len` as a variable because it is a built-in function in Python (not for speed, but for good practice). Use L or something like that. 3. Don't pass two-element arrays to functions unless yo...
Using javadoc for Python documentation
5,334,531
138
2011-03-17T03:22:52Z
5,334,625
24
2011-03-17T03:40:14Z
[ "python", "documentation", "javadoc", "docstring" ]
I am currently beginning with Python and I have a strong PHP background and in PHP I have took the habit of using `javadoc` as a documentation template. I was wondering if `javadoc` has its place as `docstring` documentation in Python. Is something like this too elaborate to fit in the Python mindset or should I try t...
The standard for python documentation strings is described in [Python Enhancement Proposal 257](http://www.python.org/dev/peps/pep-0257/). The appropriate comment for your method would be something like ``` def format(...): """Return timestamp string with place holders replaced with values. Keyword arguments...
Using javadoc for Python documentation
5,334,531
138
2011-03-17T03:22:52Z
5,339,352
209
2011-03-17T13:02:27Z
[ "python", "documentation", "javadoc", "docstring" ]
I am currently beginning with Python and I have a strong PHP background and in PHP I have took the habit of using `javadoc` as a documentation template. I was wondering if `javadoc` has its place as `docstring` documentation in Python. Is something like this too elaborate to fit in the Python mindset or should I try t...
Have a look at the [reStructuredText](http://docutils.sourceforge.net/rst.html) (also known as "reST") format, which is a plaintext/docstring markup format, and probably the most popular in the Python world. And you should certainly look at [Sphinx](http://sphinx-doc.org), a tool to generate documentation from reStruct...
Using javadoc for Python documentation
5,334,531
138
2011-03-17T03:22:52Z
27,232,448
60
2014-12-01T16:10:53Z
[ "python", "documentation", "javadoc", "docstring" ]
I am currently beginning with Python and I have a strong PHP background and in PHP I have took the habit of using `javadoc` as a documentation template. I was wondering if `javadoc` has its place as `docstring` documentation in Python. Is something like this too elaborate to fit in the Python mindset or should I try t...
Follow [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html?showone=Comments#Comments). Note that Sphinx can also parse this format using the [Napolean](http://sphinxcontrib-napoleon.readthedocs.org/en/latest/) extension, which will come packaged with Sphinx 1.3 (this is also compatible with [PE...
Python: how to know function return type and argument types?
5,336,320
16
2011-03-17T07:54:12Z
5,336,458
8
2011-03-17T08:11:40Z
[ "python", "types" ]
While I am aware of the duck-typing concept of Python, I sometimes struggle with the type of arguments of functions, or the type of the return value of the function. Now, if I wrote the function myself, I DO know the types. But what if somebody wants to use and call my functions, how is he/she expected to know the typ...
This is how dynamic languages work. It is not always a good thing though, especially if the documentation is poor - anyone tried to use a poorly documented python framework? Sometimes you have to revert to reading the source. Here are some strategies to avoid problems with duck typing: * create a language for your pr...
Is there a Python module to detect month or day in string?
5,336,447
3
2011-03-17T08:10:02Z
5,336,473
22
2011-03-17T08:13:48Z
[ "python", "date" ]
Is there a Python module to parse month or day references in a given string?
You could try using `dateutil.parser`, e.g.: ``` >>> from dateutil import parser >>> parser.parse("There's a date 09-21 in here", fuzzy=True) datetime.datetime(2011, 9, 21, 0, 0) ``` ... with the `fuzzy=True` option. The documentation is [here](http://niemeyer.net/python-dateutil#head-a23e8ae0a661d77b89dfb3476f85b26f...
Boost.Python call by reference : TypeError: No to_python (by-value) converter found for C++ type:
5,336,942
14
2011-03-17T09:07:55Z
5,337,551
13
2011-03-17T10:04:30Z
[ "c++", "python", "boost", "boost-python" ]
I'm trying to expose my C++ Classes to Python using Boost.Python. Here is a simplyfied version of what i'm trying to do: I have a class A deriving from boost::noncopyable and a second class B with a method that takes a reference to A as an argument. ``` class A : boost::noncopyable { /*...*/ }; class B { public: ...
Change `B.do_something(a);` to `B.do_something(boost::ref(a));`. See [Calling Python Functions and Methods](http://www.boost.org/doc/libs/1_46_0/libs/python/doc/v2/callbacks.html#argument_handling) in the boost manual.
How can I get a file's permission mask?
5,337,070
28
2011-03-17T09:19:04Z
5,337,329
56
2011-03-17T09:44:00Z
[ "python", "file" ]
How can I get a file's permission mask like 644 or 755 on \*nix using python? Is there any function or class for doing that? Could you guys help me out? Thank you very much!
`os.stat` is a wrapper around the [stat(2)](http://linux.die.net/man/2/stat) system call interface. ``` >>> import os >>> from stat import * >>> os.stat("test.txt") # returns 10-tupel, you really want the 0th element ... posix.stat_result(st_mode=33188, st_ino=57197013, \ st_dev=234881026L, st_nlink=1, st_uid=501,...
How can I get a file's permission mask?
5,337,070
28
2011-03-17T09:19:04Z
5,337,805
24
2011-03-17T10:28:50Z
[ "python", "file" ]
How can I get a file's permission mask like 644 or 755 on \*nix using python? Is there any function or class for doing that? Could you guys help me out? Thank you very much!
I think this is the clearest way of getting a file's the permission bits: ``` stat.S_IMODE(os.lstat("file").st_mode) ``` The os.lstat function, will in case the file is a symlink, give you the mode of the link itself, whereas os.stat dereferences the link. Therefore I find os.lstat the most generally useful. Here's ...
Use Django User-Model or create a own Model?
5,337,351
3
2011-03-17T09:45:46Z
5,337,548
8
2011-03-17T10:04:02Z
[ "python", "django", "design-decisions", "django-users" ]
I'm currently designing a Django based site. For simplicity lets assume that it is a simple community site where users can log in and write messages to other users. My current choice is wether to use the buildin User-Model or to build something my own. I don't need much from the buildin `User`: there will be no userna...
> Is there anything wrong with my reflections? Yes. > My current choice is wether to use the buildin User-Model or to build something my own. There is a third choice. <http://docs.djangoproject.com/en/1.2/topics/auth/#storing-additional-information-about-users> > everything else would be placed in a UserProfile C...
How to draw probabilistic distributions with numpy/matplotlib?
5,338,944
5
2011-03-17T12:23:23Z
5,339,058
8
2011-03-17T12:34:09Z
[ "python", "numpy", "matplotlib" ]
I want to draw probabilistic functions (like the binomial distribution), but i don't find a function that returns the probability for given parameters. To write it myself i need binomial coefficients (I could write that myself), for which I haven't found a function either. Is there a 'short and/or easy' to do this? T...
`scipy.stats.binom.pmf` gives the probability mass function for the binomial distribution. You could compute it for a range and plot it. for example, for 10 trials, and p = 0.1, you could do ``` import scipy, scipy.stats x = scipy.linspace(0,10,11) pmf = scipy.stats.binom.pmf(x,10,0.1) import pylab pylab.plot(x,pmf) `...
display an object's attributes in python
5,340,042
9
2011-03-17T13:59:48Z
5,340,074
12
2011-03-17T14:01:18Z
[ "python", "oop", "list" ]
I would like to display the attributes of a give object and was wondering if there was a python function for it. For example if I had an object from the following class: ``` class Antibody(): def __init__(self,toSend): self.raw = toSend self.pdbcode = '' self.year = '' ``` Could I get an...
Try `dir(self)`. It will include all attributes, not only "data".
display an object's attributes in python
5,340,042
9
2011-03-17T13:59:48Z
5,340,364
7
2011-03-17T14:24:50Z
[ "python", "oop", "list" ]
I would like to display the attributes of a give object and was wondering if there was a python function for it. For example if I had an object from the following class: ``` class Antibody(): def __init__(self,toSend): self.raw = toSend self.pdbcode = '' self.year = '' ``` Could I get an...
The following method prints `['self.pdbcode', 'self.raw', 'self.year']` for an instance of your class: ``` class Antibody(): ... def get_fields(self): ret = [] for nm in dir(self): if not nm.startswith('__') and not callable(getattr(self, nm)): ret.append('self.' + nm) ...
Where should I put tests when packaging python modules?
5,341,006
7
2011-03-17T15:11:21Z
7,606,492
13
2011-09-30T06:03:43Z
[ "python", "testing", "namespaces", "distribution" ]
I have a module that sits in a namespace. Should tests and data the tests rely on go in the namespace or in the top level where setup.py sites? ``` ./company/__init__.py ./company/namespace/__init__.py ./company/namespace/useful.py ./company/namespace/test_useful.py ./company/namespace/test_data/useful_data.xml ./setu...
You should put your test module inside the module it tests according to the [The Hitchhiker's Guide to Packaging](http://the-hitchhikers-guide-to-packaging.readthedocs.org/en/latest/creation.html). Here is their example: ``` TowelStuff/ bin/ CHANGES.txt docs/ LICENSE.txt MANIFEST.in README.txt...
How to patch a module's internal functions with mock?
5,341,147
20
2011-03-17T15:21:48Z
14,410,029
13
2013-01-19T01:00:59Z
[ "python", "mocking", "patch" ]
By "internal function", I mean a function that is called from within the same module it is defined in. I am using the [mock](http://www.voidspace.org.uk/python/mock/) library, specifically the [patch](http://www.voidspace.org.uk/python/mock/patch.html) decorators, in my unit tests. They're Django unit tests, but this ...
The answer: **Clean up your darned imports** `@patch('mymodule.TAX_LOCATION', '')` did indeed patch things appropriately, but since our imports at the time were very haphazard -- sometimes we imported `mymodule.build_cart`, sometimes we imported `project.mymodule.build_cart` -- instances of the "full" import were not ...
for loop in python
5,341,794
2
2011-03-17T16:06:43Z
5,341,806
8
2011-03-17T16:07:32Z
[ "python", "loops", "for-loop" ]
I just started with python.. I got an error with for loop.. What is the problem ?? ``` Traceback (most recent call last): File "userentry.py", line 34, in <module> userentry(p,i) File "userentry.py", line 26, in userentry for cl in len(mylist): TypeError: 'int' object is not iterable ``` Please help m...
You can just iterate over the list, you don't iterate over the length of the list. ``` for cl in mylist: # do stuff ``` If you need to keep track of the index of the current item, use `enumerate`: ``` for idx, item in enumerate(mylist): # idx = index of current item # item = current item ``` When you tr...
Can I retrieve IMDb's movie recommendations for a given movie using IMDbPY?
5,342,329
11
2011-03-17T16:45:44Z
5,342,891
7
2011-03-17T17:33:07Z
[ "python", "imdb" ]
I'm using [IMDbPY](http://imdbpy.sourceforge.net/) to retrieve all kinds of data about movies. For example, if I have a movie object of "Pulp Fiction (1994)" then I can get the name of its (first) director like this: ``` >>> pulp_fiction['director'][0]['name'] u'Quentin Tarantino' ``` Or the name of the third act...
Looking in the source, I found something: [http://bitbucket.org/alberanid/imdbpy/src/579c50b280f9/imdb/parser/http/**init**.py](https://bitbucket.org/alberanid/imdbpy/src/579c50b280f9/imdb/parser/http/__init__.py) check `def get_movie_recommendations(self, movieID)` I haven't tried it, but it looks like it might be ...
cursor.execute("INSERT INTO im_entry.test ("+entrym+") VALUES ('"+p+"');")
5,342,698
2
2011-03-17T17:16:38Z
5,342,741
9
2011-03-17T17:20:32Z
[ "python", "database", "postgresql" ]
``` entrym='entry' entrym=entrym+ str(idx) cursor.execute("INSERT INTO im_entry.test ("+entrym+") VALUES ('"+p+"');") ``` I am using a query like this.. Where entry1, entry2.. etc are my database tables..Program doesn't show any errors.. But p value is not get inserted in to db.. What is wrong..please help m...
By default, psycopg2 starts transactions for you automatically, which means that you have to tell it to commit. Note that `commit` is a method of the connection, not the cursor. ``` conn = psycopg2.connection('...') cur = conn.cursor() cur.execute("...") conn.commit() ``` The intent is that you can group multiple sta...
create & read from tempfile
5,344,287
23
2011-03-17T19:39:23Z
5,344,342
23
2011-03-17T19:44:51Z
[ "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(...
If you need a temporary file with a name you have to use the `NamedTemporaryFile` function. Then you can use `temp.name`. Read <http://docs.python.org/library/tempfile.html> for details.