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
Installing 3rd party Python modules on an Ubuntu Linux machine?
11,893,311
6
2012-08-09T23:11:39Z
11,893,356
7
2012-08-09T23:17:47Z
[ "python", "module" ]
I'm guessing my question is pretty basic, but after 15-20 minutes on Google and YouTube, I am still a little fuzzy. I am relatively new to both Linux and Python, so I am having some difficulty comprehending the file system tree (coming from Windows). From what I've found digging around the directories in Ubuntu (which...
You aren't supposed to manually install anything. There are three ways to install Python libraries: 1. Use `apt-get`, `aptitude` or similar utilities. 2. Use `easy_install` or `pip` (install `pip` first, its not available by default) 3. If you download some `.tar.gz` file, unzip it and then type `sudo python setup.py...
Installing 3rd party Python modules on an Ubuntu Linux machine?
11,893,311
6
2012-08-09T23:11:39Z
11,893,357
9
2012-08-09T23:17:59Z
[ "python", "module" ]
I'm guessing my question is pretty basic, but after 15-20 minutes on Google and YouTube, I am still a little fuzzy. I am relatively new to both Linux and Python, so I am having some difficulty comprehending the file system tree (coming from Windows). From what I've found digging around the directories in Ubuntu (which...
`virtualenv` is the de facto Python standard for installing third party library cleanly. Read more about it here: <http://www.virtualenv.org/> Usage example: ``` daniel@redhotcar:~/tmp$ virtualenv myenv New python executable in myenv/bin/python Installing distribute.......................................................
how to make square subplots in matplotlib with heatmaps?
11,893,414
11
2012-08-09T23:24:44Z
11,894,123
8
2012-08-10T01:04:29Z
[ "python", "numpy", "matplotlib", "scipy" ]
I'm trying to make a simple subplot with a dendrogram in one subplot and a heat map in another, while maintaining square axes. I try the following: ``` from scipy.cluster.hierarchy import linkage from scipy.cluster.hierarchy import dendrogram from scipy.spatial.distance import pdist fig = plt.figure(figsize=(7,7)) pl...
aspect="equal" mean the same length in data space will be the same length in screen space, but in your top axe, the data ranges of xaxis and yaxis are not the same, so it will not be a square. To fix this problem, you can set the aspect to the ratio of xaxis range and yaxis range: ``` from scipy.cluster.hierarchy impo...
how to make square subplots in matplotlib with heatmaps?
11,893,414
11
2012-08-09T23:24:44Z
11,978,051
8
2012-08-15T22:08:59Z
[ "python", "numpy", "matplotlib", "scipy" ]
I'm trying to make a simple subplot with a dendrogram in one subplot and a heat map in another, while maintaining square axes. I try the following: ``` from scipy.cluster.hierarchy import linkage from scipy.cluster.hierarchy import dendrogram from scipy.spatial.distance import pdist fig = plt.figure(figsize=(7,7)) pl...
@HYRY's answer is very good and deserves all the credit. But to finish off the answer about lining the squared plots up nicely, you could trick matplotlib into thinking that both plots have colorbars, only making the first one invisible: ``` from scipy.cluster.hierarchy import linkage from scipy.cluster.hierarchy impo...
python convert ipv6 to an integer
11,894,717
7
2012-08-10T02:38:07Z
11,894,858
7
2012-08-10T02:56:31Z
[ "python", "ipv6" ]
Is there any package or easy way to convert an ipv6 to an integer? The algorithm should be a little smart to understand the ipv6 short formats. Before I start to write my own code , I just wonder if anyone knows a package that can do the job? Thanks,
You want [IPy](http://c0re.23.nu/c0de/IPy/). ``` >>> IPy.IP('fe80::21b:77ff:fbd6:7860') IP('fe80::21b:77ff:fbd6:7860') >>> IPy.IP('fe80::21b:77ff:fbd6:7860').int() 338288524927261089654170743795120240736L >>> IPy.IP('fe80::fbd6:7860') IP('fe80::fbd6:7860') >>> IPy.IP('fe80::fbd6:7860').int() 3382885249272610896540188...
python convert ipv6 to an integer
11,894,717
7
2012-08-10T02:38:07Z
11,895,071
13
2012-08-10T03:28:34Z
[ "python", "ipv6" ]
Is there any package or easy way to convert an ipv6 to an integer? The algorithm should be a little smart to understand the ipv6 short formats. Before I start to write my own code , I just wonder if anyone knows a package that can do the job? Thanks,
You can do this with some help from the **standard** Python socket module. [`socket.inet_pton()`](http://docs.python.org/library/socket.html#socket.inet_pton) handles IPV6 short form without any trouble. ``` import socket from binascii import hexlify def IPV6_to_int(ipv6_addr): return int(hexlify(socket.inet_pton...
Unable log in to the django admin page with a valid username and password
11,894,765
26
2012-08-10T02:45:15Z
12,110,570
24
2012-08-24T13:39:20Z
[ "python", "django", "login", "admin", "mod-wsgi" ]
I can’t log in to the django admin page. When I enter a valid username and password, it just brings up the login page again, with no error messages This question is in the [django FAQ](https://docs.djangoproject.com/en/dev/faq/admin/#i-can-t-log-in-when-i-enter-a-valid-username-and-password-it-just-brings-up-the-log...
Steps to debug: * Make sure that your Database is synced + Double check that you have a django\_session table * Try to authenticate + Do you see a record being created in the `django_session` table? IF NOT * remove non-standard settings + AUTHENTICATION\_BACKENDS = ('django.contrib.auth.backends.ModelBackend',...
Django url pattern - string parameter
11,894,916
17
2012-08-10T03:04:48Z
11,894,992
17
2012-08-10T03:15:52Z
[ "python", "regex", "django" ]
Django url pattern that have a number parameter is: ``` url(r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail') ``` What will be the correct syntax if my poll\_id is not a number but a string of character?
Depends on what characters you care about. Like [the docs](http://docs.python.org/library/re.html) say, `\w` will give you an alphanumeric character or an underscore.
does ndb have a list property
11,895,710
15
2012-08-10T04:58:20Z
11,895,711
27
2012-08-10T04:58:20Z
[ "python", "google-app-engine", "list", "gae-datastore" ]
Instead of a single StringProperty(), I want to store a list of strings ``` class BlogPost(ndb.Model): s1 = ndb.StringProperty(required=True) s2 = ndb.StringProperty(required=True) s3 = ndb.StringProperty(required=True) ``` I would rather go ``` class BlogPost(ndb.Model): my_strings = ndb.StringListP...
yes, use a repeated property: > Any property with repeated=True becomes a repeated property. The > property takes a list of values of the underlying type, rather than a > single value. For example, the value of a property defined with > IntegerProperty(repeated=True) is a list of integers. see the docs: [Repeated Pro...
Python: string to a list of lists
11,895,768
3
2012-08-10T05:05:18Z
11,895,778
14
2012-08-10T05:06:37Z
[ "python", "string", "list", "split" ]
I'm new to python and confused about converting a string to a list. I'm unsure how to create a list within a list to accomplish the following: Ex. ``` string = '2,4,6,8|10,12,14,16|18,20,22,24' ``` I'm trying to use split() to create a data structure, my\_data, so that when I input ``` print my_data[1][2] #it shoul...
``` >>> text = '2,4,6,8|10,12,14,16|18,20,22,24' >>> my_data = [x.split(',') for x in text.split('|')] >>> my_data [['2', '4', '6', '8'], ['10', '12', '14', '16'], ['18', '20', '22', '24']] >>> print my_data[1][2] 14 ``` Maybe you also want to convert each digit (still strings) to `int`, in which case I would do this:...
How can I consistently convert strings like "3.71B" and "4M" to numbers in Python?
11,896,560
5
2012-08-10T06:32:02Z
11,896,657
10
2012-08-10T06:40:01Z
[ "python", "regex", "finance", "yahoo-finance" ]
I have some rather mangled code that almost produces the **tangible price/book** from Yahoo Finance for companies (a nice module called `ystockquote` gets the **intangible price/book** value already). My problem is this: For one of the variables in the calculation, **shares outstanding** I'm getting strings like **10...
``` >>> from decimal import Decimal >>> d = { 'M': 6, 'B': 9 } >>> def text_to_num(text): if text[-1] in d: num, magnitude = text[:-1], text[-1] return Decimal(num) * 10 ** d[magnitude] else: return Decimal(text) >>> text_to_num('3.17B') Decimal('3170...
Why are these results so different when using Python's "float" function?
11,897,260
3
2012-08-10T07:30:42Z
11,897,339
17
2012-08-10T07:37:03Z
[ "python", "math", "floating-point", "type-conversion", "converter" ]
My Python code was doing something strange to me (or my numbers, rather): a) ``` float(poverb.tangibles[1])*1000 1038277000.0 ``` b) ``` float(poverb.tangibles[1]*1000) inf ``` Which led to discovering that: ``` long(poverb.tangibles[1]*1000) ``` produces the largest number I've ever seen. Uhhh, I didn't read t...
What you probably missed is docs on how multiplication works on strings. Your `tangibles` list contains *strings*. `tangibles[1]` is a string. `tangibles[1]*1000` is that string repeated 1000 times. Calling `float` or `long` on that string interprets it as a number, creating a huge number. If you instead do `float(tang...
SQLAlchemy: Table already exists
11,900,553
4
2012-08-10T11:17:44Z
16,003,063
10
2013-04-14T19:00:15Z
[ "python", "sqlalchemy" ]
when do we generally get the following error in SQLAlchemy? ``` sqlalchemy.exc.OperationalError: (OperationalError) (1050, "Table 'foobar' already exists") ``` The `foobar` table does already exists, but why SQLAlchemy is trying to create table when already present. I'm assuming it shouldn't create table if already e...
Just use schema object's **(Table,Index and Sequence)** **create** and **drop** methods with **checkfirst=True** **keyword** and table will automatically add an **"IF NOT EXISTS or IF EXISTS CLAUSE"** whichever is appropriate to SQL. **FOR EXAMPLE:** ``` t = Table('foobar', metadata, Column('col1', String(50), prim...
store return value of a Python script in a bash script
11,900,828
14
2012-08-10T11:35:36Z
11,900,864
10
2012-08-10T11:37:37Z
[ "python", "bash", "return", "return-value" ]
I want to execute a python script from a bash script, and I want to store the output of the python script in a variable. In my python script, I print some stuff to screen and at the end I return a string with: ``` sys.exit(myString) ``` In my bash script, I did the following: ``` outputString=`python myPythonScript...
`sys.exit()` should return an integer, not a string: ``` sys.exit(1) ``` The value `1` is in `$?`. ``` $ cat e.py import sys sys.exit(1) $ python e.py $ echo $? 1 ``` **Edit:** If you want to write to stderr, use [`sys.stderr`](http://docs.python.org/library/sys.html?highlight=sys.stderr#sys.stderr).
store return value of a Python script in a bash script
11,900,828
14
2012-08-10T11:35:36Z
11,900,911
13
2012-08-10T11:41:02Z
[ "python", "bash", "return", "return-value" ]
I want to execute a python script from a bash script, and I want to store the output of the python script in a variable. In my python script, I print some stuff to screen and at the end I return a string with: ``` sys.exit(myString) ``` In my bash script, I did the following: ``` outputString=`python myPythonScript...
<http://docs.python.org/library/sys.html#sys.exit> `sys.exit` will write to `stderr` if you use string args. Do something like ``` python yourscript 2> return_file ``` [Bash script - store stderr in variable](http://stackoverflow.com/questions/3130375/bash-script-store-stderr-in-variable) You could do something li...
Only index needed: enumerate or (x)range?
11,901,081
12
2012-08-10T11:51:48Z
11,901,101
13
2012-08-10T11:53:14Z
[ "python", "range", "enumerate" ]
If I want to use only the index within a loop, should I better use the `range/xrange` function in combination with `len()` ``` a = [1,2,3] for i in xrange(len(a)): print i ``` or `enumerate`? Even if I won't use `p` at all? ``` for i,p in enumerate(a): print i ```
That's a rare requirement – the only information used from the container is its length! In this case, I'd indeed make this fact explicit and use the first version.
Only index needed: enumerate or (x)range?
11,901,081
12
2012-08-10T11:51:48Z
11,901,150
7
2012-08-10T11:55:50Z
[ "python", "range", "enumerate" ]
If I want to use only the index within a loop, should I better use the `range/xrange` function in combination with `len()` ``` a = [1,2,3] for i in xrange(len(a)): print i ``` or `enumerate`? Even if I won't use `p` at all? ``` for i,p in enumerate(a): print i ```
Using xrange with len is quite a common use case, so yes, you can use it if you only need to access values by index. But if you prefer to use enumerate for some reason, you can use underscore (\_), it's just a frequently seen notation that show you won't use the variable in some meaningful way: ``` for i, _ in enumer...
Only index needed: enumerate or (x)range?
11,901,081
12
2012-08-10T11:51:48Z
11,901,308
11
2012-08-10T12:05:35Z
[ "python", "range", "enumerate" ]
If I want to use only the index within a loop, should I better use the `range/xrange` function in combination with `len()` ``` a = [1,2,3] for i in xrange(len(a)): print i ``` or `enumerate`? Even if I won't use `p` at all? ``` for i,p in enumerate(a): print i ```
I would use `enumerate` as it's more generic - eg it will work on iterables and sequences, and the overhead for just returning a reference to an object isn't that big a deal - while `xrange(len(something))` although (to me) more easily readable as your intent - will break on objects with no support for `len`...
How to timeout function in python, timeout less than a second
11,901,328
15
2012-08-10T12:06:54Z
11,901,541
21
2012-08-10T12:18:10Z
[ "python", "regex", "function", "timeout" ]
### Specification of the problem: I'm searching through really great amount of lines of a log file and I'm distributing those lines to groups in order to regular expressions(RegExses) I have stored using the `re.match()` function. Unfortunately some of my RegExses are too complicated and Python sometimes gets himself ...
**Solution:** In the end, the solution wasn't that complicated, but I thought, that it might be useful for some other hopelessly stacked guys like me to post this simple solution here. I've just a bit modified script posted here: [Timeout function if it takes too long to finish](http://stackoverflow.com/questions/228...
Subprocess.poll() falsely returns a value
11,901,517
6
2012-08-10T12:16:59Z
11,901,881
7
2012-08-10T12:41:19Z
[ "python", "subprocess", "popen" ]
**test1.py:** ``` process = Popen(["python","test2.py"]) time.sleep(3) alive = process.poll() if alive is None: print "Still running" else: print "Not running\r\n" print "%r" % alive ``` **test1.py Output:** `Not running` `2` **test2.py:** ``` time.sleep(30) print "done" ``` What is going on? Shoul...
If Popen() cannot find test2.py, it produces the error "No such file or directory", with errno 2. This error number is returned by poll(). Since you seem to be running this script through wsgi, something seems to be gulping your stderr and you don't see the error message: ``` $ cat test1.py from subprocess import Pope...
BeautifulSoup, a dictionary from an HTML table
11,901,846
8
2012-08-10T12:38:52Z
11,901,913
10
2012-08-10T12:43:10Z
[ "python", "beautifulsoup" ]
I am trying to scrape table data from a website. Here is a simple example table: ``` t = '<html><table>' +\ '<tr><td class="label"> a </td> <td> 1 </td></tr>' +\ '<tr><td class="label"> b </td> <td> 2 </td></tr>' +\ '<tr><td class="label"> c </td> <td> 3 </td></tr>' +\ '<tr><td class="label"> d </td> ...
Try this: ``` from BeautifulSoup import BeautifulSoup, Comment t = '<html><table>' +\ '<tr><td class="label"> a </td> <td> 1 </td></tr>' +\ '<tr><td class="label"> b </td> <td> 2 </td></tr>' +\ '<tr><td class="label"> c </td> <td> 3 </td></tr>' +\ '<tr><td class="label"> d </td> <td> 4 </td></tr>' +\ ...
Django - User full name as unicode
11,902,262
5
2012-08-10T13:04:48Z
11,902,442
13
2012-08-10T13:14:44Z
[ "python", "django", "django-models", "django-users" ]
I have many Models linked to `User` and I'd like my templates to always display his full\_name if available. Is there a way to change the default `User` `__unicode__()` ? Or is there another way to do it ? I have a profile model registered where I can define the `__unicode__()`, should I link all my models to it ? See...
Try this: ``` User.full_name = property(lambda u: u"%s %s" % (u.first_name, u.last_name)) ``` # EDIT Apparently what you want already exists.. <https://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.models.User.get_full_name> # ALSO if its imperative that the unicode function be replaced: ``` def...
I want to exception handle 'list index out of range.'
11,902,458
31
2012-08-10T13:15:45Z
11,902,480
83
2012-08-10T13:17:13Z
[ "python", "list", "exception-handling" ]
I am using **BeautifulSoup** and parsing some HTMLs. I'm getting a certain data from each HTML *(using for loop)* and adding that data to a certain list. The problem is, some of the HTMLs have different format *(and they don't have the data that I want in them)*. So, I was trying to use exception handling and add va...
Handling the exception is the way to go: ``` try: gotdata = dlist[1] except IndexError: gotdata = 'null' ``` Of course you could also check the `len()` of `dlist`; but handling the exception is more intuitive.
I want to exception handle 'list index out of range.'
11,902,458
31
2012-08-10T13:15:45Z
11,902,491
15
2012-08-10T13:17:43Z
[ "python", "list", "exception-handling" ]
I am using **BeautifulSoup** and parsing some HTMLs. I'm getting a certain data from each HTML *(using for loop)* and adding that data to a certain list. The problem is, some of the HTMLs have different format *(and they don't have the data that I want in them)*. So, I was trying to use exception handling and add va...
You have two options; either handle the exception or test the length: ``` if len(dlist) > 1: newlist.append(dlist[1]) continue ``` or ``` try: newlist.append(dlist[1]) except IndexError: pass continue ``` Use the first if there *often* is no second item, the second if there *sometimes* is no second ...
I want to exception handle 'list index out of range.'
11,902,458
31
2012-08-10T13:15:45Z
11,902,575
7
2012-08-10T13:22:06Z
[ "python", "list", "exception-handling" ]
I am using **BeautifulSoup** and parsing some HTMLs. I'm getting a certain data from each HTML *(using for loop)* and adding that data to a certain list. The problem is, some of the HTMLs have different format *(and they don't have the data that I want in them)*. So, I was trying to use exception handling and add va...
A ternary will suffice. change: ``` gotdata = dlist[1] ``` to ``` gotdata = dlist[1] if len(dlist) > 1 else 'null' ``` this is a short hand for ``` if len(dlist) > 1: gotdata = dlist[1] else: gotdata = 'null' ```
top values from dictionary
11,902,665
10
2012-08-10T13:26:01Z
11,902,696
17
2012-08-10T13:27:59Z
[ "python", "dictionary" ]
How do I retrive the top 3 list from a dictionary? ``` >>> d {'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4} ``` Expected result: ``` and: 23 only: 21 this: 14 ```
Use [`collections.Counter`](http://docs.python.org/library/collections.html#counter-objects): ``` >>> d = Counter({'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4}) >>> d.most_common() [('and', 23), ('only.', 21), ('this', 14), ('test', 4), ('a', 2), ('is', 2), ('work', 2)...
top values from dictionary
11,902,665
10
2012-08-10T13:26:01Z
11,902,719
10
2012-08-10T13:28:57Z
[ "python", "dictionary" ]
How do I retrive the top 3 list from a dictionary? ``` >>> d {'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4} ``` Expected result: ``` and: 23 only: 21 this: 14 ```
``` >>> d = {'a': 2, 'and': 23, 'this': 14, 'only.': 21, 'is': 2, 'work': 2, 'will': 2, 'as': 2, 'test': 4} >>> t = sorted(d.iteritems(), key=lambda x:-x[1])[:3] >>> for x in t: ... print "{0}: {1}".format(*x) ... and: 23 only.: 21 this: 14 ```
regex Python match large list of strings
11,902,865
10
2012-08-10T13:37:03Z
11,902,995
10
2012-08-10T13:44:37Z
[ "python", "regex" ]
I have a large list of strings which include whitespaces in them (e.g. "New York", "United States", "North Carolina", "United Arab Emirates", "United Kingdom of Great Britain and Northern Ireland" ...and around 5000+ such strings). And I have a large text in which may include any of these these strings *(e.g. "I went ...
``` whitespaces_list=['New York','United States', 'United Arab Emirates'] large_text="I went to New York on my way to North Carolina, and eventually will be going to United Arab Emirates." for i in whitespaces_list: if i in large_text: print i," Exist in Large text" ``` are you looking for something like t...
Python dictionary comprehension very slow
11,903,325
12
2012-08-10T14:03:46Z
11,903,424
13
2012-08-10T14:08:51Z
[ "python", "list", "dictionary" ]
I have a dictionary `d1` and a list `l1`. The dictionary keys are strings, and the values are Objects I have defined myself. If it helps, I can describe the Object in more detail but for now, the objects have a list attribute `names`, and some of the elements of `name` may or may not appear in `l1`. What I wanted to ...
You are effectively computing the set intersection of each list occuring in the dictionary values with the list `l1`. Using lists for set intersections is rather inefficient because of the linear searches involved. You should turn `l1` into a set and use `set.intersection()` or set membership tests instead (depending o...
Python - returning from a Tkinter callback
11,903,596
4
2012-08-10T14:17:57Z
11,907,627
7
2012-08-10T18:55:47Z
[ "python", "callback", "tkinter", "return" ]
How can I get a returned object (or variable, or whatever - they're all basically the same, aren't they) from a function that is executed as a Tkinter callback? ``` import Tkinter as Tk from functools import partial def square(x): return x*x root = Tk.Tk() var = Tk.IntVar(root, value=0) #the variable the gets pa...
The notion of "returning" values from callbacks doesn't make sense in the context of an event driven program. Callbacks are called as the result of an event, so there's nowhere to return a value to. As a general rule of thumb, your callbacks should always call a function, rather than using `functools.partial` or `lamb...
how to get image size (bytes) using PIL
11,904,083
7
2012-08-10T14:46:56Z
11,904,141
9
2012-08-10T14:49:35Z
[ "python", "python-imaging-library", "tornado", "filesize" ]
In the forums I've searched, I've found out how to use PIL to get the image dimensions, but not the file size in bytes. I need to know the file size to decide if the file is too big to be uploaded to the database.
Try: ``` import os print os.stat('somefile.ext').st_size ```
Configuring django settings to work with 1.4.1. Loading template error
11,904,609
14
2012-08-10T15:17:07Z
11,904,746
26
2012-08-10T15:25:18Z
[ "python", "django", "django-templates", "osqa" ]
Here is the error I got: ``` ImproperlyConfigured: Error importing template source loader django.template.loaders.filesystem.load_template_source: "'module' object has no attribute 'load_template_source'" ``` Here is my loader template code: ``` if DEBUG: TEMPLATE_LOADERS = [ 'django.template.loaders.filesys...
If you look at the documentation on [template loader types](https://docs.djangoproject.com/en/dev/ref/templates/api/#loader-types) (scroll down to the cached template loader section), it looks like when you configure the cached loader you still need to pass it `Loader` classes - so you'd want to change your config to l...
How to get the module from which the currently executing function was called?
11,904,960
6
2012-08-10T15:37:19Z
11,904,986
7
2012-08-10T15:39:36Z
[ "python", "introspection" ]
This is my best solution so far to the problem of accessing the calling module from within a function: ``` import inspect import sys def calling_module(level=0): filename = inspect.stack()[level+2][1] modulename = inspect.getmodulename(filename) try: return sys.modules[modulename] except KeyErr...
I find that the following works well: ``` import inspect def printfunc() stk = inspect.stack()[1] mod = inspect.getmodule(stk[0]) print "Currently in " + mod + "." + stk[3] ``` which I have inside a utility function called something like `printfunc()`
TypeError: __init__() takes exactly 1 argument (3 given) pyXML
11,905,148
3
2012-08-10T15:50:35Z
11,905,190
7
2012-08-10T15:53:31Z
[ "python", "xml", "python-2.4", "pyxml" ]
I've recently started to learn how to use python to parse xml files. I took the tutorial from <http://pyxml.sourceforge.net/topics/howto/node12.html> When I run the following code I get the error: ``` Traceback (most recent call last): File "C:\Users\Name\Desktop\pythonxml\tutorials\pythonxml\pyxml sourceforge\5.1 ...
You've got too many \_ in the name of \_\_init\_\_. The declaration of your constructor should be: ``` def __init__(self, title, number): ``` not: ``` def __init___(self, title, number): ```
point from a list into a dicitonary variable
11,905,188
3
2012-08-10T15:53:19Z
11,905,208
12
2012-08-10T15:55:10Z
[ "python", "python-2.7", "python-2.6", "python-2.x" ]
Assume you have a list ``` a = [3,4,1] ``` I want with this information to point to the dictionary: ``` b[3][4][1] ``` Now, what I need is a routine. After I see the value, to read and write a value inside b's position. I don't like to copy the variable. I want to change variable b's content directly.
Assuming `b` is a nested dictionary, you could do ``` reduce(dict.get, a, b) ``` to access `b[3][4][1]`. For more general object types, use ``` reduce(operator.getitem, a, b) ``` Writing the value is a bit more involved: ``` reduce(dict.get, a[:-1], b)[a[-1]] = new_value ``` All this assumes you don't now the nu...
How do I filter on a field in a related object?
11,905,206
5
2012-08-10T15:55:04Z
11,907,741
11
2012-08-10T19:04:51Z
[ "python", "django", "django-models", "tastypie" ]
If I try to filter on a field in a related object then Tastypie returns an error. For example, running ``` curl -H "Accept: application/json" \ "http://localhost:8080/wordgame/api/v1/rounds/?format=json&players__username=moe" ``` returns "Lookups are not allowed more than one level deep on the 'players' field." ...
Apparently, you need to specifically white-list the relation-spanning lookups in your `filtering` line, like this: ``` class UserResource(ModelResource): class Meta: queryset = User.objects.all() resource_name = 'players' filtering = { 'username': ALL_WITH_RELATIONS, } `...
Getting all combinations of key/value pairs in Python dict
11,905,573
3
2012-08-10T16:17:59Z
11,905,613
11
2012-08-10T16:21:28Z
[ "python", "list", "dictionary", "combinations" ]
This may be a silly question, but given the following dict: ``` combination_dict = {"one": [1, 2, 3], "two": [2, 3, 4], "three": [3, 4, 5]} ``` How would I achieve this list: ``` result_list = [{"one": [1, 2, 3], "two": [2, 3, 4]}, {"one": [1, 2, 3], "three": [3, 4, 5]}, {"two": [2, 3, 4], "three": [3, 4, 5]}] ``` ...
One solution is to use `itertools.combinations()`: ``` result_list = map(dict, itertools.combinations( combination_dict.iteritems(), 2)) ``` **Edit**: Due to [popular demand](http://stackoverflow.com/questions/11905573/getting-all-combinations-of-key-value-pairs-in-python-dict/11905613#comment15849570_11905613), ...
Changing the number of iterations in a for loop
11,905,606
6
2012-08-10T16:21:01Z
11,905,641
8
2012-08-10T16:23:46Z
[ "python", "loops", "for-loop", "range" ]
I have code like this: ``` loopcount = 3 for i in range(1, loopcount) somestring = '7' newcount = int(somestring) loopcount = newcount ``` so what I want is to modify the range of the for 'inside' the loop. I wrote this code expecting the range of the for loop would change to (1,7) during the first loop, bu...
From the `range()` docstring: > range([start,] stop[, step]) -> list of integers > > Return a list containing an arithmetic progression of integers. > range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. > When step is given, it specifies the increment (or decrement). > For example, range(4) returns [...
Changing the number of iterations in a for loop
11,905,606
6
2012-08-10T16:21:01Z
11,905,667
15
2012-08-10T16:26:22Z
[ "python", "loops", "for-loop", "range" ]
I have code like this: ``` loopcount = 3 for i in range(1, loopcount) somestring = '7' newcount = int(somestring) loopcount = newcount ``` so what I want is to modify the range of the for 'inside' the loop. I wrote this code expecting the range of the for loop would change to (1,7) during the first loop, bu...
The range is created based on the value of `loopcount` at the time it is called--anything that happens to loopcount afterwards is irrelevant. What you probably want is a while statement: ``` loopcount = 3 i = 1 while i < loopcount: somestring = '7' loopcount = int(somestring) i += 1 ``` The `while` tests ...
Python requirements for SUDs
11,905,785
2
2012-08-10T16:34:15Z
11,905,854
8
2012-08-10T16:38:50Z
[ "python", "windows-7", "suds" ]
I'm a noob to SOAP and SUDs. I need to install SUDs on a windows 7 machine, on which I have Python 3.2. I haven't heard of anyone installing SUDs in Python 3+. Should I install Python 2.7? Or do I need to go earlier?
If you look under the overview section you can see that **SUDs** was tested on **Python 3.2** under Windows. On this [website](https://bitbucket.org/jurko/suds) you can also find instructions on how to install **SUDs** for Python using `pip`, easy install or from source.
How to import numpy in python shell
11,906,575
7
2012-08-10T17:33:37Z
11,906,601
11
2012-08-10T17:36:11Z
[ "python", "numpy" ]
Can any body help me with this problem: I have tried importing **numpy** in Python but couldn't succeed: ``` >>> import numpy as np x=np.array([[7,8,5],[3,5,7]],np.int32) Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> import numpy as np File "C:\Python27\lib\numpy\__init__....
The message is fairly self-explanatory; your working directory should not be the numpy source directory when you invoke Python; numpy should be installed and your working directory should be anything but the directory where it lives.
Python simulate keydown
11,906,925
17
2012-08-10T18:02:04Z
11,907,114
11
2012-08-10T18:17:54Z
[ "python", "keypress", "keydown", "simulate" ]
After searching for several hours i´m wondering if its possible to simulate a keydown press on the keyboard. For example I want my program to hold the 'x' key down for five seconds so when I run it in notepad it would look like to see something like this: `xxxxxxxxxxxxx`. I tried around with different pieces of code o...
If you're using Python for Windows then there's a very good chance that you have the `win32api` module, which handles hooking into the API for you... ``` >>> import win32api >>> import win32con >>> win32api.keybd_event(win32con.SHIFT_PRESSED, 0, win32con.KEYEVENTF_EXTENDEDKEY, 0) >>> HELLO ``` Does that help? (p.s. y...
Python simulate keydown
11,906,925
17
2012-08-10T18:02:04Z
11,910,555
23
2012-08-10T23:34:29Z
[ "python", "keypress", "keydown", "simulate" ]
After searching for several hours i´m wondering if its possible to simulate a keydown press on the keyboard. For example I want my program to hold the 'x' key down for five seconds so when I run it in notepad it would look like to see something like this: `xxxxxxxxxxxxx`. I tried around with different pieces of code o...
This code should get you started. `ctypes` is used heavily. At the bottom, you will see example code. ``` import ctypes LONG = ctypes.c_long DWORD = ctypes.c_ulong ULONG_PTR = ctypes.POINTER(DWORD) WORD = ctypes.c_ushort class MOUSEINPUT(ctypes.Structure): _fields_ = (('dx', LONG), ('dy', LONG), ...
After I read from a file then write it out again, I am getting Chinese characters
11,907,669
4
2012-08-10T18:59:32Z
11,907,855
13
2012-08-10T19:12:34Z
[ "python", "python-2.7" ]
I am reading all the lines in a file and then writing them out again. When I do this, the file I have written out ends up being mostly Chinese characters. I am not modifying any of the lines at all. This is my Python code: ``` #test.py import os, sys, time import getopt if __name__=='__main__': testFile = None ...
Your original file is in UTF-16 and a byte has been dropped somewhere, resulting in all your characters being off by one byte. ``` $ charinfo "䤀一䤀吀" U+4900 CJK UNIFIED IDEOGRAPH-4900 U+4E00 CJK UNIFIED IDEOGRAPH-4E00 U+4900 CJK UNIFIED IDEOGRAPH-4900 U+5400 CJK UNIFIED IDEOGRAPH-5400 $ charinfo "INIT" U+0049 L...
Python parsing log file to extract events in real time
11,908,919
2
2012-08-10T20:38:24Z
11,909,244
8
2012-08-10T21:05:49Z
[ "python", "linux", "logging" ]
I've a process that is logging messages to a file. I want to implement another process (in Python) that parses these logs (as they are written to the file), filters the lines that I'm interested in and then performs certain actions based on the state of the first process. I was wondering before I go ahead and write s...
No need to run `tail -f`. Plain Python files should work: ``` with open('/tmp/track-this') as f: while True: line = f.readline() if line: print line ``` This thing works almost exactly like `tail -f`. Check it by running in another terminal: ``` echo "more" >> /tmp/track-this # alt-tab here to the te...
Python parsing log file to extract events in real time
11,908,919
2
2012-08-10T20:38:24Z
11,909,303
10
2012-08-10T21:10:13Z
[ "python", "linux", "logging" ]
I've a process that is logging messages to a file. I want to implement another process (in Python) that parses these logs (as they are written to the file), filters the lines that I'm interested in and then performs certain actions based on the state of the first process. I was wondering before I go ahead and write s...
C programs usually seek to the current position to clear any “end of file” flags. But as [@9000 correctly pointed out](http://stackoverflow.com/a/11909244/1468366), python apparently takes care of this, so you can read from the same file repeatedly even if it has reached end of file. You might have to take care of...
How to upload an image with python-tornado from an HTML form?
11,909,397
8
2012-08-10T21:18:18Z
11,911,972
12
2012-08-11T04:44:51Z
[ "python", "tornado", "image-upload" ]
I saw examples that used pycurl, but could not be sure if this is the way to go with? Some examples will help. Thanks.
It's simple: ``` <form action="/file" methods="POST"><!--your code--></form> ``` in Python: ``` class FileHandler(tornado.web.RequestHandler): # get post data file_body = self.request.files['filefieldname'][0]['body'] img = Image.open(StringIO.StringIO(file_body)) img.save("../img/", img.format) ``` ...
How to upload an image with python-tornado from an HTML form?
11,909,397
8
2012-08-10T21:18:18Z
11,913,817
10
2012-08-11T10:15:43Z
[ "python", "tornado", "image-upload" ]
I saw examples that used pycurl, but could not be sure if this is the way to go with? Some examples will help. Thanks.
Here is [demo application](https://github.com/vamsiikrishna/tornado-upload) that implements tornado upload. Here is server code: ``` import tornado.httpserver, tornado.ioloop, tornado.options, tornado.web, os.path, random, string from tornado.options import define, options define("port", default=8888, help="run on t...
Pygame: key.get_pressed() does not coincide with the event queue
11,910,410
2
2012-08-10T23:15:39Z
11,930,034
7
2012-08-13T07:42:38Z
[ "python", "pygame", "movement" ]
I'm attempting to work out simple controls for an application using pygame in Python. I have got the basics working, but I'm hitting a weird wall: I am using the arrow keys to control my character. If I hold down one arrow key, then hold down another arrow key (to move diagonally), the character moves as expected. Howe...
For things like movement, you should not check for events (like `KEYDOWN` or `KEYUP`), but check every iteration of your mainloop if your movement keys are pressed (using [`get_pressed`](http://www.pygame.org/docs/ref/key.html#pygame.key.get_pressed)). In your code, you check the pressed keys only if there's also a `K...
Best Machine Learning package for Python 3x?
11,910,481
17
2012-08-10T23:24:42Z
11,910,601
10
2012-08-10T23:43:53Z
[ "python", "python-3.x", "machine-learning", "scikit-learn" ]
I was bummed out to see that scikit-learn does not support Python 3...Is there a comparable package anyone can recommend for Python 3?
Try either of these, both are supported by python 3 1. <http://mdp-toolkit.sourceforge.net/> 2. <http://mlpy.sourceforge.net/>
Best Machine Learning package for Python 3x?
11,910,481
17
2012-08-10T23:24:42Z
11,912,783
12
2012-08-11T07:12:25Z
[ "python", "python-3.x", "machine-learning", "scikit-learn" ]
I was bummed out to see that scikit-learn does not support Python 3...Is there a comparable package anyone can recommend for Python 3?
if you look for scikits-learn on Windows there are [binary installers for 3.2 32&64 bits](http://www.lfd.uci.edu/~gohlke/pythonlibs/#scikit-learn)
sqlite3 writes only floating-point numpy arrays not integer ones
11,910,584
4
2012-08-10T23:40:39Z
11,911,418
7
2012-08-11T02:34:47Z
[ "python", "sqlite", "numpy" ]
I am able to save Numpy arrays with floating point numbers to sqlite3, but not arrays with integers: ``` import sqlite3 import numpy as np db = sqlite3.connect('database.db') database = db.cursor() database.execute("CREATE TABLE table_name " "(round INT, id INT, PRIMARY KEY(round, id))") row_to_write = np.a...
Numpy is using some custom integer data types to efficiently pack data into memory. Since these types aren't familiar to sqlite, you'll have to tell it about how to handle them, beforehand: ``` >>> for t in (np.int8, np.int16, np.int32, np.int64, ... np.uint8, np.uint16, np.uint32, np.uint64): ... sqlite...
Python Arpabet phonetic transcription
11,911,028
5
2012-08-11T01:05:46Z
14,431,734
9
2013-01-21T02:31:45Z
[ "python" ]
Is there a library in python that can convert words (mainly names) to Arpabet phonetic transcription? BARBELS -> B AA1 R B AH0 L Z BARBEQUE -> B AA1 R B IH0 K Y UW2 BARBEQUED -> B AA1 R B IH0 K Y UW2 D BARBEQUEING -> B AA1 R B IH0 K Y UW2 IH0 NG BARBEQUES -> B AA1 R B IH0 K Y UW2 Z
What you want is variously called "letter to sound" or "grapheme to phoneme" engine. There are a few around, including one in every text-to-speech system. I usually deal with non-US accents, for which I use [espeak](http://espeak.sourceforge.net/). It doesn't output arpabet directly (which is restricted to US sounds a...
Python: Jaccard Distance using word intersection but not character intersection
11,911,252
3
2012-08-11T01:56:51Z
11,911,276
7
2012-08-11T02:01:35Z
[ "python", "set", "intersection" ]
I didn't realize the that Python set function actually separating string into individual characters. I wrote python function for Jaccard and used python intersection method. I passed two sets into this method and before passing the two sets into my jaccard function I use the set function on the setring. example: assum...
Try splitting your string into words first: ``` word_set = set(your_string.split()) ``` Example: ``` >>> word_set = set("NEW Fujifilm 16MP 5x".split()) >>> character_set = set("NEW Fujifilm 16MP 5x") >>> word_set set(['NEW', '16MP', '5x', 'Fujifilm']) >>> character_set set([' ', 'f', 'E', 'F', 'i', 'M', 'j', 'm', 'l...
TF*IDF for Search Queries
11,911,469
9
2012-08-11T02:44:49Z
11,913,695
11
2012-08-11T09:58:52Z
[ "python", "nlp", "nltk", "scikit-learn", "tf-idf" ]
Okay, so I have been following these two posts on TF\*IDF but am little confused : <http://css.dzone.com/articles/machine-learning-text-feature> Basically, I want to create a search query that contains searches through multiple documents. I would like to use the scikit-learn toolkit as well as the NLTK library for Pyt...
You're defining `train_set` and `test_set` as tuples, but I think that they should be lists: ``` train_set = ["The sky is blue.", "The sun is bright."] #Documents test_set = ["The sun in the sky is bright."] #Query ``` Using this the code seems to run fine.
Python PIL has no attribute 'Image'
11,911,480
8
2012-08-11T02:46:32Z
11,911,536
9
2012-08-11T02:59:38Z
[ "python", "import", "python-imaging-library" ]
I'm using python2.6 and got a problem this morning. It said 'module' has no attribute 'Image'. Here is my input. Why the first time I can not use PIL.Image? ``` >>> import PIL >>> PIL.Image Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'module' object has no attribute 'Image'...
PIL's `__init__.py` is just an empty stub as is common. It won't magically import anything by itself. When you do `from PIL import Image` it looks in the PIL package and finds the file Image.py and imports that. When you do `PIL.Image` you are actually doing an attribute lookup on the PIL module (which is just an empt...
Does an equivalent of override exist for nested functions?
11,911,544
6
2012-08-11T03:00:43Z
11,912,076
9
2012-08-11T05:07:29Z
[ "python", "function", "nested", "override" ]
If I have this function, what should I do to replace the inner function with my own custom version? ``` def foo(): def bar(): # I want to change this pass # here starts a long list of functions I want to keep unchanged def baz(): pass ``` Using classes this would be easily done ov...
Here's one way of doing it, creating a new foo that "does the right thing" by hacking the function internals. ( As mentioned by @DSM ). Unfortunately we cant just jump into the `foo` function and mess with its internals, as they're mostly marked read only, so what we have to do is modify a copy we construct by hand. `...
remove last element in a dictionary of lists in python
11,912,097
3
2012-08-11T05:10:42Z
11,912,105
7
2012-08-11T05:12:09Z
[ "python", "dictionary" ]
What's a more pythonic or efficent way of removing the last element of each list, in a dictionary of lists? For example, take this: ``` listDict = {'tom': [-2,10,2,-8], 'sam': [-9,-10,-10,-7]} ``` And transform it into this: ``` listDict = {'tom': [-2,10,2], 'sam': [-9,-10,-10]} ``` This is what I'm currently doin...
I would use a dictionary comprehension: ``` new_dict = {key: value[:-1] for key, value in listDict.items()} ``` For older Python versions you'll have to use the `dict()` constructor: ``` new_dict = dict((key, value[:-1]) for key, value in listDict.items()) ```
Difference between a and a[:] in a loop
11,912,749
2
2012-08-11T07:06:51Z
11,912,764
14
2012-08-11T07:08:54Z
[ "python", "for-loop" ]
The following code snippets generate different output in Python: ``` a = ['b','c'] for x in a: a.insert(0,'d') ``` The loop does not terminate and the python shell hangs. While, ``` a = ['b','c'] for x in a[:]: a.insert(0,'d') print a ``` generates the following : `['d','d','b','c']` for python 2.6.6 Can an...
In the first example, you add to the list while you iterate over it. It never stops because you keep making the list longer as you go, so it can never get to the end. In the second example `a[:]` is a copy of the list. You can iterate over the copy while appending to the original just fine.
python: how to convert a query string to json string?
11,912,843
8
2012-08-11T07:21:06Z
11,912,899
26
2012-08-11T07:31:40Z
[ "python", "json" ]
I want to convert such query string: ``` a=1&b=2 ``` to json string ``` {"a":1, "b":2} ``` Any existing solution?
``` import json import urlparse json.dumps(urlparse.parse_qs("a=1&b=2")) ``` yields ``` '{"a": ["1"], "b": ["2"]}' ``` This is actually better than your `{"a":1, "b":2}`, because URL query strings can legally contain the same key multiple times, i.e. multiple values per key.
StringIO in python3
11,914,472
91
2012-08-11T11:53:30Z
11,970,414
36
2012-08-15T13:44:25Z
[ "python", "numpy", "python-3.x", "io", "python-3.2" ]
I am using python 3.2.1 and I can't import the `StringIO` module. I use `io.StringIO` and it works but i can't use it with `numpy`'s `genfromtxt` like this: ``` x="1 3\n 4.5 8" numpy.genfromtxt(io.StringIO(x)) ``` I get the following error: ``` TypeError: Can't convert 'bytes' object to str implicitly ``` a...
On Python 3 `numpy.genfromtxt` expects a bytes stream. Use the following: ``` numpy.genfromtxt(io.BytesIO(x.encode())) ```
StringIO in python3
11,914,472
91
2012-08-11T11:53:30Z
18,284,900
159
2013-08-17T03:43:30Z
[ "python", "numpy", "python-3.x", "io", "python-3.2" ]
I am using python 3.2.1 and I can't import the `StringIO` module. I use `io.StringIO` and it works but i can't use it with `numpy`'s `genfromtxt` like this: ``` x="1 3\n 4.5 8" numpy.genfromtxt(io.StringIO(x)) ``` I get the following error: ``` TypeError: Can't convert 'bytes' object to str implicitly ``` a...
From [What’s New In Python 3.0](http://docs.python.org/3.0/whatsnew/3.0.html): > The `StringIO` and `cStringIO` modules are gone. Instead, import the `io` > module and use `io.StringIO` or `io.BytesIO` for text and data > respectively. Example, compatible with both Python2 and Python3: ``` try: from StringIO i...
python using sqlalchemy store a list into sql database
11,914,666
3
2012-08-11T12:24:10Z
11,915,539
7
2012-08-11T14:30:48Z
[ "python", "sqlalchemy" ]
The brief code is like this: ``` class Word(Base): __tablename__ = 'word' eng = Column(String(32),primary_key=True) chinese = Column(String(128)) word = Word(eng='art',chinese=[u'艺术',u'美术']) session.add(word) session.commit() ``` I'm trying to store wor...
To store a list in a db you could use a new table: ``` class Word(Base): __tablename__ = "words" id = Column(Integer, primary_key=True) eng = Column(String(32), unique=True) chinese = relationship("Chinese", backref="eng") def __init__(self, eng, chinese): self.eng = eng self.chin...
How to convert python .py file into an executable file for use cross platform?
11,915,462
6
2012-08-11T14:20:52Z
11,915,518
8
2012-08-11T14:27:51Z
[ "python", "exe", "py2exe", "cx-freeze", "pyinstaller" ]
I've been searching through SO for a while now trying to come up with an answer to this but due to my inexperience with programming I don't understand much of the documentation, nor am I confident enough to experiment too much. Would anyone be able to describe in slightly simpler terms how I would use programs like Py...
There are two distinct ways of freezing python scripts to executables: 1. Packing interpreter and \*.pyc files into one exe file-container. Such approach is used by tools like [PyInstaller](http://www.pyinstaller.org/), [Py2exe](http://www.py2exe.org/), [cx\_freeze](http://cx-freeze.sourceforge.net/). 2. Creating nati...
Import Error: Missing DLL on Windows 7 when trying to import Python module
11,916,267
4
2012-08-11T16:17:40Z
11,918,573
22
2012-08-11T23:44:16Z
[ "python", "python-3.x", "importerror", "scikit-learn" ]
Details: Python 3.2 (32 bit install) Windows 7 64 bit Code inducing the error: ``` from sklearn import svm ``` Error: ``` Traceback (most recent call last): File "C:\Users\chrismv48\workspace\Python Datamining\Biological_Response.py", line 1, in <module> from sklearn import svm File "C:\Python32\lib\site-p...
In case you are using the binaries from <http://www.lfd.uci.edu/~gohlke/pythonlibs/#scikit-learn>. They require [numpy-MKL](http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy), as indicated on the download page. The official numpy binaries won't work.
double quotes in string representation
11,917,043
10
2012-08-11T19:33:17Z
11,917,093
7
2012-08-11T19:40:53Z
[ "python", "python-2.7" ]
This snippet: ``` formatter = "%r %r %r %r" print formatter % ( "I had this thing.", "That you could type up right.", "But it didn't sing.", "So I said goodnight." ) ``` when run, prints this string: ``` 'I had this thing.' 'That you could type up right.' "But it didn't sing." 'So I said goodnight.' ...
Python is clever; it'll use double quotes for strings that contain single quotes when generating the representation, to minimize escapes: ``` >>> 'no quotes' 'no quotes' >>> 'one quote: \'' "one quote: '" ``` Add a double quote in there *as well* and it'll revert back to single quotes and escape any single quotes con...
How do I print out the full url with tweepy?
11,917,184
8
2012-08-11T19:56:51Z
11,917,231
8
2012-08-11T20:04:06Z
[ "python", "tweepy" ]
How do I print out the full urls in tweepy (rather than the t.co link)? The following code prints out "this is a test link <http://t.co/93Hme7Jv> 90210", even though twitter.com shows "this is a test link <http://www.test.com/test> 90210". ``` import tweepy, random consumer_key="my_key" consumer_secret="my_secret" ac...
Not sure how that'd work with tweepy, but you want to set [`include_entities`](https://dev.twitter.com/docs/tweet-entities) to True, and the Twitter API will include the full URLs of `t.co` URLs with responses. Probably something like: ``` for status in tweepy.Cursor(status.user_timeline, id=user, include_entities=Tr...
pip install bitarray
11,917,350
4
2012-08-11T20:20:53Z
11,917,372
13
2012-08-11T20:24:34Z
[ "python", "pip" ]
Running `pip install bitarray` results in a fatal error for me: ``` bitarray/_bitarray.c:9:20: fatal error: Python.h: No such file or directory ``` I'm running an **Ubuntu 12.04 upgrade**. Perhaps I missed installing some dependencies? Running Python works: ``` Python 2.7.3 (default, Aug 1 2012, 05:16:07) [GCC 4....
At the very least, you will need the python-dev package ``` sudo apt-get install python-dev ```
how to annotate heatmap with text in matplotlib?
11,917,547
18
2012-08-11T20:48:47Z
11,918,066
33
2012-08-11T22:10:18Z
[ "python", "numpy", "matplotlib", "scipy" ]
I am plotting a heatmap in matplotlib using: `plt.pcolor(rand(5,5))` how can I annotate the heatmap with the actual numbers plotted? meaning in each cell of the plotted heatmap, put the value corresponding to that cell in the 5x5 matrix passed to `pcolor`. thanks.
There is no automatic feature to do such a thing, but you could loop through each point and put text in the appropriate location: ``` import matplotlib.pyplot as plt import numpy as np data = np.random.rand(5, 4) heatmap = plt.pcolor(data) for y in range(data.shape[0]): for x in range(data.shape[1]): plt...
how to plot and annotate hierarchical clustering dendrograms in scipy/matplotlib
11,917,779
28
2012-08-11T21:24:11Z
12,311,618
12
2012-09-07T04:13:46Z
[ "python", "numpy", "matplotlib", "scipy", "dendrogram" ]
I'm using `dendrogram` from `scipy` to plot hierarchical clustering using `matplotlib` as follows: ``` mat = array([[1, 0.5, 0.9], [0.5, 1, -0.5], [0.9, -0.5, 1]]) plt.subplot(1,2,1) plt.title("mat") dist_mat = mat linkage_matrix = linkage(dist_mat, "single") print "l...
I think there's a couple misunderstandings as to the use of the functions that you are trying to use. Here's a fully working code snippet to illustrate my points: ``` import matplotlib.pyplot as plt from scipy.cluster.hierarchy import dendrogram, linkage from numpy import array import numpy as np mat = array([184, 2...
how to plot and annotate hierarchical clustering dendrograms in scipy/matplotlib
11,917,779
28
2012-08-11T21:24:11Z
12,311,782
49
2012-09-07T04:34:39Z
[ "python", "numpy", "matplotlib", "scipy", "dendrogram" ]
I'm using `dendrogram` from `scipy` to plot hierarchical clustering using `matplotlib` as follows: ``` mat = array([[1, 0.5, 0.9], [0.5, 1, -0.5], [0.9, -0.5, 1]]) plt.subplot(1,2,1) plt.title("mat") dist_mat = mat linkage_matrix = linkage(dist_mat, "single") print "l...
The input to `linkage()` is either an n x m array, representing n points in m-dimensional space, or a one-dimensional array containing the [*condensed* distance matrix](http://stackoverflow.com/questions/13079563/how-does-condensed-distance-matrix-work-pdist). In your example, `mat` is 3 x 3, so you are clustering thre...
Python: UnicodeDecodeError: 'utf8' codec can't decode byte
11,918,512
10
2012-08-11T23:32:41Z
11,918,923
8
2012-08-12T00:58:48Z
[ "python", "encoding", "utf-8", "scikit-learn" ]
I'm reading a bunch of RTF files into python strings. On SOME texts, I get this error: ``` Traceback (most recent call last): File "11.08.py", line 47, in <module> X = vectorizer.fit_transform(texts) File "C:\Python27\lib\site-packages\sklearn\feature_extraction\text.py", line 716, in fit_transform X = sup...
This will solve your issues: ``` import codecs f = codecs.open(dir+location, 'r', encoding='utf-8') txt = f.read() ``` from that moment txt is in unicode format and you can use it everywhere in your code. If you want to generate UTF-8 files after your processing do: ``` f.write(txt.encode('utf-8')) ```
Python: Change values in dict of nested dicts using items in a list
11,918,852
5
2012-08-12T00:39:34Z
11,919,150
8
2012-08-12T02:01:29Z
[ "python", "recursion", "dictionary", "nested", "list-comprehension" ]
How would you modify/create keys/values in a dict of nested dicts based on the values of a list, in which the last item of the list is a value for the dict, and the rest of items reefer to keys within dicts? This would be the list: ``` list_adddress = [ "key1", "key1.2", "key1.2.1", "value" ] ``` This would only be a...
One-liner: ``` keys, (newkey, newvalue) = list_address[:-2], list_address[-2:] reduce(dict.__getitem__, keys, dict_nested)[newkey] = newvalue ``` Note: `dict.get` and `operator.getitem` would produce wrong exceptions here. An explicit for-loop as in [Joel Cornett's answer](http://stackoverflow.com/a/11918901/4279) m...
How do I create a dictionary from two parallel strings?
11,918,909
2
2012-08-12T00:55:08Z
11,918,917
7
2012-08-12T00:56:57Z
[ "python", "dictionary" ]
I have two text files, which are formatted like so: ``` foo,bar,etc ``` the other one is like this: ``` 1,2,3 ``` and I want to put these two text files into one dictionary for Python without having to do each one by hand. I want the output to connect the strings to the numbers. Is there any way of doing this?
``` keys = first_string.split(',') values = second_string.split(',') output_dict = dict(zip(keys, values)) ``` --- ``` >>> first_string = "foo,bar,etc" >>> second_string = "1,2,3" >>> keys = first_string.split(',') >>> values = second_string.split(',') >>> output_dict = dict(zip(keys, values)) >>> output_dict {'etc':...
Key Listeners in python?
11,918,999
4
2012-08-12T01:20:35Z
11,919,074
9
2012-08-12T01:39:43Z
[ "python", "keylistener" ]
Is there a way to do key listeners in python without a huge bloated module such as pygame? An example would be, when I pressed the 'a' key it would print to the console 'The a key was pressed!' Edit: this was intended so it could listen for the arrow keys/spacebar/shift key, sorry for the vagueness Much Appreciated!
It's unfortunately not so easy to do that. If you're trying to make some sort of text user interface, you may want to look into [`curses`](http://docs.python.org/library/curses.html). If you want to display things like you normally would in a terminal, but want input like that, then you'll have to work with [`termios`]...
Key Listeners in python?
11,918,999
4
2012-08-12T01:20:35Z
23,098,294
7
2014-04-16T03:08:24Z
[ "python", "keylistener" ]
Is there a way to do key listeners in python without a huge bloated module such as pygame? An example would be, when I pressed the 'a' key it would print to the console 'The a key was pressed!' Edit: this was intended so it could listen for the arrow keys/spacebar/shift key, sorry for the vagueness Much Appreciated!
Here's how can do it on Windows: ``` """ Display series of numbers in infinite loop Listen to key "s" to stop Only works on Windows because listening to keys is platform dependent """ # msvcrt is a windows specific native module import msvcrt import time # asks whether a key has been acquired def k...
How to debug an application without using an IDE and without understanding of the program flow?
11,919,018
3
2012-08-12T01:25:35Z
11,919,082
8
2012-08-12T01:41:40Z
[ "python", "debugging", "google-app-engine", "syntax-error", "datastore" ]
I'm trying to modify the code of naive bayes classifier provided by the excellent book [Programming Collective Intelligence](http://rads.stackoverflow.com/amzn/click/0596529325), adapting it to the GAE datastore (the provided code uses pysqlite2). But trying to do it, I'm encountering an error difficult to debug. The e...
You've got a type error which should be simple to find but you seem to be making a false choice between running it on a deployment server or in your IDE. There is a [GAE development server](https://developers.google.com/appengine/docs/python/tools/devserver) which you run locally and it simulates the deployment enviro...
How to change the path of Python in Spyder?
11,919,615
17
2012-08-12T03:59:32Z
12,355,200
24
2012-09-10T15:52:44Z
[ "python", "ide", "path", "spyder" ]
I'm using Debian. I installed Python 3.2.3. The path of Python 3 is /usr/bin/python3. How do I change it in Spyder?
Press `CTRL+SHIFT+ALT+P` to open the Preferences window. Within this window, select the `Console` item on the left, then the `Advanced Settings` tab. The path to the Python executable will be right there.
How do I run os.walk in parallel in Python?
11,920,490
17
2012-08-12T07:33:23Z
23,779,787
17
2014-05-21T09:54:37Z
[ "python" ]
I wrote a simple app in Java that takes a list of paths and generates a file with all the file paths under that original list. If I have paths.txt that has: ``` c:\folder1\ c:\folder2\ ... ... c:\folder1000\ ``` My app runs the recursive function on each path multithreaded, and returns a file with all the file paths...
Here is a *multiprocessing* solution: ``` from multiprocessing.pool import Pool from multiprocessing import JoinableQueue as Queue import os def explore_path(path): directories = [] nondirectories = [] for filename in os.listdir(path): fullname = os.path.join(path, filename) if os.path.isd...
Python style for `chained` function calls
11,920,583
6
2012-08-12T07:51:07Z
11,920,726
10
2012-08-12T08:12:49Z
[ "python", "styles" ]
More and more we use chained function calls: ``` value = get_row_data(original_parameters).refine_data(leval=3).transfer_to_style_c() ``` It can be long. To save long line in code, which is prefered? ``` value = get_row_data( original_parameters).refine_data( leval=3).transfer_to_style_c() ``` or: ``` valu...
I tend to prefer the following, which eschews the [non-recommended](http://www.python.org/dev/peps/pep-0008/#maximum-line-length) `\`, thanks to an opening parenthesis: ``` value = (get_row_data(original_parameters) .refine_data(level=3) .transfer_to_style_c()) ``` One advantage of this syntax is that...
Python - can i know if a printing occurred or not
11,920,725
3
2012-08-12T08:12:43Z
11,920,757
9
2012-08-12T08:18:41Z
[ "python", "command-line" ]
I wrote a simple python script. During the script i'm using ``` os.system ("diff file1 file2") ``` to check if two text files are similar or not. I know the files are similar if nothing is being printed out. In case nothing is being printed, i'd like to print out something to the command line like "> the file are sim...
``` >>> import filecmp >>> filecmp.cmp('file1.txt', 'file1.txt') True ``` if `True` then just print message like both are similar [filecmp](http://docs.python.org/library/filecmp.html)- A byte by byte efficient comparison it is
What does Python return when we return with logical operator?
11,920,972
2
2012-08-12T08:54:37Z
11,921,016
11
2012-08-12T09:02:56Z
[ "python", "boolean", "boolean-logic" ]
I was reading someone else's code and he had something like this: ``` return val1 and val2 ``` I tried this in the Python interpreter and it gave me the latter value on AND while OR gives me the prior value. So my question is what exactly is happening in that statement? Thanks.
An expression using `and` or `or` short-circuits when it can determine that the expression will not evaluate to True or False based on the first operand, and returns the last evaluated value: ``` >>> 0 and 'string' 0 >>> 1 and 'string' 'string' >>> 'string' or 10 'string' >>> '' or 10 10 ``` This 'side-effect' is oft...
MySQL and lock a table, read, and then truncate
11,921,366
3
2012-08-12T10:06:09Z
11,921,410
7
2012-08-12T10:13:33Z
[ "python", "mysql", "mysql-python" ]
I am using mysqldb in python. I need to do the following for a table. ``` 1) Lock 2) Read 3) Truncate the table 4) Unlock ``` When I run the below code, I get the below error. So, I am rather unsure on how to lock a table for reading it, then truncating the table. I need to be sure that no other connection reads the...
You can't truncate a table that is locked for writing. This is because "truncate" means "destroy the table, and recreate a new one with the same schema." You can however, *empty* the table. Instead of `TRUNCATE TABLE asin_one_time_only` use `DELETE FROM asin_one_time_only`. Note that this will not reset the autoincrem...
What is the most pythonic way to avoid specifying the same value in a string
11,921,649
8
2012-08-12T10:54:57Z
11,921,662
25
2012-08-12T10:57:08Z
[ "python", "string", "formatting" ]
``` message = "hello %s , how are you %s, welcome %s"%("john","john","john") ``` What is the most pythonic way to avoid specifying "john" 3 times and instead to specify one phrase.
I wouldn't use `%` formatting, `.format` has many advantages. Also `%` formatting was originally planned to be removed with `.format` replacing it, although apparently this hasn't actually happened. > A new system for built-in string formatting operations replaces the `%` string formatting operator. (However, the `%` ...
What is the most pythonic way to avoid specifying the same value in a string
11,921,649
8
2012-08-12T10:54:57Z
11,921,695
11
2012-08-12T11:05:12Z
[ "python", "string", "formatting" ]
``` message = "hello %s , how are you %s, welcome %s"%("john","john","john") ``` What is the most pythonic way to avoid specifying "john" 3 times and instead to specify one phrase.
``` "hello %(name)s , how are you %(name)s, welcome %(name)s" % {"name": "john"} 'hello john, how are you john, welcome john' ``` This is another way to do this without using format.
SqlAlchemy , AttributeError: 'tuple' object has no attribute 'foreign_keys'
11,922,138
5
2012-08-12T12:24:44Z
11,922,163
10
2012-08-12T12:29:57Z
[ "python", "sqlalchemy" ]
I have the following models to describe my database schema: ``` from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.orm import relationship, backref import sqlalchemy.dialects.mysql as mysql Base = declarative_base() class Country(Base): ...
`backref` should be a keyword argument in your declaration of `Competition.teams`: ``` class Competition(Base): # ... teams = relationship('Team', backref="competition") ``` See the [documentation on `relationship`](http://docs.sqlalchemy.org/en/rel_0_7/orm/relationships.html#sqlalchemy.orm.relationship). You...
How to add an outline border to a widget?
11,922,769
4
2012-08-12T14:06:23Z
11,923,125
7
2012-08-12T14:52:41Z
[ "python", "wxpython", "wxwidgets", "wx" ]
How can I add a outline border to a widget in wxpython? (Any widget, for example, a `wx.Button`)
For panel, you can use ``` p = wx.Panel(....., style=wx.SUNKEN_BORDER) ``` there you can choose from constants: ``` wx.SIMPLE_BORDER wx.RAISED_BORDER wx.SUNKEN_BORDER wx.NO_BORDER ``` If you want to create border around `wx.Button`, i would use my custom bitmap with `wx.BitmapButton`: ``` b = wx.BitmapButton(pane,...
Jinja2 and Json
11,922,893
6
2012-08-12T14:21:40Z
11,923,913
11
2012-08-12T16:42:54Z
[ "python", "json", "jinja2" ]
I have for example a JSON File ``` { "Google":{ "Web":"www.web.de", "Apps":{ "Drive": "DriveLink", "Dropbox": "DropboxLink" }, "Google Main":"http://mail.google.com", "G+":"http://plus.google.com" }, "Social":{ "Facebook":"http://www.facebook.de", "G+":"https:/...
The [documentation](http://jinja.pocoo.org/docs/templates) reads: > It is possible to use loops recursively. This is useful if you are > dealing with recursive data such as sitemaps. To use loops recursively > you basically have to add the recursive modifier to the loop > definition and call the loop variable with the...
What is the most Pythonic way to test for match with first item of tuple in sequence of 2-tuples?
11,922,904
4
2012-08-12T14:23:12Z
11,922,913
11
2012-08-12T14:24:28Z
[ "python" ]
Suppose you have a sequence of 2-tuples: ``` seq_of_tups = (('a', 1), ('b', 2), ('c', 3)) ``` and you want to test if `'a'` is the first item of any tuple in the sequence. What is the most Pythonic way? Convert to a dictionary and test for keys, which seems easy enough to understand? i.e. ``` 'a' in dict(seq_of_tu...
``` >>> seq_of_tups = (('a', 1), ('b', 2), ('c', 3)) >>> any(x == 'a' for x, y in seq_of_tups) True ``` For tuples of any size you could use this instead: ``` any(x[0] == 'a' for x in seq_of_tups) ``` Also here are some interesting timings: ``` >python -m timeit -s "seq_of_tups = (('a', 1), ('b', 2), ('c', 3))" ...
Python UnicodeEncodeError, but I have encoded the parameters to UTF-8
11,923,242
3
2012-08-12T15:10:43Z
11,923,324
8
2012-08-12T15:20:41Z
[ "python", "django", "unicode", "md5", "hash" ]
Here is my code: ``` def renren_get_sig(params): cat_params = ''.join([u'%s=%s'%(unicode(k), unicode(params[k])) for k in sorted(params)]) sig = hashlib.md5(u"%s%s"%(unicode(cat_params), unicode(SEC_KEY))).hexdigest() return sig ``` The exception message is: > Exception Type: UnicodeEncodeError > Excep...
Unicode is the problem. Hashing algorithms are designed to be used with bytes, not unicode code points. So you must choose encoding and encode your unicode strings to byte strings before applying hashing algorithm: ``` from hashlib import md5 str_to_hash = unicode_str.encode('utf-8') md5(str_to_hash).hexdigest() ```...
creating django forms
11,923,317
11
2012-08-12T15:19:50Z
11,924,616
25
2012-08-12T18:19:59Z
[ "python", "django", "django-forms" ]
I'm struggling to get my head round django forms.. I've been reading various documentation but just can't quite grasp the concepts. I have got to grips with models, views and templates. What I am trying to do is to create a form with various fields composing of dropdown lists and checkboxes which are populated by value...
Forms are just a tool to simplify and speed-up (the development of) the process of fetching POST data from the request. A manual way would be to do `request.POST.get('somefield')` for all the fields there are in some HTML form. But Django can do better than that... In its essence, a Form class holds a number of Fields...
Django model field default from model method
11,923,581
9
2012-08-12T15:59:38Z
11,923,606
9
2012-08-12T16:02:36Z
[ "python", "django", "model", "default" ]
I want to give a model field default value from the a model method. How can i do that ? when i try this code ``` Class Person(models.Model): def create_id(self): return os.urandom(12).encode('hex') name = models.CharField(max_length = 255) id = models.CharField(max_length = 255,default = self.cr...
You can define global method like this: ``` def create_id(): return os.urandom(12).encode('hex') Class Person(models.Model): name = models.CharField(max_length = 255) id = models.CharField(max_length = 255,default = create_id) ```
How to supply not all default arguments in python?
11,923,645
3
2012-08-12T16:08:21Z
11,923,664
7
2012-08-12T16:10:22Z
[ "python" ]
Lets say i have this code: ``` def dosomething(thing1, thing2=hello, thing3=world): print thing1 print thing2 print thing3 ``` I would like to be able to specify what thing3 is, but wihout having to say what thing2 is. (The code below is how i thought it might work...) ``` dosomething("This says 'hello f...
Use keyword arguments ``` dosomething("This says 'hello fail!'", thing3='fail!') ```
Use Regular Expressions (or another python module) to compare text/characters?
11,924,585
6
2012-08-12T18:16:06Z
11,924,644
13
2012-08-12T18:24:14Z
[ "python", "regex", "string-matching" ]
Let's say that my program receives an input such as a string of characters that has any type of character. For example, 'Bob's Bagel Shop'. Then it gets another string that says 'Fred's Bagel Store'. How can I use regular expressions or some other module in python to compare these and have my program tell me if at leas...
There's a Python standard library class [`difflib.SequenceMatcher`](http://docs.python.org/library/difflib.html#sequencematcher-objects) that will help to solve your problem. Here's a code sample: ``` from difflib import SequenceMatcher s1 = "Bob's Bagel Shop" s2 = "Bill's Bagel Shop" matcher = SequenceMatcher(a=s1,...
How to get rid of double backslash in python windows file path string?
11,924,706
16
2012-08-12T18:32:18Z
11,924,758
8
2012-08-12T18:37:49Z
[ "python", "file", "dictionary", "path" ]
I have a dictionary: ``` my_dictionary = {"058498":"table", "064165":"pen", "055123":"pencil"} ``` I iterate over it: ``` for item in my_dictionary: PDF = r'C:\Users\user\Desktop\File_%s.pdf' %item doIt(PDF) def doIt(PDF): part = MIMEBase('application', "octet-stream") part.set_payload( open(PDF,"rb...
Double backslashes are due to `r`, raw string: ``` r'C:\Users\user\Desktop\File_%s.pdf' , ``` It is used because the `\` might escape some of the characters. ``` >>> strs = "c:\desktop\notebook" >>> print strs #here print thinks that \n in \notebook is the newline char c:\desktop otebook >>> strs = ...
How to get rid of double backslash in python windows file path string?
11,924,706
16
2012-08-12T18:32:18Z
11,924,842
10
2012-08-12T18:48:12Z
[ "python", "file", "dictionary", "path" ]
I have a dictionary: ``` my_dictionary = {"058498":"table", "064165":"pen", "055123":"pencil"} ``` I iterate over it: ``` for item in my_dictionary: PDF = r'C:\Users\user\Desktop\File_%s.pdf' %item doIt(PDF) def doIt(PDF): part = MIMEBase('application', "octet-stream") part.set_payload( open(PDF,"rb...
The double backslash is not wrong, python prints/represents it that to the user way. If `a = r'raw s\tring'` and `b = 'raw s\\tring'` (no 'r' and explicit double slash) then they are both represented as `'raw s\\tring'`. ``` >>> a = r'raw s\tring' >>> b = 'raw s\\tring' >>> a 'raw s\\tring' >>> b 'raw s\\tring' ``` B...
logging errors with flask
11,925,558
6
2012-08-12T20:15:31Z
11,988,068
9
2012-08-16T13:19:34Z
[ "python", "oop", "decorator", "flask", "uwsgi" ]
I'm trying to log an error in a decorator function using `app.logger.error('')`, but it just doesn't work. In addition I cant debug this well and I can only see the response from the http client: *(I'm using nginx+uwsgi+flask)* > HTTP/1.1 502 Bad Gateway > > Server: nginx > > Date: Sun, 12 Aug 2012 15:45:09 GMT > > C...
in fact, the decorator wasnt able to detect the app instance out of context, i solve this using current\_app: 1st. Import the method: `from flask import current_app` 2nd. append any app class to current\_app: `current_app.logger.error('panic !!!')` > info @ <http://flask.pocoo.org/docs/api/#flask.current_app> > > "P...
How to pass a C++ object to another C++ object with Boost.Python
11,926,340
7
2012-08-12T22:25:42Z
11,976,960
7
2012-08-15T20:43:28Z
[ "c++", "python", "boost", "boost-python" ]
I have some C++ code that defines two classes, A and B. B takes an instance of A during construction. I have wrapped A with Boost.Python so that Python can create instances of A, as well as subclasses. I want to do the same with B. ``` class A { public: A(long n, long x, long y) : _n(n), _x(x), _y(y) {}; ...
In short, define `B`'s wrapper as: ``` class_<B>( "B", init< A >() ) ``` instead of ``` class_<B>( "B", init< object >() ) ``` When defining a wrapper for class in Boost.Python (at least in 1.50), the `class_` template generates convert and construct functions. This allows `A` to be converted to and constructed fro...
Declaring a python function with an array parameters and passing an array argument to the function call?
11,926,620
9
2012-08-12T23:19:19Z
11,926,665
10
2012-08-12T23:30:29Z
[ "python", "function", "parameters", "arguments" ]
I am a complete newbie to python and attempting to pass an array as an argument to a python function that declares a list/array as the parameter. I am sure I am declaring it wrong, here goes: ``` def dosomething(listparam): #do something here dosomething(listargument) ``` Clearly this is not working, what ...
What you have is on the right track. ``` def dosomething( thelist ): for element in thelist: print element dosomething( ['1','2','3'] ) alist = ['red','green','blue'] dosomething( alist ) ``` Produces the output: ``` 1 2 3 red green blue ``` A couple of things to note given your comment above: unlike i...
How to get a file object from mkstemp()?
11,926,855
6
2012-08-13T00:11:30Z
11,926,872
7
2012-08-13T00:14:53Z
[ "python", "file" ]
I'm trying to use mkstemp with Python 3: ``` Python 3.2.3 (default, Jun 25 2012, 23:10:56) [GCC 4.7.1] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from tempfile import mkstemp >>> mkstemp() (3, '/tmp/tmp080316') ``` According to the [documentation](http://docs.python.org/dev/...
In the documentation for `mktemp` you can see an example of how to use `NamedTemporaryFile` the way you want: <http://docs.python.org/dev/library/tempfile.html?highlight=mkstemp#tempfile.mktemp> ``` >>> f = NamedTemporaryFile(delete=False) >>> f <open file '<fdopen>', mode 'w+b' at 0x384698> ``` This provides the sam...