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
Why does this division is not performed correctly?
3,851,002
4
2010-10-03T18:24:46Z
3,851,019
15
2010-10-03T18:28:27Z
[ "python", "python-2.x", "division" ]
I've a strange issue in python, the division is not performed correctly: ``` print pointB[1] print pointA[1] print pointB[0] print pointA[0] print (pointB[1]-pointA[1]) / (pointB[0]-pointA[0]) ``` These are the results: ``` 100 50 100 40 0 ``` thanks
The above behavior is true for Python 2. The behavior of `/` was fixed in Python 3. In Python 2 you can use: ``` from __future__ import division ``` and then use `/` to get the result you desire. ``` >>> 5 / 2 2 >>> from __future__ import division >>> 5 / 2 2.5 ``` Since you are dividing two integers, you get the r...
Why does this division is not performed correctly?
3,851,002
4
2010-10-03T18:24:46Z
3,851,024
8
2010-10-03T18:29:48Z
[ "python", "python-2.x", "division" ]
I've a strange issue in python, the division is not performed correctly: ``` print pointB[1] print pointA[1] print pointB[0] print pointA[0] print (pointB[1]-pointA[1]) / (pointB[0]-pointA[0]) ``` These are the results: ``` 100 50 100 40 0 ``` thanks
It is done correctly. 50/60 = 0 Maybe you are looking for 50.0/60.0 = 0.83333333333333337, you can cast your variables to float to get that: ``` print float(pointB[1]-pointA[1]) / (pointB[0]-pointA[0]) ```
Using cython .pxd files to Augment pure python files
3,852,742
6
2010-10-04T03:56:39Z
3,853,593
13
2010-10-04T08:17:51Z
[ "python", "cython" ]
Following the example here, "[Augementing .pxd](http://docs.cython.org/src/tutorial/pure.html?highlight=pxd#augmenting-pxd)", I'm trying to use ".pxd" files to augment a pure python file. (Add type definitions external to the pure python file). python file: ``` class A(object): def foo(self, i=3, x=None): ...
Optional arguments in cpdef functions are declared differently from cdef functions which essentially is same as python functions. Your .pxd file should be modified to be written as ``` cdef class A: cpdef foo(self, int i=*, x=*) ```
Python -Intersection of multiple lists?
3,852,780
21
2010-10-04T04:12:19Z
3,852,792
21
2010-10-04T04:16:22Z
[ "python", "list", "set", "intersection" ]
I am playing with python and am able to get the intersection of two lists: ``` result = set(a).intersection(b) ``` Now if `d` is a list containing `a` and `b` and a third element `c`, is there an built-in function for finding the intersection of all the three lists inside `d`? So for instance, ``` d = [[1,2,3,4], [2...
for 2.4, you can just define an intersection function. ``` def intersect(*d): sets = iter(map(set, d)) result = sets.next() for s in sets: result = result.intersection(s) return result ``` --- for newer versions of python: the intersection method takes an arbitrary amount of arguments ``` r...
Python -Intersection of multiple lists?
3,852,780
21
2010-10-04T04:12:19Z
3,852,806
28
2010-10-04T04:18:50Z
[ "python", "list", "set", "intersection" ]
I am playing with python and am able to get the intersection of two lists: ``` result = set(a).intersection(b) ``` Now if `d` is a list containing `a` and `b` and a third element `c`, is there an built-in function for finding the intersection of all the three lists inside `d`? So for instance, ``` d = [[1,2,3,4], [2...
``` set.intersection(*map(set,d)) ```
Python argparse: How to insert newline in the help text?
3,853,722
153
2010-10-04T08:40:00Z
3,853,776
173
2010-10-04T08:49:57Z
[ "python", "argparse" ]
I'm using [`argparse` in Python 2.7](http://docs.python.org/library/argparse.html) for parsing input options. One of my options is a multiple choice. I want to make a list in its help text, e.g. ``` from argparse import ArgumentParser parser = ArgumentParser(description='test') parser.add_argument('-g', choices=['a'...
Try using `RawTextHelpFormatter`: ``` from argparse import RawTextHelpFormatter parser = ArgumentParser(description='test', formatter_class=RawTextHelpFormatter) ```
Python argparse: How to insert newline in the help text?
3,853,722
153
2010-10-04T08:40:00Z
22,157,136
36
2014-03-03T20:49:56Z
[ "python", "argparse" ]
I'm using [`argparse` in Python 2.7](http://docs.python.org/library/argparse.html) for parsing input options. One of my options is a multiple choice. I want to make a list in its help text, e.g. ``` from argparse import ArgumentParser parser = ArgumentParser(description='test') parser.add_argument('-g', choices=['a'...
If you just want to override the one option, you should not use `RawTextHelpFormatter`. Instead subclass the `HelpFormatter` and provide a special intro for the options that should be handled "raw" (I use `"R|rest of help"`): ``` import argparse class SmartFormatter(argparse.HelpFormatter): def _split_lines(self...
How can I catch SIGINT in threading python program?
3,853,932
10
2010-10-04T09:15:31Z
3,853,966
7
2010-10-04T09:20:49Z
[ "python", "multithreading", "signals", "sigint" ]
When using threading module and Thread() class, SIGINT (Ctrl+C in console) could not be catched. Why and what can I do? Simple test program: ``` #!/usr/bin/env python import threading def test(suffix): while True: print "test", suffix def main(): for i in (1, 2, 3, 4, 5): threading.Thread(...
Threads and signals don't mix. In Python this is even more so the case than outside: signals only ever get delivered to one thread (the main thread); other threads won't get the message. There's nothing you can do to interrupt threads other than the main thread. They're out of your control. The only thing you can do h...
approximate comparison in python
3,854,047
3
2010-10-04T09:37:47Z
3,854,177
18
2010-10-04T10:02:26Z
[ "python", "comparison" ]
I want to make '==' operator use approximate comparison in my program: float values x and y are equal (==) if ``` abs(x-y)/(0.5(x+y)) < 0.001 ``` What's a good way to do that? Given that float is a built-in type, I don't think I can redefine the == operator, can I? Note that I would like to use other features of flo...
You can create a new class deriving from the builtin float type, and then overwrite the necessary operators: ``` class InexactFloat(float): def __eq__(self, other): try: return abs(self.real - other) / (0.5 * (abs(self.real) + abs(other))) < 0.001 except ZeroDivisionError: #...
Runtime model generation using django
3,854,159
4
2010-10-04T10:00:18Z
3,854,284
7
2010-10-04T10:21:18Z
[ "python", "django", "django-models" ]
I have an application that needs to generate its models on runtime. This will be done according to the current database scheme. How can it be done? How can I create classes on runtime in python? Should I create a json representation and save it in a database and then unserialize it into a python object?
You can try to read this <http://code.djangoproject.com/wiki/DynamicModels> Here is example how to create python model class: ``` Person = type('Person', (models.Model,), { 'first_name': models.CharField(max_length=255), 'last_name': models.CharField(max_length=255), }) ``` You can also read about python met...
How to convert a negative number to positive?
3,854,310
41
2010-10-04T10:25:26Z
3,854,323
84
2010-10-04T10:26:48Z
[ "python", "numbers", "absolute-value" ]
How can I convert a negative number to positive in Python? (And keep a positive one.)
``` >>> n = -42 >>> -n # if you know n is negative 42 >>> abs(n) # for any n 42 ``` Don't forget to check the [docs](http://docs.python.org/library/functions.html#abs).
How to convert a negative number to positive?
3,854,310
41
2010-10-04T10:25:26Z
3,854,329
14
2010-10-04T10:27:18Z
[ "python", "numbers", "absolute-value" ]
How can I convert a negative number to positive in Python? (And keep a positive one.)
If "keep a positive one" means you want a positive number to stay positive, but also convert a negative number to positive, use `abs()`: ``` >>> abs(-1) 1 >>> abs(1) 1 ```
How to convert a negative number to positive?
3,854,310
41
2010-10-04T10:25:26Z
14,053,631
19
2012-12-27T11:05:07Z
[ "python", "numbers", "absolute-value" ]
How can I convert a negative number to positive in Python? (And keep a positive one.)
simply multiplying by -1 works in both ways ... ``` >>> -10 * -1 10 >>> 10 * -1 -10 ```
How to distinguish between a sequence and a mapping
3,854,470
5
2010-10-04T10:45:42Z
3,854,667
8
2010-10-04T11:08:54Z
[ "python", "dictionary", "sequence" ]
I would like to perform an operation on an argument based on the fact that it might be a map-like object or a sequence-like object. I understand that no strategy is going to be 100% reliable for type-like checking, but I'm looking for a robust solution. Based on this [answer](http://stackoverflow.com/questions/305359/...
``` >>> from collections import Mapping, Sequence >>> isinstance('ac', Sequence) True >>> isinstance('ac', Mapping) False >>> isinstance({3:42}, Mapping) True >>> isinstance({3:42}, Sequence) False ``` [`collections` abstract base classes (ABCs)](http://docs.python.org/library/collections.html#abcs-abstract-base-class...
Generate password in python
3,854,692
25
2010-10-04T11:13:23Z
3,854,837
19
2010-10-04T11:34:16Z
[ "python", "passwords" ]
I'dl like to generate some alphanumeric passwords in python. Some possible ways are: ``` import string from random import sample, choice chars = string.letters + string.digits length = 8 ''.join(sample(chars,length)) # way 1 ''.join([choice(chars) for i in range(length)]) # way 2 ``` But I don't like both because: *...
Option #2 seems quite reasonable except you could add a couple of improvements: ``` ''.join(choice(chars) for _ in range(length)) # in py2k use xrange ``` `_` is a conventional "I don't care what is in there" variable. And you don't need list comprehension there, generator expression works just fine for `str...
Generate password in python
3,854,692
25
2010-10-04T11:13:23Z
23,012,224
12
2014-04-11T12:12:03Z
[ "python", "passwords" ]
I'dl like to generate some alphanumeric passwords in python. Some possible ways are: ``` import string from random import sample, choice chars = string.letters + string.digits length = 8 ''.join(sample(chars,length)) # way 1 ''.join([choice(chars) for i in range(length)]) # way 2 ``` But I don't like both because: *...
For the crypto-PRNG folks out there: ``` def generate_temp_password(length): if not isinstance(length, int) or length < 8: raise ValueError("temp password must have positive length") chars = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" from os import urandom return "".join(chars[ord(c) % len(chars)] for...
What is for Python what 'explode' is for PHP?
3,854,867
59
2010-10-04T11:38:50Z
3,854,876
91
2010-10-04T11:40:30Z
[ "php", "python", "string" ]
I had a string which is stored in a variable `myvar = "Rajasekar SP"`. I want to split it with delimiter like we do using [`explode`](http://php.net/manual/en/function.explode.php) in PHP. What is the equivalent in Python?
Choose one you need: ``` >>> s = "Rajasekar SP def" >>> s.split(' ') ['Rajasekar', 'SP', '', 'def'] >>> s.split() ['Rajasekar', 'SP', 'def'] >>> s.partition(' ') ('Rajasekar', ' ', 'SP def') ``` [`str.split`](http://docs.python.org/library/stdtypes.html#str.split) and [`str.partition`](http://docs.python.org/librar...
What is for Python what 'explode' is for PHP?
3,854,867
59
2010-10-04T11:38:50Z
3,854,920
12
2010-10-04T11:48:31Z
[ "php", "python", "string" ]
I had a string which is stored in a variable `myvar = "Rajasekar SP"`. I want to split it with delimiter like we do using [`explode`](http://php.net/manual/en/function.explode.php) in PHP. What is the equivalent in Python?
The alternative for explode in php is [split](http://docs.python.org/library/stdtypes.html#str.split). The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace i...
Python: Replacing an element in a list of lists (#2)
3,854,870
7
2010-10-04T11:39:17Z
3,854,904
13
2010-10-04T11:45:15Z
[ "python", "list", "mutable" ]
A previous question with the same title as mine [has been posted](http://stackoverflow.com/questions/2104796/python-replacing-item-in-a-list-of-lists), with (I think) the same question, but had other problems in the code. I was not able to determine if that case was identical to mine or not. Anyway, I want to replace ...
You are having four references to same object by \* 4, use instead list comprehension with range for counting: ``` my_nested_list = [[0,0] for count in range(4)] my_nested_list[1][1] = 5 print(my_nested_list) ``` To explain little more concretely the problem: ``` yourNestedList = [[0,0]]*4 yourNestedList[1][1] = 5 p...
error when exec'ing scp from python
3,855,250
3
2010-10-04T12:34:39Z
3,855,280
9
2010-10-04T12:38:18Z
[ "python", "ssh", "scp" ]
this code is giving following error: ``` os.system("scp %s:/export/home/sample/backup.sql %s:/home/rushi/abc.sql" % (a, b)) Permission denied (publickey,keyboard-interactive). lost connection ``` a and b are the command line arguments which accept user name and machine name as arguments: eg: root@10.88.77.77 .
This has nothing to do with Python and everything to do with SSH. > Permission denied (publickey,keyboard-interactive). It's telling you you have failed to log in. I suggest you either sort your key-based auth out or pass it a password. See: <http://unixhelp.ed.ac.uk/CGI/man-cgi?ssh+1> Or instead of trying to use t...
How to pickle and unpickle instances of a class that inherits from defaultdict?
3,855,428
9
2010-10-04T12:57:23Z
3,855,616
8
2010-10-04T13:24:18Z
[ "python", "pickle" ]
I have a class that inherits from `defaultdict` like this: ``` class listdict(defaultdict): def __init__(self): defaultdict.__init__(self, list) ``` I can pickle it, but when I unpickle it, this happens: ``` ('__init__() takes exactly 1 argument (2 given)', <class 'listdict'>, (<type 'list'>,)) ``` The ...
Types define how instances of it get pickled by defining one or more of a (fairly large) set of methods. Each has its own subtle behaviour. See [the docs on the pickle protocol](http://docs.python.org/library/pickle#the-pickle-protocol). In the case of `collections.defaultdict`, it uses the `__reduce__` method: ``` >>...
Fastest way to sort in Python
3,855,537
5
2010-10-04T13:12:31Z
3,855,569
7
2010-10-04T13:16:47Z
[ "python", "arrays", "performance", "sorting" ]
What is the fastest way to sort an array of whole integers bigger than 0 and less than 100000 in Python? But not using the built in functions like sort. Im looking at the possibility to combine 2 sport functions depending on input size.
Since you know the range of numbers, you can use [Counting Sort](http://en.wikipedia.org/wiki/Counting_sort) which will be linear in time.
Fastest way to sort in Python
3,855,537
5
2010-10-04T13:12:31Z
3,855,607
11
2010-10-04T13:23:29Z
[ "python", "arrays", "performance", "sorting" ]
What is the fastest way to sort an array of whole integers bigger than 0 and less than 100000 in Python? But not using the built in functions like sort. Im looking at the possibility to combine 2 sport functions depending on input size.
If you are interested in **asymptotic time**, then counting sort or radix sort provide good performance. However, if you are interested in **wall clock time** you will need to compare performance between different algorithms using *your particular data sets*, as different algorithms perform differently with different ...
Call Class Method from another Class
3,856,413
13
2010-10-04T14:56:35Z
3,856,502
23
2010-10-04T15:08:03Z
[ "python" ]
So in Python, I am wondering if there is a way to call a class method from another class? I am attempting to spin my own MVC framework in Python and I can not for the life of me figure out how to invoke a method from one class in another class. Below is basically what I want to happen: ``` class A: def method1(ar...
update: Just saw the reference to `call_user_func_array` in your post. that's different. use `getattr` to get the function object and then call it with your arguments ``` class A(object): def method1(self, a, b, c): # foo methodname = 'method1' method = getattr(A, methodname) ``` `method` is now an actua...
Installing the igraph package for python
3,856,820
5
2010-10-04T15:45:33Z
3,889,151
9
2010-10-08T09:10:45Z
[ "python", "igraph" ]
I have downloaded the igraph 0.5.4 tar ball for macosx Leopard 10.5.8. When I unpack it and then run: ``` sudo python setup.py install ``` I get the following long error message: ``` Include path: /usr/include /usr/local/include Library path: running install running bdist_egg running egg_info writing python_igr...
What you have downloaded is only the Python *interface* to the igraph library. The library itself is written in C, and you will have to install the C core of igraph first before trying to compile the Python interface. Basically, you have three choices here: 1. Try to make use of the pre-compiled Mac OS X installer of...
django project directory structure and the python path
3,856,891
5
2010-10-04T15:54:15Z
3,856,947
12
2010-10-04T16:01:43Z
[ "python", "django", "django-models", "pythonpath" ]
I am trying to get the best possible set up for developing my django project from the start and I'm having trouble getting everything to play nicely in the directory structure. I have set up virtualenv's (env in this example) so that I can deploy a clean empty python environment for every django project. The basic str...
You can put the following in your `settings.py` to add your `appsfolder` to your `PYTHONPATH`: ``` import os import sys PROJECT_ROOT = os.path.dirname(__file__) sys.path.insert(0, os.path.join(PROJECT_ROOT, 'appsfolder')) ```
Why is printing to stdout so slow? Can it be sped up?
3,857,052
111
2010-10-04T16:14:35Z
3,857,154
9
2010-10-04T16:24:08Z
[ "python", "linux", "printing", "stdout", "tty" ]
I've always been amazed/frustrated with how long it takes to simply output to the terminal with a print statement. After some recent painfully slow logging I decided to look into it and was quite surprised to find that almost **all** the time spent is waiting for the terminal to process the results. Can writing to std...
Your redirection probably does nothing as programs can determine whether their output FD points to a tty. It's likely that stdout is line buffered when pointing to a terminal (the same as C's [`stdout`](http://linux.die.net/man/3/stdout) stream behaviour). As an amusing experiment, try piping the output to `cat`. --...
Why is printing to stdout so slow? Can it be sped up?
3,857,052
111
2010-10-04T16:14:35Z
3,857,543
99
2010-10-04T17:17:51Z
[ "python", "linux", "printing", "stdout", "tty" ]
I've always been amazed/frustrated with how long it takes to simply output to the terminal with a print statement. After some recent painfully slow logging I decided to look into it and was quite surprised to find that almost **all** the time spent is waiting for the terminal to process the results. Can writing to std...
> How can it be that writing to physical disk is WAY faster than writing to the "screen" (presumably an all-RAM op), and is effectively as fast as simply dumping to the garbage with /dev/null? Congratulations, you have just discovered the importance of I/O buffering. :-) The disk *appears* to be faster, because it is...
Why is printing to stdout so slow? Can it be sped up?
3,857,052
111
2010-10-04T16:14:35Z
3,860,319
56
2010-10-05T01:35:46Z
[ "python", "linux", "printing", "stdout", "tty" ]
I've always been amazed/frustrated with how long it takes to simply output to the terminal with a print statement. After some recent painfully slow logging I decided to look into it and was quite surprised to find that almost **all** the time spent is waiting for the terminal to process the results. Can writing to std...
Thanks for all the comments! I've ended up answering it myself with your help. It feels dirty answering your own question, though. **Question 1: Why is printing to stdout slow?** **Answer:** Printing to stdout is *not* inherently slow. It is the terminal you work with that is slow. And it has pretty much zero to do w...
Decoding if it's not unicode
3,857,763
6
2010-10-04T17:47:27Z
3,858,057
10
2010-10-04T18:29:22Z
[ "python", "unicode", "encoding", "utf-8" ]
I want my function to take an argument that could be an unicode object or a utf-8 encoded string. Inside my function, I want to convert the argument to unicode. I have something like this: ``` def myfunction(text): if not isinstance(text, unicode): text = unicode(text, 'utf-8') ... ``` Is it possible...
You could just try decoding it with the 'utf-8' codec, and if that does not work, then return the object. ``` def myfunction(text): try: text = unicode(text, 'utf-8') except TypeError: return text print(myfunction(u'cer\xf3n')) # cerón ``` When you take a unicode object and call its `decode`...
Numpy Routine for Computing Matrix Minors?
3,858,213
5
2010-10-04T18:52:48Z
3,858,333
16
2010-10-04T19:11:09Z
[ "python", "numpy" ]
I'm interested in using numpy to compute all of the minors of a given square matrix. Is there a slick way of using array slicing to do this? I'm imagining that one can rotate the columns, delete the last column, rotate the rows of the resulting matrix and delete the last row, but I haven't found anything in the numpy d...
``` In [34]: arr=np.random.random((4,4)) In [35]: arr Out[35]: array([[ 0.00750932, 0.47917318, 0.39813503, 0.11755234], [ 0.30330724, 0.67527229, 0.71626247, 0.22526589], [ 0.5821906 , 0.2060713 , 0.50149411, 0.0328739 ], [ 0.42066294, 0.88529916, 0.09179092, 0.39389844]]) ``` This ...
How to use virtualenv with Google App Engine SDK on Mac OS X 10.6
3,858,772
29
2010-10-04T20:14:23Z
5,464,790
15
2011-03-28T20:38:06Z
[ "python", "osx", "google-app-engine", "virtualenv" ]
I am pulling my hair out trying to figure this out because I had it working until last week and somehow it broke. When I setup a virtualenv for a Google App Engine app and start the app with `dev_appserver.py`, I get errors importing the standard library (like "ImportError: No module named base64"). Here's what I'm d...
It's an [issue 4339](http://code.google.com/p/googleappengine/issues/detail?id=4339) with the GAE SDK, it's confirmed and there are two slightly different patches available in the bug entry that make it work. What happens is `dev_appserver.py` sets up a restricted python environment by disallowing access to any non-sy...
Python, get windows special folders for currently logged-in user
3,858,851
13
2010-10-04T20:26:09Z
3,858,957
14
2010-10-04T20:42:29Z
[ "python", "windows", "pywin32" ]
How can I get Windows special folders like My Documents, Desktop, etc. from my Python script? Do I need win32 extensions? It must work on Windows 2000 to Windows 7.
You can do it with the pywin32 extensions: ``` from win32com.shell import shell, shellcon print shell.SHGetFolderPath(0, shellcon.CSIDL_MYPICTURES, None, 0) # prints something like C:\Documents and Settings\Username\My Documents\My Pictures # (Unicode object) ``` Check `shellcon.CSIDL_xxx` for other possible folders....
Python, get windows special folders for currently logged-in user
3,858,851
13
2010-10-04T20:26:09Z
3,859,336
13
2010-10-04T21:36:42Z
[ "python", "windows", "pywin32" ]
How can I get Windows special folders like My Documents, Desktop, etc. from my Python script? Do I need win32 extensions? It must work on Windows 2000 to Windows 7.
Should you wish to do it without the win32 extensions, you can use `ctypes` to call [SHGetFolderPath](http://msdn.microsoft.com/en-us/library/bb762181%28VS.85%29.aspx): ``` >>> import ctypes.wintypes >>> CSIDL_PERSONAL= 5 # My Documents >>> SHGFP_TYPE_CURRENT= 0 # Want current, not default value >>> buf= ctyp...
Preventing window overlap in GTK
3,859,045
4
2010-10-04T20:57:29Z
3,859,540
12
2010-10-04T22:10:23Z
[ "python", "gtk", "x11", "dock", "ewmh" ]
I've got a Python/Linux application that displays bits of info I need in a GTK window. For the purposes of this discussion, it should behave exactly like a dock - exists on all virtual desktops, and maximized windows do not overlap it. The first point is pretty easy, but I have spent days bashing my head against my mo...
Use [`_NET_WM_STRUT`](http://standards.freedesktop.org/wm-spec/wm-spec-1.3.html#id2507592) and [`_NET_WM_STRUT_PARTIAL`](http://standards.freedesktop.org/wm-spec/wm-spec-1.3.html#id2507618) (for backwards compatibility) properties to reserve space at the edge of X Window System desktop. With PyGtk you can set these pr...
Choosing multicast network interface in Python
3,859,090
5
2010-10-04T21:04:48Z
6,102,513
7
2011-05-23T20:16:39Z
[ "python", "sockets", "networking" ]
I have a server with two separate Ethernet connections. When I bind a socket in python it defaults to one of the two networks. How do I pull a multicast stream from the second network in Python? I have tried calling bind using the server's IP address on the second network, but that hasn't worked.
I recommend you don't use INADDR\_ANY. In production multicast environments you want to be very specific with your multicast sockets and don't want to be doing things like sending igmp joins out all interfaces. This leads to hack-job workarounds when things aren't working like "route add -host 239.1.1.1 dev eth3" to ge...
How to add http headers in WSGI middleware?
3,859,097
6
2010-10-04T21:05:46Z
3,859,300
17
2010-10-04T21:33:04Z
[ "python", "wsgi" ]
How can http headers be added within a WSGI middleware?
I've found a nice example from the [pylons book](http://pylonsbook.com/en/1.1/the-web-server-gateway-interface-wsgi.html#changing-the-status-and-headers). ``` class Middleware(object): def __init__(self, app): self.app = app def __call__(self, environ, start_response): def custom_start_respon...
create 2d array in python?
3,859,301
2
2010-10-04T21:33:05Z
3,859,445
10
2010-10-04T21:56:03Z
[ "python" ]
this is the code i am trying to create the 2d matrix ``` m=4 tagProb=[[]]*(m+1) count=0 index=0 for line in lines: print(line) if(count < m+1): tagProb[index].append(line.split('@@')[2].strip()) count+=1 if(count == m+1): // this check to goto next index count = 0 index+=1 pr...
You are using `*` on lists, which has a gotcha -- it will make a list of lots of references to the *same* object. This is fine for immutables like `int`s or `tuple`s, but not for mutables like `list`, because changing one of the objects will change all of them. See: ``` >>> foo = [[]]*10 >>> foo[0].append(1) >>> foo [...
custom comparison for built-in containers
3,860,009
5
2010-10-04T23:55:28Z
3,860,102
9
2010-10-05T00:23:49Z
[ "python", "comparison" ]
In my code there's numerous comparisons for equality of various containers (list, dict, etc.). The keys and values of the containers are of types float, bool, int, and str. The built-in == and != worked perfectly fine. I just learned that the floats used in the values of the containers must be compared using a custom ...
The only route to altering the way built-in containers check equality is to make them contain as values, instead of the "originals", *wrapped* values (wrapped in a class that overrides `__eq__` and `__ne__`). This is if you need to alter the way the containers themselves use equality checking, e.g. for the purpose of t...
Generate a list of length n with m possible elements
3,860,267
3
2010-10-05T01:19:20Z
3,860,325
7
2010-10-05T01:37:34Z
[ "python", "permutation", "combinations", "itertools" ]
I need to generate a ton of lists in Python. Every list is of length 13, and I have 4 possible values that can go into each element. These are [1, -1, i, -i], but it could be whatever. Thus I should get 4 \* 4 \* 4 ... \* 4 = 4^13 = 67,108,864 lists, or more generally, m^n, given the info in the subject. I tried the ...
I think you want ``` y = itertools.product((1, -1, 1j, -1j), repeat=13) ``` Then, btw, `print sum(1 for x in y)` prints, `67108864`, as you expect.
about python datetime type
3,860,482
2
2010-10-05T02:31:34Z
3,860,503
13
2010-10-05T02:37:23Z
[ "python", "datetime", "types" ]
What's the equivalent type in types module for datetime? Example: ``` import datetime import types t=datetime.datetime.now() if type(t)==types.xxxxxx: do sth ``` I didn't find the relevent type in types module for the datetime type; could any one help me?
``` >>> type(t) <type 'datetime.datetime'> >>> type(t) is datetime.datetime True ``` Is that the information you're looking for? I don't think you'll be able to find the relevant type within the `types` module since `datetime.datetime` is not a builtin type. Edit to add: Another note, since this is evidently what you...
Decorators applied to class definition with Python
3,860,539
7
2010-10-05T02:51:27Z
3,860,556
23
2010-10-05T02:55:18Z
[ "python", "decorator" ]
Compared to decorators applied to a function, it's not easy to understand the decorators applied to a class. ``` @foo class Bar(object): def __init__(self, x): self.x = x def spam(self): statements ``` What's the use case of decorators to a class? How to use it?
It replaces the vast majority of classic good uses for custom metaclasses in a much simpler way. Think about it this way: nothing that's directly in the class body can refer to the class object, because the class object doesn't exist until well after the body's done running (it's the metaclass's job to create the clas...
recursively traverse multidimensional dictionary, dimension unknown
3,860,813
7
2010-10-05T04:18:34Z
3,860,882
10
2010-10-05T04:37:46Z
[ "python" ]
I want to create a function to recursively traverse a multidimensional dictionary, where the dimensions are unknown. Here is what I have come up with so far, but it doesn't seem to be working correctly. This will print out some key / values twice and they are not in order. ``` def walk_dict(d): for k,v in d.items...
I'm not sure what your ultimate goal is, but the code is doing what it is supposed to. You are seeing what you think are repeats of items because there are key/value combos like 'first\_name':'b' that are both within 'account' and within 'billing\_info' within 'account'. I'm not sure what order you are looking for, but...
How do I modify a single character in a string, in Python?
3,861,026
12
2010-10-05T05:23:15Z
3,861,032
12
2010-10-05T05:24:36Z
[ "python", "string" ]
How do I modify a single character in a string, in Python? Something like: ``` a = "hello" a[2] = "m" ``` 'str' object does not support item assignment.
Strings are immutable in Python. You can use a list of characters instead: ``` a = list("hello") ``` When you want to display the result use `''.join(a)`: ``` a[2] = 'm' print ''.join(a) ```
How do I modify a single character in a string, in Python?
3,861,026
12
2010-10-05T05:23:15Z
3,861,033
8
2010-10-05T05:24:43Z
[ "python", "string" ]
How do I modify a single character in a string, in Python? Something like: ``` a = "hello" a[2] = "m" ``` 'str' object does not support item assignment.
Try constructing a list from it. When you pass an iterable into a list constructor, it will [turn it into a list](http://docs.python.org/library/functions.html#list) (this is a bit of an oversimplification, but usually works). ``` a = list("hello") a[2] = m ``` You can then join it back up with `''.join(a)`.
How do I modify a single character in a string, in Python?
3,861,026
12
2010-10-05T05:23:15Z
3,861,034
9
2010-10-05T05:25:01Z
[ "python", "string" ]
How do I modify a single character in a string, in Python? Something like: ``` a = "hello" a[2] = "m" ``` 'str' object does not support item assignment.
In python, string are immutable. If you want to change a single character, you'll have to use [slicing](http://docs.python.org/tutorial/introduction.html#strings): ``` a = "hello" a = a[:2] + "m" + a[3:] ```
How do you correct Module already loaded UserWarnings in Python?
3,861,336
18
2010-10-05T06:38:12Z
4,834,842
7
2011-01-29T02:54:47Z
[ "python", "warnings", "virtualenv", "distribute" ]
Getting the following kinds of warnings when running most python scripts in the command line: ``` /Library/Python/2.6/site-packages/virtualenvwrapper/hook_loader.py:16: UserWarning: Module pkg_resources was already imported from /System/Library/Frameworks/Python.framework/Versions/2.6/Extras/lib/python/pkg_resources...
Perhaps use the virtualenv option `--no-site-packages` so you won't see any system site-packages within your virtual environment. Having items installed both in your virtualenv and on the system root may be the cause of this issue. Using `--no-site-packages` when creating your virtualenv prevents any conflict between ...
Is there a generator version of `string.split()` in Python?
3,862,010
59
2010-10-05T08:31:00Z
9,770,397
25
2012-03-19T12:41:04Z
[ "python", "string", "generator" ]
[`string.split()`](http://docs.python.org/library/stdtypes.html#str.split) returns a *list* instance. Is there a version that returns a [*generator*](http://docs.python.org/tutorial/classes.html#generators) instead? Are there any reasons against having a generator version?
It is highly probable that [`re.finditer`](http://docs.python.org/library/re.html#re.finditer)(link) uses fairly minimal memory overhead. ``` def split_iter(string): return (x.group(0) for x in re.finditer(r"[A-Za-z']+", string)) ``` Demo: ``` >>> list( split_iter("A programmer's RegEx test.") ) ['A', "programme...
How can I find all subclasses of a class given its name?
3,862,310
97
2010-10-05T09:17:35Z
3,862,957
123
2010-10-05T10:53:04Z
[ "python" ]
I need a working approach of getting all classes that are inherited from the base class in Python.
New-style classes (i.e. subclassed from `object`, which is the default in Python 3) have a `__subclasses__` method which returns the subclasses: ``` class Foo(object): pass class Bar(Foo): pass class Baz(Foo): pass class Bing(Bar): pass ``` Here are the names of the subclasses: ``` print([cls.__name__ for cls in var...
How can I find all subclasses of a class given its name?
3,862,310
97
2010-10-05T09:17:35Z
17,246,726
30
2013-06-22T02:22:14Z
[ "python" ]
I need a working approach of getting all classes that are inherited from the base class in Python.
If you just want direct subclasses then `.__subclasses__()` works fine. If you want all subclasses, subclasses of subclasses, and so on, you'll need a function to do that for you. Here's a simple, readable function that recursively finds all subclasses of a given class: ``` def get_all_subclasses(cls): all_subcla...
HTML form POST to a python script?
3,862,788
11
2010-10-05T10:29:18Z
3,862,829
8
2010-10-05T10:35:34Z
[ "python", "html" ]
Does anyone know of any good resources for information on how to POST data from a HTML form over to a python script?
For a very basic [CGI](http://en.wikipedia.org/wiki/Common_Gateway_Interface) script, you can use the [cgi module](http://docs.python.org/library/cgi.html). Check out the following article from the Python documentation for a very basic example on how to handle an HTML form submitted through `POST`: * [Web Programming ...
PyDev bugs with imports
3,863,369
14
2010-10-05T11:55:31Z
3,864,323
16
2010-10-05T13:58:19Z
[ "python", "eclipse", "pydev" ]
I am using PyDev/Eclipse for several monthes and I get ever and ever the same bugs with imports: PyDev underline in red an import and say `Unresolved import xxx ; Found at yyy`. When I click on `yyy` eclispe find and open the implementation of the module. (PyDev just inform me that it can't find the module xxx and in t...
This can happen if new modules are not cached by PyDev. For example, on my new laptop I first set up PyDev/Eclipse and later installed the Django package. That's why Django imports were marked as unresolved. You can refresh it using Pydev > Interpreter - Python > Libraries > Apply. Select the interpreter you want to "r...
Using reStructuredText to add some HTML with custom "id" and "class" attributes
3,864,712
5
2010-10-05T14:37:00Z
7,692,929
13
2011-10-07T21:13:48Z
[ "python", "restructuredtext" ]
Using rsStructuredText to generate HTML, I am trying to wrap a paragraph with an extra div element. The must contain an "id" attribute with a value I assign. Also, the must have a "class" attribute with "editable" value. This is what I have so far: ``` .. raw:: html <div id="an_identifier"> .. class:: editabl...
Since release 0.8 (2011-07-07), you can use the container directive with a name option: ``` .. container:: test :name: my-id a paragraph ``` results in ``` <div class="test container" id="my-id"> a paragraph </div> ```
Resampling irregularly spaced data to a regular grid in Python
3,864,899
12
2010-10-05T14:57:05Z
3,867,302
48
2010-10-05T20:08:36Z
[ "python", "matplotlib", "resampling" ]
I need to resample 2D-data to a regular grid. This is what my code looks like: ``` import matplotlib.mlab as ml import numpy as np y = np.zeros((512,115)) x = np.zeros((512,115)) # Just random data for this test: data = np.random.randn(512,115) # filling the grid coordinates: for i in range(512): y[i,:]=np...
Comparing your code example to your question's title, I think you're a bit confused... In your example code, you're creating *regularly gridded* random data and then resampling it onto *another regular grid*. You don't have irregular data anywhere in your example... (Also, the code doesn't run as-is, and you should l...
about python __doc__ docstring
3,865,254
4
2010-10-05T15:36:16Z
3,865,321
12
2010-10-05T15:43:20Z
[ "python", "doc", "docstring" ]
i want to show docstring of my function, but if i use like this ``` @cost_time def func(): "define ...." blabla print func.__doc__ ``` it will not show the docstring,just because i use some meta programming tricky, how can fix this?
Your wrapped function returned from the `cost_time` decorator must have the docstring instead of `func`. Therefore, use [`functools.wraps`](http://docs.python.org/library/functools.html#functools.wraps) which correctly sets `__name__` and `__doc__`: ``` from functools import wraps def cost_time(fn): @wraps(fn) ...
understanding zip function
3,865,640
13
2010-10-05T16:20:39Z
3,866,373
8
2010-10-05T18:00:56Z
[ "python", "iterator", "zip", "python-3.x" ]
All discussion is about python 3.1.2; see [Python docs](http://docs.python.org/py3k/library/functions.html?highlight=zip#zip) for the source of my question. I know what `zip` does; I just don't understand why it can be implemented like this: ``` def zip(*iterables): # zip('ABCD', 'xy') --> Ax By iterables = m...
It looks like it's a bug in the documentation. The 'equivalent' code works in python2 but not in python3, where it goes into an infinite loop. And the latest version of the documentation has the same problem: <http://docs.python.org/release/3.1.2/library/functions.html> Looks like change [61361](http://svn.python.org...
understanding zip function
3,865,640
13
2010-10-05T16:20:39Z
3,866,604
7
2010-10-05T18:31:21Z
[ "python", "iterator", "zip", "python-3.x" ]
All discussion is about python 3.1.2; see [Python docs](http://docs.python.org/py3k/library/functions.html?highlight=zip#zip) for the source of my question. I know what `zip` does; I just don't understand why it can be implemented like this: ``` def zip(*iterables): # zip('ABCD', 'xy') --> Ax By iterables = m...
It seems like this code is supposed to be read as python-2.x code. It doesn't even run properly in py3k. What happens in python-2.x is that `map` return a list of iterators, when `next` is called it returns an element of iterator, those elements combined into tuple. So, given ``` >>> zip('ABCD', 'xy') ``` iterables ...
sorting by first group element in python
3,865,779
2
2010-10-05T16:39:03Z
3,865,853
16
2010-10-05T16:46:53Z
[ "python" ]
I was wondering how can I make python order my collection of tuples so that first similar items would appear grouped and groups ordered by first item. ``` order group 3 1 4 2 2 2 1 1 ``` After sort ``` order group 1 1 3 1 2 2 4 2 ``` Python list ``` unordered = [(3, 1), (4, 2), (2, ...
I assume you meant `unordered = [(3, 1), (4, 2), (2, 2), (1, 1)]` because that part of your example as you typed it is incompatible with the other two, right? If so, then ``` >>> import operator >>> sorted(unordered, key=operator.itemgetter(1,0)) [(1, 1), (3, 1), (2, 2), (4, 2)] ``` or similarly `unordered.sort(key=...
Translating PHP’s preg_match_all to Python
3,865,896
7
2010-10-05T16:53:56Z
3,865,925
12
2010-10-05T16:57:35Z
[ "php", "python", "regex" ]
Can I have a translation of PHP’s `preg_match_all('/(https?:\/\/\S+)/', $text, $links)` in Python, please? (ie) I need to get the links present in the plain text argument in an array.
This will do it: ``` import re links = re.findall('(https?://\S+)', text) ``` If you plan to use this multiple times than you can consider doing this: ``` import re link_re = re.compile('(https?://\S+)') links = link_re.findall(text) ```
Can this Python postfix notation (reverse polish notation) interpreter be made more efficient and accurate?
3,865,939
7
2010-10-05T16:59:23Z
3,866,502
10
2010-10-05T18:18:17Z
[ "python", "rpn", "postfix-notation" ]
Here is a Python postfix notation interpreter which utilizes a stack to evaluate the expressions. Is it possible to make this function more efficient and accurate? ``` #!/usr/bin/env python import operator import doctest class Stack: """A stack is a collection, meaning that it is a data structure that con...
General suggestions: * Avoid unnecessary type checks, and rely on default exception behavior. * [`has_key()`](http://docs.python.org/library/stdtypes.html#dict.has_key) has long been deprecated in favor of the `in` operator: use that instead. * [Profile](http://docs.python.org/library/profile.html) your program, befor...
plotting histograms whose bar heights sum to 1 in matplotlib
3,866,520
31
2010-10-05T18:21:10Z
3,866,730
26
2010-10-05T18:45:29Z
[ "python", "graph", "numpy", "matplotlib", "scipy" ]
I'd like to plot a normalized histogram from a vector using matplotlib. I tried the following: ``` plt.hist(myarray, normed=True) ``` as well as: ``` plt.hist(myarray, normed=1) ``` but neither option produces a y-axis from [0, 1] such that the bar heights of the histogram sum to 1. I'd like to produce such a histo...
It would be more helpful if you posed a more complete working (or in this case non-working) example. I tried the following: ``` import numpy as np import matplotlib.pyplot as plt x = np.random.randn(1000) fig = plt.figure() ax = fig.add_subplot(111) n, bins, rectangles = ax.hist(x, 50, normed=True) fig.canvas.draw(...
plotting histograms whose bar heights sum to 1 in matplotlib
3,866,520
31
2010-10-05T18:21:10Z
15,121,190
9
2013-02-27T19:57:27Z
[ "python", "graph", "numpy", "matplotlib", "scipy" ]
I'd like to plot a normalized histogram from a vector using matplotlib. I tried the following: ``` plt.hist(myarray, normed=True) ``` as well as: ``` plt.hist(myarray, normed=1) ``` but neither option produces a y-axis from [0, 1] such that the bar heights of the histogram sum to 1. I'd like to produce such a histo...
I know this answer is too late considering the question is dated 2010 but I came across this question as I was facing a similar problem myself. As already stated in the answer, normed=True means that the total area under the histogram is equal to 1 but the sum of heights is not equal to 1. However, I wanted to, for con...
plotting histograms whose bar heights sum to 1 in matplotlib
3,866,520
31
2010-10-05T18:21:10Z
16,399,202
83
2013-05-06T12:53:31Z
[ "python", "graph", "numpy", "matplotlib", "scipy" ]
I'd like to plot a normalized histogram from a vector using matplotlib. I tried the following: ``` plt.hist(myarray, normed=True) ``` as well as: ``` plt.hist(myarray, normed=1) ``` but neither option produces a y-axis from [0, 1] such that the bar heights of the histogram sum to 1. I'd like to produce such a histo...
If you want the sum of all bars to be equal unity, weight each bin by the total number of values: ``` weights = np.ones_like(myarray)/len(myarray) plt.hist(myarray, weights=weights) ``` Hope that helps, although the thread is quite old...
django error: 'unicode' object is not callable
3,866,577
6
2010-10-05T18:28:28Z
3,866,601
26
2010-10-05T18:31:06Z
[ "python", "django" ]
im attempting to do the django tutorial from the django website, and ive run into a bit of an issue: ive got to adding my `__unicode__` methods to my models classes, but when ever i try to return the objects of that model i get the following error: ``` in __unicode__ return self.question() TypeError: 'unicode' obj...
`self.choice` is a string value, but the code is trying to call it like a function. Just remove the `()` after it.
Converting a python numeric expression to LaTeX
3,867,028
17
2010-10-05T19:33:07Z
3,868,121
9
2010-10-05T22:04:18Z
[ "python", "math", "latex" ]
I need to convert strings with valid python syntax such as: ``` '1+2**(x+y)' ``` and get the equivalent LaTeX: ``` $1+2^{x+y}$ ``` I have tried sympy's latex function but it processes actual expression, rather than the string form of it: ``` >>> latex(1+2**(x+y)) '$1 + 2^{x + y}$' >>> latex('1+2**(x+y)') '$1+2**(x...
You can use `sympy.latex` with `eval`: ``` s = "1+2**(x+y)" sympy.latex(eval(s)) # prints '$1 + {2}^{x + y}$' ``` You still have to declare the variables as symbols, but if this is really a problem, it's much easier to write a parser to do this than to parse everything and generate the latex from scratch.
Converting a python numeric expression to LaTeX
3,867,028
17
2010-10-05T19:33:07Z
3,874,621
13
2010-10-06T16:14:02Z
[ "python", "math", "latex" ]
I need to convert strings with valid python syntax such as: ``` '1+2**(x+y)' ``` and get the equivalent LaTeX: ``` $1+2^{x+y}$ ``` I have tried sympy's latex function but it processes actual expression, rather than the string form of it: ``` >>> latex(1+2**(x+y)) '$1 + 2^{x + y}$' >>> latex('1+2**(x+y)') '$1+2**(x...
Here's a rather long but still incomplete method that doesn't involve sympy in any way. It's enough to cover the example of `(-b-sqrt(b**2-4*a*c))/(2*a)` which gets translated to `\frac{- b - \sqrt{b^{2} - 4 \; a \; c}}{2 \; a}` and renders as ![alt text](http://i.stack.imgur.com/bVJLe.png) It basically creates the A...
Converting a python numeric expression to LaTeX
3,867,028
17
2010-10-05T19:33:07Z
4,308,411
7
2010-11-29T21:45:55Z
[ "python", "math", "latex" ]
I need to convert strings with valid python syntax such as: ``` '1+2**(x+y)' ``` and get the equivalent LaTeX: ``` $1+2^{x+y}$ ``` I have tried sympy's latex function but it processes actual expression, rather than the string form of it: ``` >>> latex(1+2**(x+y)) '$1 + 2^{x + y}$' >>> latex('1+2**(x+y)') '$1+2**(x...
You can use SymPy. Just pass the string to the `sympify()` function first, which will convert it to a valid SymPy expression (i.e., create the Symbols for you, etc.). So you could do ``` >>> latex(sympify('1+2**(x+y)')) 1 + 2^{x + y} ``` `S()` is also a shortcut to `sympify()`, i.e., `latex(S('1+2**(x+y)'))` also wor...
Comparing Python lists
3,867,262
8
2010-10-05T20:03:38Z
3,867,290
14
2010-10-05T20:06:36Z
[ "python", "list" ]
I have several long lists in python and have compare them and find the lists that are equal to each other except the last elements in the them. Which is the fastest way?
`a[:-1]` is shorthand for "all the elements of `a` but the last one." If you need more than 1 element to be excluded, change the 1 to the number you need. `a[:-1] == b[:-1]` will compare `a` and `b` without their final elements. See [this](http://stackoverflow.com/q/509211/391531) for more information on slicing.
Comparing Python lists
3,867,262
8
2010-10-05T20:03:38Z
3,867,296
7
2010-10-05T20:06:58Z
[ "python", "list" ]
I have several long lists in python and have compare them and find the lists that are equal to each other except the last elements in the them. Which is the fastest way?
Use something like `if list1[:-1] == list2[:-1]`.
How do I abort object instance creation in Python?
3,867,718
21
2010-10-05T21:05:01Z
3,867,799
14
2010-10-05T21:14:53Z
[ "python", "object" ]
I want to set up a class that will abort during instance creation based on the value of the the argument passed to the class. I've tried a few things, one of them being raising an error in the `__new__` method: ``` class a(): def __new__(cls, x): if x == True: return cls else: ...
When you override `__new__`, dont forget to call to super! ``` >>> class Test(object): ... def __new__(cls, x): ... if x: ... return super(Test, cls).__new__(cls) ... else: ... raise ValueError ... >>> obj1 = Test(True) >>> obj2 = Test(False) Traceback (most recent call las...
Google App Engine-Ajax refresh from datastore using python
3,868,710
4
2010-10-06T00:19:35Z
3,868,816
8
2010-10-06T00:49:36Z
[ "python", "google-app-engine", "gae-datastore" ]
I have an application(developed in python) that requires a refreshed view from the datastore after every 5 seconds. I have came out with an javascript function and handle the refresh using ajax. Ajax function ``` <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></sc...
The call to `load('/refresh')` replaces the contents of the `responsecontainer` div with the loaded HTML. You therefore need the `RefreshPage` handler to just return that HTML, and not the whole page. For example, it should use a template which just contains this: ``` {% for greeting in greetings %} {% if greeting...
Find phone numbers in python script
3,868,753
6
2010-10-06T00:32:00Z
3,868,861
10
2010-10-06T01:04:18Z
[ "python", "regex" ]
the following python script allows me to scrape email addresses from a given file using regular expressions. How could I add to this so that I can also get phone numbers? Say, if it was either the 7 digit or 10 digit (with area code), and also account for parenthesis? **My current script can be found below:** ``` # ...
If you are interested in learning Regex, you could take a stab at writing it yourself. It's not quite as hard as it's made out to be. Sites like [RegexPal](http://regexpal.com/) allow you to enter some test data, then write and test a Regular Expression against that data. Using RegexPal, try adding some phone numbers i...
Parse large RDF in Python
3,868,888
11
2010-10-06T01:12:19Z
3,879,817
13
2010-10-07T08:15:53Z
[ "python", "xml", "sax", "rdf" ]
I'd like to parse a very large (about 200MB) RDF file in python. Should I be using sax or some other library? I'd appreciate some very basic code that I can build on, say to retrieve a tag. Thanks in advance.
If you are looking for fast performance then I'd recommend you to use [Raptor](http://librdf.org/raptor/) with the [Redland Python Bindings](http://librdf.org/bindings/). The performance of Raptor, written in C, is way better than RDFLib. And you can use the python bindings in case you don't want to deal with C. Anoth...
Parse large RDF in Python
3,868,888
11
2010-10-06T01:12:19Z
3,943,111
7
2010-10-15T14:18:45Z
[ "python", "xml", "sax", "rdf" ]
I'd like to parse a very large (about 200MB) RDF file in python. Should I be using sax or some other library? I'd appreciate some very basic code that I can build on, say to retrieve a tag. Thanks in advance.
I second the suggestion that you try out rdflib. It's nice and quick prototyping, and the BerkeleyDB backend store scales pretty well into the millions of triples if you don't want to load the whole graph into memory. ``` import rdflib graph = rdflib.Graph("Sleepycat") graph.open("store", create=True) graph.parse("bi...
Python Tornado - making POST return immediately while async function keeps working
3,869,421
6
2010-10-06T04:02:20Z
3,869,546
7
2010-10-06T04:42:22Z
[ "python", "tornado" ]
so I have a handler below: ``` class PublishHandler(BaseHandler): def post(self): message = self.get_argument("message") some_function(message) self.write("success") ``` The problem that I'm facing is that some\_function() takes some time to execute and I would like the post request to re...
You might be able to accomplish this by using your `IOLoop`'s `add_callback` method like so: ``` loop.add_callback(lambda: some_function(message)) ``` Tornado will execute the callback in the next IOLoop pass, which *may* (I'd have to dig into Tornado's guts to know for sure, or alternatively test it) allow the reque...
Why do C programs require decompilers but python programs dont?
3,869,435
3
2010-10-06T04:07:42Z
3,869,443
10
2010-10-06T04:11:45Z
[ "python", "c", "decompiling" ]
If I write a python script, anyone can simply point an editor to it and read it. But for programming written in C, one would have to use decompilers and hex tables and such. Why is that? I mean I simply can't open up the Safari web browser and look at its code.
Python is a script language, runs in a virtual machine through an interpeter. C is a compiled language, the code compiled to binary code which the computer can run without all that extra stuff Python needs.
Why do C programs require decompilers but python programs dont?
3,869,435
3
2010-10-06T04:07:42Z
3,869,508
13
2010-10-06T04:32:15Z
[ "python", "c", "decompiling" ]
If I write a python script, anyone can simply point an editor to it and read it. But for programming written in C, one would have to use decompilers and hex tables and such. Why is that? I mean I simply can't open up the Safari web browser and look at its code.
*Note: The author disavows a deep expertise in this subject. Some assertions may be incorrect.* Python actually is compiled into bytecode, which is what gets run by the python interpreter. Whenever you use a Python module, Python will generate a `.pyc` file with a name corresponding to the module. This is the equivale...
how to decode a non unicode character in python?
3,870,084
5
2010-10-06T06:54:00Z
3,870,181
10
2010-10-06T07:12:00Z
[ "python", "unicode" ]
I have a string say `s = 'Chocolate Moelleux-M\xe8re'` When i am doing: ``` In [14]: unicode(s) --------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe8 in position 20...
I have had to face this problem one too many times. The problem that I had contained strings in different encoding schemes. So I wrote a method to decode a string heuristically based on certain features of different encodings. ``` def decode_heuristically(string, enc = None, denc = sys.getdefaultencoding()): """ ...
Cython C++ and std::string
3,870,772
9
2010-10-06T08:42:07Z
3,940,267
8
2010-10-15T07:29:00Z
[ "c++", "python", "cython" ]
What is the best way of using C++ standard std::string from cython? The last cython distribution should make it easy anyway, but I wonder why there are wrappers for std::vector and not for std::string...
Oops, this question has been hanging here for a few days now. At the end I did this: ``` cdef extern from "string" namespace "std": cdef cppclass string: char* c_str() ``` which is not a complete solution but still it does the thing.
Cython C++ and std::string
3,870,772
9
2010-10-06T08:42:07Z
11,909,483
10
2012-08-10T21:25:59Z
[ "c++", "python", "cython" ]
What is the best way of using C++ standard std::string from cython? The last cython distribution should make it easy anyway, but I wonder why there are wrappers for std::vector and not for std::string...
Cython 0.16 [includes wrappers for std::string](http://docs.cython.org/src/tutorial/strings.html#c-strings), which can be imported with: ``` from libcpp.string cimport string ```
Why does this cause a syntax error?
3,870,778
8
2010-10-06T08:42:59Z
3,870,813
17
2010-10-06T08:46:44Z
[ "python", "arguments", "tuples", "expand" ]
In python, I wrote this: ``` bvar=mht.get_value() temp=self.treemodel.insert(iter,0,(mht,False,*bvar)) ``` I'm trying to expand bvar to the function call as arguments. But then it return, ``` File "./unobsoluttreemodel.py", line 65 temp=self.treemodel.insert(iter,0,(mht,False,*bvar)) ...
If you want to pass the last argument as a tuple of `(mnt, False, bvar[0], bvar[1], ...)` you could use ``` temp = self.treemodel.insert(iter, 0, (mht,False)+tuple(bvar) ) ``` --- The extended call syntax `*b` can only be used in [calling functions](http://docs.python.org/reference/expressions.html#calls), [function...
Why does this cause a syntax error?
3,870,778
8
2010-10-06T08:42:59Z
33,973,612
9
2015-11-28T16:26:53Z
[ "python", "arguments", "tuples", "expand" ]
In python, I wrote this: ``` bvar=mht.get_value() temp=self.treemodel.insert(iter,0,(mht,False,*bvar)) ``` I'm trying to expand bvar to the function call as arguments. But then it return, ``` File "./unobsoluttreemodel.py", line 65 temp=self.treemodel.insert(iter,0,(mht,False,*bvar)) ...
Update: this behavior was fixed in Python 3.5.0, see [PEP-0448](https://www.python.org/dev/peps/pep-0448/): > Unpacking is proposed to be allowed inside tuple, list, set, and dictionary displays: ``` *range(4), 4 # (0, 1, 2, 3, 4) [*range(4), 4] # [0, 1, 2, 3, 4] {*range(4), 4} # {0, 1, 2, 3, 4} {'x': 1, **{'y': 2...
How to handle call to __setattr__ from __init__?
3,870,982
7
2010-10-06T09:07:35Z
3,871,001
7
2010-10-06T09:10:13Z
[ "python" ]
I have written a class that will be used to store parameters in a convenient way for pickling. It overloads `__setattr__` for convenient access. It also uses a list to remember the order in which attributes where added, so that the iteration order is predictable and constant. Here it is: ``` class Parameters(object): ...
yes. have it call `super(Parameters, self).__setattr__()` instead. ``` class Parameters(object): def __init__(self): super(Parameters, self).__setattr__('paramOrder', []) # etc. ``` Or am I missing something? Another alternative is to just go straight to `__dict__` ``` class Parameters(object): ...
Reading from a file using pickle and for loop in python
3,871,388
8
2010-10-06T10:05:10Z
3,871,442
9
2010-10-06T10:12:41Z
[ "python", "pickle" ]
I have a file in which I have dumped a huge number of lists.Now I want to load this file into memory and use the data inside it.I tried to load my file using the "load" method of "pickle", However, for some reason it just gives me the first item in the file. actually I noticed that it only load the my first list into m...
How about this: ``` lists = [] infile = open('yourfilename.pickle', 'r') while 1: try: lists.append(pickle.load(infile)) except (EOFError, UnpicklingError): break infile.close() ```
Scrapy - how to identify already scraped urls
3,871,613
11
2010-10-06T10:38:32Z
4,201,553
11
2010-11-17T04:39:40Z
[ "python", "web-crawler", "scrapy" ]
Im using scrapy to crawl a news website on a daily basis. How do i restrict scrapy from scraping already scraped URLs. Also is there any clear documentation or examples on `SgmlLinkExtractor`.
You can actually do this quite easily with the scrapy snippet located here: <http://snipplr.com/view/67018/middleware-to-avoid-revisiting-already-visited-items/> To use it, copy the code from the link and put it into some file in your scrapy project. To reference it, add a line in your settings.py to reference it: ``...
Ideas on how to uniquely identify a computer?
3,873,105
2
2010-10-06T13:46:22Z
3,873,252
9
2010-10-06T14:00:19Z
[ "python", "hash", "uniqueidentifier" ]
I have been thinking of ways I could uniquely identify a computer in python. First, I thought about checking the user's mac address and hard disk space, then I tried to compute some sort of rating from many of these variables. However, this solution doesn't feel right. It takes a long time to run and I had to change it...
First you need to define "computer." Is a computer the same computer if you change the case? The hard drive? The network card? Increase the RAM? Upgrade the kernel? (It brings to mind the saying about "my grandfather's hammer" — sure, I've replaced the head five times and the handle twice, but it's still the same ha...
Can I change an an existing virtualenv to ignore global site packages? (like --no-site-package on a new one)
3,873,294
11
2010-10-06T14:04:16Z
3,873,405
8
2010-10-06T14:13:51Z
[ "python", "virtualenv" ]
I can create a new virtualenv that ignores global site-packages with "--no-site-package". Is it possible to change an existing virtualenv (which was created without "--no-site-package") to also ignore the global site-packages? (So that it workes like it was created with "--no-site-package" in the first place.) thanks ...
Can you just create a new one and then re-create it with the `--no-site-package`? If you use [pip](http://pip.openplans.org/) then you can use `pip freeze > requirements.pip` to generate a requirements file to re-install into your new virtualenv.
Can I change an an existing virtualenv to ignore global site packages? (like --no-site-package on a new one)
3,873,294
11
2010-10-06T14:04:16Z
3,874,179
15
2010-10-06T15:29:56Z
[ "python", "virtualenv" ]
I can create a new virtualenv that ignores global site-packages with "--no-site-package". Is it possible to change an existing virtualenv (which was created without "--no-site-package") to also ignore the global site-packages? (So that it workes like it was created with "--no-site-package" in the first place.) thanks ...
I think all you have to do is create an empty file called `no-global-site-packages.txt` and put it into the virtualenv's python2.x folder (eg, `lib/python2.6/`, the one with all the modules). Then the normal site.py generated by virtualenv detects the difference and handles everything from there.
Finding multiple occurrences of a string within a string in Python
3,873,361
34
2010-10-06T14:10:19Z
3,873,422
53
2010-10-06T14:15:46Z
[ "python", "string" ]
How do I find multiple occurrences of a string within a string in Python? Consider this: ``` >>> text = "Allowed Hello Hollow" >>> text.find("ll") 1 >>> ``` So the first occurrence of `ll` is at 1 as expected. How do I find the next occurrence of it? Same question is valid for a list. Consider: ``` >>> x = ['ll', '...
Using regular expressions, you can use [`re.finditer`](http://docs.python.org/3/library/re.html#re.finditer) to find all (non-overlapping) occurences: ``` >>> import re >>> text = 'Allowed Hello Hollow' >>> for m in re.finditer('ll', text): print('ll found', m.start(), m.end()) ll found 1 3 ll found 10 12 ll...
Finding multiple occurrences of a string within a string in Python
3,873,361
34
2010-10-06T14:10:19Z
3,873,471
9
2010-10-06T14:20:32Z
[ "python", "string" ]
How do I find multiple occurrences of a string within a string in Python? Consider this: ``` >>> text = "Allowed Hello Hollow" >>> text.find("ll") 1 >>> ``` So the first occurrence of `ll` is at 1 as expected. How do I find the next occurrence of it? Same question is valid for a list. Consider: ``` >>> x = ['ll', '...
I think what you are looking for is `string.count` ``` "Allowed Hello Hollow".count('ll') >>> 3 ``` Hope this helps NOTE: this only captures non-overlapping occurences
Finding multiple occurrences of a string within a string in Python
3,873,361
34
2010-10-06T14:10:19Z
3,874,144
11
2010-10-06T15:27:19Z
[ "python", "string" ]
How do I find multiple occurrences of a string within a string in Python? Consider this: ``` >>> text = "Allowed Hello Hollow" >>> text.find("ll") 1 >>> ``` So the first occurrence of `ll` is at 1 as expected. How do I find the next occurrence of it? Same question is valid for a list. Consider: ``` >>> x = ['ll', '...
For the list example, use a comprehension: ``` >>> l = ['ll', 'xx', 'll'] >>> print [n for (n, e) in enumerate(l) if e == 'll'] [0, 2] ``` Similarly for strings: ``` >>> text = "Allowed Hello Hollow" >>> print [n for n in xrange(len(text)) if text.find('ll', n) == n] [1, 10, 16] ``` this will list adjacent runs of ...
Finding multiple occurrences of a string within a string in Python
3,873,361
34
2010-10-06T14:10:19Z
3,874,760
12
2010-10-06T16:27:36Z
[ "python", "string" ]
How do I find multiple occurrences of a string within a string in Python? Consider this: ``` >>> text = "Allowed Hello Hollow" >>> text.find("ll") 1 >>> ``` So the first occurrence of `ll` is at 1 as expected. How do I find the next occurrence of it? Same question is valid for a list. Consider: ``` >>> x = ['ll', '...
FWIW, here are a couple of non-RE alternatives that I think are neater than [poke's solution](http://stackoverflow.com/questions/3873361/finding-multiple-occurrences-of-a-string-within-a-string-in-python/3873422#3873422). The first uses `str.index` and checks for `ValueError`: ``` def findall(sub, string): """ ...
Combinations from dictionary with list values using Python
3,873,654
17
2010-10-06T14:38:42Z
3,873,734
23
2010-10-06T14:45:34Z
[ "python", "algorithm", "list", "dictionary", "combinations" ]
I have the following incoming value: ``` variants = { "debug" : ["on", "off"], "locale" : ["de_DE", "en_US", "fr_FR"], ... } ``` I want to process them so I get the following result: ``` combinations = [ [{"debug":"on"},{"locale":"de_DE"}], [{"debug":"on"},{"locale":"en_US"}], [{"debug":"on"},{"locale":"...
``` import itertools as it varNames = sorted(variants) combinations = [dict(zip(varNames, prod)) for prod in it.product(*(variants[varName] for varName in varNames))] ``` Hm, this returns: ``` [{'debug': 'on', 'locale': 'de_DE'}, {'debug': 'on', 'locale': 'en_US'}, {'debug': 'on', 'locale': 'fr_FR'}, {'debug': 'o...
Developing with Django+Celery without running `celeryd`?
3,874,422
26
2010-10-06T15:54:03Z
3,875,424
41
2010-10-06T17:50:00Z
[ "python", "django", "celery" ]
In development, it's a bit of a hassle to run the `celeryd` as well as the Django development server. Is it possible to, for example, ask `celery` to run tasks synchronously during development? Or something similar?
Yes you can do this by setting `CELERY_ALWAYS_EAGER = True` in your settings. <http://docs.celeryproject.org/en/latest/configuration.html#task-execution-settings>
Getting html stripped of script and style tags with BeautifulSoup?
3,874,442
7
2010-10-06T15:55:46Z
3,874,642
7
2010-10-06T16:16:00Z
[ "python", "html-parsing", "beautifulsoup", "python-2.6" ]
I have a simple script where I am fetching an HTML page, passing it to BeautifulSoup to remove all script and style tags, then I want to pass the HTML result to another method. Is there an easy way to do this? Skimming the BeautifulSoup.py, I haven't seen it yet. ``` soup = BeautifulSoup(html) for script in soup("scri...
`unicode( soup )` gives you the html. Also what you want is this: ``` for elem in soup.findAll(['script', 'style']): elem.extract() ```
python: how to remove certain characters
3,874,730
4
2010-10-06T16:24:35Z
3,874,768
8
2010-10-06T16:28:35Z
[ "python", "string", "character" ]
how do i write a function removeThese(stringToModify,charsToRemove) that will return a string which is the original stringToModify string with the characters in charsToRemove removed from it.
``` >>> s = 'stringToModify' >>> rem = 'oi' >>> s.translate(str.maketrans(dict.fromkeys(rem))) 'strngTMdfy' ```
How do I compress a folder with the Python GZip module?
3,874,837
3
2010-10-06T16:37:50Z
11,605,421
7
2012-07-23T01:27:02Z
[ "python", "compression", "gzip", "tar" ]
I'm creating Python software that compresses files/folders... How would I create a section of the code that asks for the user input of the folder location and then compresses it. I currently have the code for a single file but not a folder full of files. Please explain in detail how to do this.
The code to compress a folder in to tar file is: ``` import tarfile tar = tarfile.open("TarName.tar.gz", "w:gz") tar.add("folder/location", arcname="TarName") tar.close() ``` It works for me. Hope that works for you too.
Data type problem using scipy.spatial
3,875,062
3
2010-10-06T17:04:29Z
3,875,304
7
2010-10-06T17:33:22Z
[ "python", "numpy", "scipy" ]
I want to use scipy.spatial's KDTree to find nearest neighbor pairs in a two dimensional array (essentially a list of lists where the dimension of the nested list is 2). I generate my list of lists, pipe it into numpy's array and then create the KDTree instance. However, whenever I try to run "query" on it, I inevitabl...
I have used `scipy.spatial` before, and it appears to be a nice improvement (especially wrt the interface) as compared to `scikits.ann`. In this case I think you have confused the return from your `tree.query(...)` call. From the `scipy.spatial.KDTree.query` [docs](http://docs.scipy.org/doc/scipy/reference/generated/s...
equivalent of Python's "with" in Ruby
3,875,596
10
2010-10-06T18:14:29Z
3,875,616
8
2010-10-06T18:16:04Z
[ "python", "ruby", "language-features", "with-statement", "control-flow" ]
In Python, the `with` statement is used to make sure that clean-up code always gets called, regardless of exceptions being thrown or function calls returning. For example: ``` with open("temp.txt", "w") as f: f.write("hi") raise ValueError("spitespite") ``` Here, the file is closed, even though an exception w...
The equivalent in Ruby would be to pass a block to the File.open method. ``` File.open(...) do |file| #do stuff with file end #file is closed ``` This is the idiom that Ruby uses and one that you should get comfortable with.
equivalent of Python's "with" in Ruby
3,875,596
10
2010-10-06T18:14:29Z
3,875,832
20
2010-10-06T18:42:15Z
[ "python", "ruby", "language-features", "with-statement", "control-flow" ]
In Python, the `with` statement is used to make sure that clean-up code always gets called, regardless of exceptions being thrown or function calls returning. For example: ``` with open("temp.txt", "w") as f: f.write("hi") raise ValueError("spitespite") ``` Here, the file is closed, even though an exception w...
Ruby has syntactically lightweight support for literal anonymous procedures (called *blocks* in Ruby). Therefore, it doesn't need a new language feature for this. (In general, it is a bad sign, if you need to add language features. You should be able to implement everything in a library, otherwise it is a sign of bad ...