title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Python: Why should 'from <module> import *' be prohibited?
3,571,514
22
2010-08-26T01:46:33Z
3,571,636
15
2010-08-26T02:21:54Z
[ "python", "namespaces", "module" ]
If you happen to have ``` from <module> import * ``` in the middle of your program (or module), you would get the warning: ``` /tmp/foo:100: SyntaxWarning: import * only allowed at module level ``` I understand why `import *` is discouraged in general (namespace invisibility), but there are many situations where it...
At any lexical level, `from amodule import *` is a "seemed a good idea at the time" design decision that has proven a real disaster in real life, with the *possible* exception of handy exploration at the interactive interpreter prompt (even then, I'm not too hot on it -- `import module as m` forces only two extra chara...
Moving Beyond Factories in Python
3,571,773
7
2010-08-26T03:04:52Z
3,571,805
12
2010-08-26T03:13:26Z
[ "java", "python" ]
Coming to Python from Java, I've been told that factories are not Pythonic. Thus, I'm looking for a the Python way to do something like the following. (I'm oversimplifying my goal so that I don't have to describe my entire program, which is very complicated). My script will read in names of people (along with some inf...
I don't think factories are un-Pythonic. You don't need a whole class, though. One big difference between Java and Python is that in Python you can have code outside of classes. So you might want to create a factory function. Or you can make the factory be a class method on the Person class: ``` class Person: nam...
Python and OpenMP C Extensions
3,572,580
26
2010-08-26T06:36:35Z
3,893,679
15
2010-10-08T19:25:14Z
[ "python", "parallel-processing", "openmp", "python-c-extension" ]
I have a C extension in which I'd like to use OpenMP. When I import my module, though, I get an import error: ``` ImportError: /home/.../_entropysplit.so: undefined symbol: GOMP_parallel_end ``` I've compiled the module with -fopenmp and -lgomp. Is this because my Python installation wasn't compiled with the -fopenmp...
Just to make it clearer, here is what your setup.py should look like: ``` ext = Extension( 'milk.unsupervised._som', sources = ['milk/unsupervised/_som.cpp'], extra_compile_args=['-fopenmp'], extra_link_args=['-lgomp']) ... setup(..., ext_modules = [ext]) ```
Mapping module imports in Python for easy refactoring
3,573,694
12
2010-08-26T09:18:15Z
3,573,801
13
2010-08-26T09:32:38Z
[ "python", "refactoring", "module", "python-module" ]
I have a bunch of Python modules I want to clean up, reorganize and refactor (there's some duplicate code, some unused code ...), and I'm wondering if there's a tool to make a map of which module uses which other module. Ideally, I'd like a map like this: ``` main.py -> task_runner.py -> task_utils.py -> deseria...
Python's [`modulefinder`](http://docs.python.org/library/modulefinder.html) does this. It is quite easy to write a script that will turn this information into an import graph (which you can render with e.g. [graphviz](http://www.graphviz.org/)): here's a [clear explanation](http://www.tarind.com/depgraph.html). There's...
What is the correct way to unset a linux environment variable in python?
3,575,165
24
2010-08-26T12:49:16Z
3,575,213
33
2010-08-26T12:54:19Z
[ "python", "environment-variables" ]
From the documentation: > If the platform supports the `unsetenv()` function, you can delete items in this mapping to unset environment variables. `unsetenv()` will be called automatically when an item is deleted from os.environ, and when one of the `pop()` or `clear()` methods is called. However I want something tha...
Just ``` del os.environ['MYVAR'] ``` should work.
copy objects between different Virtual-Machines efficiently
3,575,218
5
2010-08-26T12:55:04Z
3,575,453
7
2010-08-26T13:23:58Z
[ "java", "javascript", "c#", "python", "vm-implementation" ]
I have a feeling that I am going to ask a "stupid" question, yet I must ask ... I have 2 virtual machines. I would like to copy an instance of an object from one to another, Is it possible to copy the bits that represents this object in the VM's heap, send it to the other VM, like that the other VM just need to allo...
Lets ignore for a second the naive assumption that you can generalize this question over multiple VMs easily. Any attempt to build a mechanism like this would be heavily dependent on the implementation details of the VM you were building the mechanism for. Here are several reasons why this isn't done: 1. In-core repr...
Select as in sqlalchemy
3,576,382
10
2010-08-26T14:56:03Z
11,443,981
19
2012-07-12T01:43:26Z
[ "python", "sqlalchemy" ]
I want to do something like this: ``` select username, userid, 'user' as new_column from users_table. ``` The columns of the table can be selected using sqlalchemy as follows: ``` query = select([users_table.c.username, users_table.c.userid]) ``` How do I do the select `x` as `col_x` to the query in sqlalchemy?
use this: `users_table.c.userid.label('NewColumn')` i.e., ``` query = select([users_table.c.username, users_table.c.userid.label('NewColumn')]) ``` evaluates to: ``` SELECT username , userid as NewColumn From MyTable; ```
Abort a running task in Celery within django
3,576,512
5
2010-08-26T15:11:43Z
3,607,397
8
2010-08-31T08:43:15Z
[ "python", "django", "rabbitmq", "celery", "celery-task" ]
I would like to be able to abort a task that is running from a Celery queue (using rabbitMQ). I call the task using ``` task_id = AsyncBoot.apply_async(args=[name], name=name, connect_timeout=3) ``` where AsyncBoot is a defined task. I can get the task ID (assuming that is the long string that `apply_async` returns)...
`apply_async` returns an `AsyncResult` instance, or in this case an `AbortableAsyncResult`. Save the `task_id` and use that to instantiate a new `AbortableAsyncResult` later, making sure you supply the backend optional argument if you're not using the `default_backend`. ``` abortable_async_result = AsyncBoot.apply_asy...
Is it a good idea to using class as a namespace in Python
3,576,596
14
2010-08-26T15:22:34Z
3,576,629
9
2010-08-26T15:25:54Z
[ "c++", "python", "oop", "class", "namespaces" ]
I am putting a bunch of related stuff into a class. The main purpose is to organize them into a namespace. ``` class Direction: north = 0 east = 1 south = 2 west = 3 @staticmethod def turn_right(d): return turn_to_the_right @staticmethod def turn_left(d): return turn_to_the_left # defined...
No. Stick it in a module instead. Python doesn't have namespaces in the same way that C++ does, but modules serve a somewhat similar purpose (that is, grouping "like" classes and functions together, and giving them unique names to avoid clashes). **Edit** I saw the comment you posted to your question. To answer mor...
Sending multiple POST data items with the same name, using AppEngine
3,577,064
5
2010-08-26T16:11:06Z
3,577,417
13
2010-08-26T16:50:03Z
[ "python", "google-app-engine", "urlfetch" ]
I try to send POST data to a server using urlfetch in AppEngine. Some of these POST-data items has the same name, but with different values. ``` form_fields = { "data": "foo", "data": "bar" } form_data = urllib.urlencode(form_fields) result = urlfetch.fetch(url="http://www.foo.com/", payload=form_data, method=u...
Modify your `form_fields` dictionary so that fields with the same name are turned into lists, and use the `doseq` argument to `urllib.urlencode`: ``` form_fields = { "data": ["foo","bar"] } form_data = urllib.urlencode(form_fields, doseq=True) ``` At this point, `form_data` is `'data=foo&data=bar'`, which is what...
SSH Tunnel for Python MySQLdb connection
3,577,555
15
2010-08-26T17:06:13Z
3,577,608
15
2010-08-26T17:13:45Z
[ "python", "mysql", "ssh" ]
I tried creating a SSH tunnel using ``` ssh -L 3306:localhost:22 <hostip> ``` Then running my python script to connect via localhost ``` conn = MySQLdb.connect(host'localhost', port=3306, user='bob', passwd='na', db='test') ``` However, I receive the following error ``` (2002, "Can't connect to local MySQL server ...
Try changing `"localhost"` to `"127.0.0.1"`, it should work as you expect. This behavior is detailed in the [manual](http://mysql-python.sourceforge.net/MySQLdb.html): > UNIX sockets and named pipes don't > work over a network, so if you specify > a host other than localhost, TCP will > be used, and you can specify an...
SSH Tunnel for Python MySQLdb connection
3,577,555
15
2010-08-26T17:06:13Z
3,577,629
11
2010-08-26T17:16:13Z
[ "python", "mysql", "ssh" ]
I tried creating a SSH tunnel using ``` ssh -L 3306:localhost:22 <hostip> ``` Then running my python script to connect via localhost ``` conn = MySQLdb.connect(host'localhost', port=3306, user='bob', passwd='na', db='test') ``` However, I receive the following error ``` (2002, "Can't connect to local MySQL server ...
Does mysqld run on port 22 on the remote? Call me ignorant but I think what you're trying to do is ``` ssh -n -N -f -L 3306:localhost:3306 remotehost ``` Then making MySQL connections on local machine will transparently get tunneled over to the target host.
MySQL error: 2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 0"
3,578,147
14
2010-08-26T18:14:09Z
6,337,930
15
2011-06-14T00:38:02Z
[ "python", "mysql" ]
I'm having an issue connecting to my local MySQL database using Python's MySQLdb library. The script has been working well previously, but I will occasionally get the MySQL error in the title. There seems to be no explanation for when the error occurs, and the script is always run from the same machine with the same ar...
``` sudo vi /etc/mysql/my.cnf ``` delete ``` bind-address = 127.0.0.1 ``` then ``` sudo reboot now ``` That's it. Be aware that this will make your mysql server less secure as you are exposing it.
Newline showing up on screen but not in email
3,578,174
5
2010-08-26T18:16:35Z
3,578,193
8
2010-08-26T18:19:03Z
[ "python", "email", "newline" ]
I have a list (`errors`) that I both print to the screen and send in the body of an email. But first I separate the elements of the list with a newline character: ``` "\n".join(errors) ``` I then print it to the console and send it as an email. On the console it appears delimited by newlines: ``` Error generating re...
Two things I would try: * try with CRLF (`"\r\n"`) instead of just LF * make sure your email is not being sent in HTML mode, or, if yes, try replacing the `"\n"` with `"<br>"`
Newline showing up on screen but not in email
3,578,174
5
2010-08-26T18:16:35Z
3,578,235
9
2010-08-26T18:24:39Z
[ "python", "email", "newline" ]
I have a list (`errors`) that I both print to the screen and send in the body of an email. But first I separate the elements of the list with a newline character: ``` "\n".join(errors) ``` I then print it to the console and send it as an email. On the console it appears delimited by newlines: ``` Error generating re...
If your email is HTML formatted then that would affect presentation of newlines.
Convert list of Fractions to floats in Python
3,578,574
4
2010-08-26T19:05:47Z
3,578,633
9
2010-08-26T19:13:51Z
[ "python", "floating-point", "fractions" ]
I have a list of fractions, such as: ``` data = ['24/221 ', '25/221 ', '24/221 ', '25/221 ', '25/221 ', '30/221 ', '31/221 ', '31/221 ', '31/221 ', '31/221 ', '30/221 ', '30/221 ', '33/221 '] ``` How would I go about converting these to floats, e.g. ``` data = ['0.10 ', '0.11 ', '0.10 ', '0.11 ', '0.13 ', '0.14 ', '...
``` import fractions data = [float(fractions.Fraction(x)) for x in data] ``` or to match your example exactly (data ends up with strings): ``` import fractions data = [str(float(fractions.Fraction(x))) for x in data] ```
How to display utf-8 in windows console
3,578,685
9
2010-08-26T19:19:58Z
3,580,165
7
2010-08-26T22:49:17Z
[ "python", "windows", "utf-8", "console" ]
> I'm using Python 2.6 on Windows 7 I borrowed some code from here: <http://stackoverflow.com/questions/5419/python-unicode-and-the-windows-console> **My goal is to be able to display uft-8 strings in the windows console.** Apparantly in python 2.6, the > sys.setdefaultencoding() is no longer supported However, I...
Never *ever* ***ever*** use `setdefaultencoding`. If you want to write unicode strings to stdio, encode them explicitly. Monkeying around with `setdefaultencoding` will cause stdlib modules and third-party modules alike to break in horrible subtle ways by allowing implicit conversion between `str` and `unicode` when it...
How to display utf-8 in windows console
3,578,685
9
2010-08-26T19:19:58Z
9,642,011
10
2012-03-09T22:46:53Z
[ "python", "windows", "utf-8", "console" ]
> I'm using Python 2.6 on Windows 7 I borrowed some code from here: <http://stackoverflow.com/questions/5419/python-unicode-and-the-windows-console> **My goal is to be able to display uft-8 strings in the windows console.** Apparantly in python 2.6, the > sys.setdefaultencoding() is no longer supported However, I...
I know you state you're using Python 2.6, but if you're able to use Python 3.3 you'll find that this is finally supported. Use the command `chcp 65001` before starting Python. See <http://docs.python.org/dev/whatsnew/3.3.html#codecs>
How do you define config variables / constants in Google App Engine (Python)?
3,578,908
4
2010-08-26T19:46:56Z
3,578,960
10
2010-08-26T19:55:04Z
[ "python", "google-app-engine", "config" ]
I am brand new to python/GAE and am wondering how to quickly define and use global settings variables, so say you git clone my GAE app and you just open `config.yaml`, add change the settings, and the app is all wired up, like this: ``` # config.yaml (or whatever) settings: name: "Lance" domain: "http://example.co...
You can use any Python persistance module, you aren't limited to YAML. Examples: ConfigParser, PyYAML, an XML parser like ElementTree, a settings module like used in Django... ``` # ---------- settings.py NAME = "Lance" DOMAIN = "http://example.com" # ---------- main.py import settings settings.DOMAIN # [...] ```...
How do you determine which backend is being used by matplotlib?
3,580,027
43
2010-08-26T22:23:13Z
3,580,047
51
2010-08-26T22:26:16Z
[ "python", "matplotlib" ]
Either interactively, such as from within an Ipython session, or from within a script, how can you determine which backend is being used by matplotlib?
Use the `get_backend()` function to obtain a string denoting which backend is in use: ``` >>> import matplotlib >>> matplotlib.get_backend() 'TkAgg' ```
Python: virtualenv - gtk-2.0
3,580,520
7
2010-08-27T00:23:02Z
3,580,618
10
2010-08-27T00:55:37Z
[ "python", "virtualenv" ]
To add gtk-2.0 to my virtualenv I did the following: ``` $ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv $ cd myvirtualenv $ source bin/activate $ cd lib/python2.6/ $ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/ ``` <http://stackoverflow.com/questions/249283/virtualenv-on-ubuntu-with-no-site-p...
`sudo python` imports it just fine because that interpreter isn't using your virtual environment. So don't do that. You only linked in one of the necessary items. Do the others mentioned in the answer to the question you linked as well. (The pygtk.pth file is of particular importance, since it tells python to actuall...
Fetching multiple IMAP messages at once
3,581,657
5
2010-08-27T05:52:42Z
3,581,682
11
2010-08-27T05:57:20Z
[ "python", "imap", "imaplib" ]
The examples I've seen about loading emails over IMAP using python do a search and then for each message id in the results, do a query. I want to speed things up by fetching them all at once.
RFC 3501 says fetch takes a sequence set, but I didn't see a definition for that and the example uses a range form (2:4 = messages 2, 3, and 4). I figured out that a comma separated list of ids works. In python with imaplib, I've got something like: ``` status, email_ids = con.search(None, query) if status != ...
Getting HTTP GET arguments in Python
3,582,398
12
2010-08-27T08:16:47Z
3,582,540
30
2010-08-27T08:40:59Z
[ "python", "cgi", "get", "arguments" ]
I'm trying to run an Icecast stream using a simple Python script to pick a random song from the list of songs on the server. I'm looking to add a voting/request interface, and my host allows use of python to serve webpages through CGI. However, I'm getting hung up on just how to get the GET arguments supplied by the us...
cgi.FieldStorage() should do the trick for you... it returns a dictionary with key as the field and value as it's value. ``` import cgi import cgitb; cgitb.enable() # Optional; for debugging only print "Content-Type: text/html" print "" arguments = cgi.FieldStorage() for i in arguments.keys(): print arguments[i].va...
Safe expression parser in Python
3,582,403
11
2010-08-27T08:17:44Z
3,582,719
8
2010-08-27T09:09:43Z
[ "python", "parsing" ]
How can I allow users to execute mathematical expressions in a safe way? Do I need to write a full parser? Is there something like [ast.literal\_eval()](http://docs.python.org/library/ast.html#ast.literal_eval), but for expressions?
The [Pyparsing examples page](http://pyparsing.wikispaces.com/Examples) lists several expression parsers: <http://pyparsing.wikispaces.com/file/view/fourFn.py> - A conventional arithmetic infix notation parser/evaluator implementation using pyparsing (despite its name, this actually does 5-function arithmetic, plus se...
How to call an element in an numpy array?
3,582,601
8
2010-08-27T08:48:53Z
3,582,613
18
2010-08-27T08:51:04Z
[ "python", "arrays", "numpy" ]
This is a really simple question, but I didnt find the answer. How to call an element in an numpy array? ``` import numpy as np arr = np.array([[1,2,3,4,5],[6,7,8,9,10]]) print arr(0,0) ``` The code above doesn't work.
Just use square brackets instead: ``` print arr[1,1] ```
How do I apply a patch from gist to the Django source?
3,582,849
2
2010-08-27T09:28:35Z
3,584,038
7
2010-08-27T12:21:56Z
[ "python", "git", "github", "patch" ]
I want to try out a patch on gist that modifies the source code of Django: [gist: 550436](http://gist.github.com/550436) How do I do it? I have never used git so a step by step instruction would be greatly appreciated.
You can use `patch` to apply diffs. Make sure you're in your django source directory (or wherever you want to apply the patch), and run something like `patch -p1 < downloaded-patch.diff`. You may want to experiment with the `-p` argument if it fails; -p tells `patch` to strip some of the directory prefix for each file...
Compare result from hexdigest() to a string
3,583,265
3
2010-08-27T10:27:37Z
3,583,372
7
2010-08-27T10:40:49Z
[ "python", "string-comparison", "python-2.x", "hashlib" ]
I've got a generated MD5-hash, which I would like to compare to another MD5-hash from a string. The statement below is false, even though they look the same when you print them and should be true. ``` hashlib.md5("foo").hexdigest() == "acbd18db4cc2f85cedef654fccc4a4d8" ``` Google told me that I should encode the resu...
Python 2.7, .hexdigest() does return a str ``` >>> hashlib.md5("foo").hexdigest() == "acbd18db4cc2f85cedef654fccc4a4d8" True >>> type(hashlib.md5("foo").hexdigest()) <type 'str'> ``` Python 3.1 .md5() doesn't take a unicode (which "foo" is), so that needs to be encoded to a byte stream. ``` >>> hashlib.md5("foo").h...
how to check whether list contains only None in python
3,583,860
10
2010-08-27T11:58:29Z
3,583,877
7
2010-08-27T12:01:21Z
[ "python" ]
``` l=[None,None] ``` is there a function that checks whether list l contains only None or not?
Try `any()` - it checks if there is a single element in the list which is considered `True` in a boolean context. `None` evaluates to `False` in a boolean context, so `any(l)` becomes `False`. Note that, to check if a list (and not its contents) is really `None`, `if l is None` must be used. And `if not l` to check if...
how to check whether list contains only None in python
3,583,860
10
2010-08-27T11:58:29Z
3,583,891
17
2010-08-27T12:03:03Z
[ "python" ]
``` l=[None,None] ``` is there a function that checks whether list l contains only None or not?
If you mean, to check if the list `l` contains only None, ``` if all(x is None for x in l): ... ```
how to check whether list contains only None in python
3,583,860
10
2010-08-27T11:58:29Z
3,584,667
16
2010-08-27T13:35:43Z
[ "python" ]
``` l=[None,None] ``` is there a function that checks whether list l contains only None or not?
``` L == [None] * len(L) ``` is much faster than using all() when L *is* all None ``` $ python -m timeit -s'L=[None]*1000' 'all(x is None for x in L)' 1000 loops, best of 3: 276 usec per loop $ python -m timeit -s'L=[None]*1000' 'L==[None]*len(L)' 10000 loops, best of 3: 34.2 usec per loop ```
How to properly add quotes to a string using python?
3,584,005
4
2010-08-27T12:18:43Z
3,584,382
8
2010-08-27T13:02:58Z
[ "python", "string" ]
I want to add a set of (double) quotes to a python string if they are missing but the string can also contain quotes. The purpose of this is to quote all command that are not already quoted because Windows API requires you to quote the entire command line when you execute a process using [\_popen()](http://msdn.micros...
### Your problem is inconsistent. Consider the two cases > `""a" b"` > > `"a" "b"` The former is interpreted as a pre-quoted string with 'nested quotes', but the latter is interpreted as separately-quoted strings. Here are some examples that highlight the issue. > `" "a" "b" "` > > `" "a" b"` > > `"a ""b"` How sho...
Time series forecasting (eventually with python)
3,584,077
23
2010-08-27T12:27:44Z
3,647,719
62
2010-09-05T20:40:09Z
[ "python", "neural-network", "time-series" ]
* What algorithms exist for time series forecasting/regression ? + What about using neural networks ? (best docs about this topic ?) + Are there python libraries/code snippets that can help ?
The classical approaches to time series regression are: * [auto-regressive models](http://en.wikipedia.org/wiki/Autoregressive_model) (there are whole literatures about them) * [Gaussian Processes](http://www.gaussianprocess.org/) * Fourier decomposition or similar to extract the periodic components of the signal (i.e...
Python: get the position of the biggest item in a numpy array
3,584,243
27
2010-08-27T12:46:52Z
3,584,260
64
2010-08-27T12:48:56Z
[ "python", "arrays", "indexing", "numpy" ]
How can I get get the position of the biggest item in a multi-dimensional numpy array?
The [`argmax()`](http://www.scipy.org/Numpy_Example_List#head-e2829234dedbedccc333d32ee2738c28777f2e94) method should help. **Update** (After reading comment) I believe the `argmax()` method would work for multi dimensional arrays as well. The linked documentation gives an example of this: ``` >>> a = array([[10,50,...
In Matplotlib, what does the argument mean in fig.add_subplot(111)?
3,584,805
225
2010-08-27T13:50:42Z
3,584,933
212
2010-08-27T14:05:22Z
[ "python", "matplotlib", "figure" ]
Sometimes I come across code such as this: ``` import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] fig = plt.figure() fig.add_subplot(111) plt.scatter(x, y) plt.show() ``` Which produces: ![Example plot produced by the included code](http://i.stack.imgur.com/yCOG3.png) I've been reading the do...
These are subplot grid parameters encoded as a single integer. For example, "111" means "1x1 grid, first subplot" and "234" means "2x3 grid, 4th subplot". Alternative form for `add_subplot(111)` is `add_subplot(1, 1, 1)`.
In Matplotlib, what does the argument mean in fig.add_subplot(111)?
3,584,805
225
2010-08-27T13:50:42Z
9,850,790
26
2012-03-24T09:59:42Z
[ "python", "matplotlib", "figure" ]
Sometimes I come across code such as this: ``` import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] fig = plt.figure() fig.add_subplot(111) plt.scatter(x, y) plt.show() ``` Which produces: ![Example plot produced by the included code](http://i.stack.imgur.com/yCOG3.png) I've been reading the do...
The answer from Constantin is spot on but for more background this behavior is inherited from Matlab. The Matlab behavior is explained in the [Figure Setup - Displaying Multiple Plots per Figure](http://www.mathworks.com/help/matlab/ref/subplot.html) section of the Matlab documentation. > subplot(m,n,i) breaks the fi...
In Matplotlib, what does the argument mean in fig.add_subplot(111)?
3,584,805
225
2010-08-27T13:50:42Z
11,404,223
245
2012-07-09T22:37:43Z
[ "python", "matplotlib", "figure" ]
Sometimes I come across code such as this: ``` import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [1, 4, 9, 16, 25] fig = plt.figure() fig.add_subplot(111) plt.scatter(x, y) plt.show() ``` Which produces: ![Example plot produced by the included code](http://i.stack.imgur.com/yCOG3.png) I've been reading the do...
I think this would be best explained by the following picture: ![enter image description here](http://i.stack.imgur.com/AEGXG.png) To initialize the above, one would type: ``` import matplotlib.pyplot as plt fig = plt.figure() fig.add_subplot(221) #top left fig.add_subplot(222) #top right fig.add_subplot(223) ...
non-technical benefits of having string-type immutable
3,584,945
16
2010-08-27T14:06:32Z
3,585,432
16
2010-08-27T14:57:49Z
[ "java", "c++", "python", "string", "immutability" ]
I am wondering about the benefits of having the string-type immutable from the programmers point-of-view. Technical benefits (on the compiler/language side) can be summarized mostly that it is easier to do optimisations if the type is immutable. Read [here](http://stackoverflow.com/questions/2916358/immutable-strings-...
> What is the point of having some > types immutable and others not? Without *some* mutable types, you'd have to go the whole hog to pure functional programming -- a completely different paradigm than the OOP and procedural approaches which are currently most popular, and, while extremely powerful, apparently very cha...
How to use less than and equal to in an assert statement in python
3,585,443
2
2010-08-27T14:58:45Z
3,585,478
9
2010-08-27T15:03:17Z
[ "python", "assert", "less" ]
When I run the following: ``` growthRates = [3, 4, 5, 0, 3] for each in growthRates: print each assert growthRates >= 0, 'Growth Rate is not between 0 and 100' assert growthRates <= 100, 'Growth Rate is not between 0 and 100' ``` I get: ``` 3 Traceback (most recent call last): File "ps4.py", line 132, ...
Do: ``` assert each >= 0, 'Growth Rate is not between 0 and 100' ``` not: ``` assert growthRates >= 0, 'Growth Rate is not between 0 and 100' ```
Fastest way to take a screenshot with python on windows
3,586,046
12
2010-08-27T16:03:31Z
3,586,280
18
2010-08-27T16:33:00Z
[ "python", "windows", "screenshot" ]
What's the fastest way to take a screenshot on windows? `PIL.ImageGrab` is rather slow.. it takes between 4-5 seconds to take 30 screenshots of the same small window. Taking screenshots of the whole desktop is even slower.
You could use win32 APIs directly . 1) First give the focus to the App that you want to take screenshot of. [link text](http://stackoverflow.com/questions/1080719/screenshot-an-application-in-python-regardless-of-whats-in-front-of-it "Focus issue is dealt in another question") 2) [Win32 API](http://sourceforge.net/pr...
Perform commands over ssh with Python
3,586,106
45
2010-08-27T16:09:01Z
3,586,153
18
2010-08-27T16:16:21Z
[ "python", "ssh" ]
I'm writing a script to automate some command line commands in Python. At the moment I'm doing calls thus: ``` cmd = "some unix command" retcode = subprocess.call(cmd,shell=True) ``` However I need to run some commands on a remote machine. Manually, I would log in using ssh and then run the commands. How would I auto...
Have you had a look at [Fabric](http://www.fabfile.org)? It allows you to do all sorts of remote stuff over SSH using python.
Perform commands over ssh with Python
3,586,106
45
2010-08-27T16:09:01Z
3,586,168
79
2010-08-27T16:18:03Z
[ "python", "ssh" ]
I'm writing a script to automate some command line commands in Python. At the moment I'm doing calls thus: ``` cmd = "some unix command" retcode = subprocess.call(cmd,shell=True) ``` However I need to run some commands on a remote machine. Manually, I would log in using ssh and then run the commands. How would I auto...
I will refer you to [paramiko](http://www.lag.net/paramiko/) see [this question](http://stackoverflow.com/questions/373639/running-interactive-commands-in-paramiko) ``` ssh = paramiko.SSHClient() ssh.connect(server, username=username, password=password) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_exec...
Perform commands over ssh with Python
3,586,106
45
2010-08-27T16:09:01Z
3,586,368
23
2010-08-27T16:44:46Z
[ "python", "ssh" ]
I'm writing a script to automate some command line commands in Python. At the moment I'm doing calls thus: ``` cmd = "some unix command" retcode = subprocess.call(cmd,shell=True) ``` However I need to run some commands on a remote machine. Manually, I would log in using ssh and then run the commands. How would I auto...
Or you can just use [commands.getstatusoutput](https://docs.python.org/2/library/commands.html#commands.getstatusoutput): ``` commands.getstatusoutput("ssh machine 1 'your script'") ``` I used it extensively and it works great. In Python 2.6+, use [`subprocess.check_output`](https://docs.python.org/3/library/subp...
Perform commands over ssh with Python
3,586,106
45
2010-08-27T16:09:01Z
14,267,719
9
2013-01-10T21:37:06Z
[ "python", "ssh" ]
I'm writing a script to automate some command line commands in Python. At the moment I'm doing calls thus: ``` cmd = "some unix command" retcode = subprocess.call(cmd,shell=True) ``` However I need to run some commands on a remote machine. Manually, I would log in using ssh and then run the commands. How would I auto...
I found paramiko to be a bit too low-level, and Fabric not especially well-suited to being used as a library, so I put together my own library called [spur](http://pypi.python.org/pypi/spur) that uses paramiko to implement a slightly nicer interface: ``` import spur shell = spur.SshShell(hostname="localhost", usernam...
How to avoid NotImplementedError "Only tempfile.TemporaryFile is available for use" in django on Google App Engine?
3,586,134
7
2010-08-27T16:13:09Z
4,319,384
7
2010-11-30T22:30:10Z
[ "python", "django", "google-app-engine", "django-forms" ]
I'm using django 1.1 on Google App Engine through use\_library. No django gae helper, django-nonrel or similar tools are used here. Django handles urls routing, forms validation etc., but I'm using pure appengine models. In one of my django's forms there is a FileField, which from time to time seems to call **django.c...
You need to update the settings.py file with the following to change the default Django behaviour: ``` # only use the memory file uploader, do not use the file system - not able to do so on # google app engine FILE_UPLOAD_HANDLERS = ('django.core.files.uploadhandler.MemoryFileUploadHandler',) FILE_UPLOAD_MAX_MEMORY_SI...
Does urllib2.urlopen() cache stuff?
3,586,295
7
2010-08-27T16:34:27Z
3,586,796
8
2010-08-27T17:41:02Z
[ "python", "urllib2", "urlopen" ]
They didn't mention this in python documentation. And recently I'm testing a website simply refreshing the site using urllib2.urlopen() to extract certain content, I notice sometimes when I update the site urllib2.urlopen() seems not get the newly added content. So I wonder it does cache stuff somewhere, right?
> So I wonder it does cache stuff somewhere, right? It doesn't. If you don't see new data, this could have many reasons. Most bigger web services use server-side caching for performance reasons, for example using caching proxies like Varnish and Squid or application-level caching. If the problem is caused by server-...
Is there a standard way to make sure a python script will be interpreted by python2 and not python3?
3,586,776
21
2010-08-27T17:38:01Z
3,586,806
11
2010-08-27T17:42:36Z
[ "python", "unix", "scripting", "python-3.x", "shebang" ]
Is there a standard way to make sure a python script will be interpreted by python2 and not python3? On my distro, I can use #!/usr/bin/env python2 as the shebang, but it seems not all distros ship "python2". I could explicitly call a specific version (eg. 2.6) of python, but that would rule out people who don't have t...
<http://docs.python.org/library/sys.html#sys.version_info> using the sys module you can determine the version of python that is running and raise an exception or exit or whatever you like. UPDATE: You could use this to call the appropriate interpreter. For example, set up a small script that does the checking for yo...
Is there a standard way to make sure a python script will be interpreted by python2 and not python3?
3,586,776
21
2010-08-27T17:38:01Z
3,587,731
7
2010-08-27T20:00:59Z
[ "python", "unix", "scripting", "python-3.x", "shebang" ]
Is there a standard way to make sure a python script will be interpreted by python2 and not python3? On my distro, I can use #!/usr/bin/env python2 as the shebang, but it seems not all distros ship "python2". I could explicitly call a specific version (eg. 2.6) of python, but that would rule out people who don't have t...
This is a bit of a messy issue during what will be a very long transition time period. Unfortunately, there is no fool-proof, cross-platform way to guarantee which Python version is being invoked, other than to have the Python script itself check once started. Many, if not most, distributions that ship Python 3 are ens...
How to handle empty values in config files with ConfigParser?
3,587,041
5
2010-08-27T18:21:30Z
3,587,078
10
2010-08-27T18:27:42Z
[ "python", "configparser" ]
How can I parse tags with no value in an ini file with python configparser module? For example, I have the following ini and I need to parse rb. In some ini files rb has integer values and on some no value at all like the example below. How can I do that with configparser without getting a valueerror? I use the getint...
You need to set `allow_no_value=True` optional argument when creating the parser object.
Python - Dynamic Nested List
3,587,215
6
2010-08-27T18:49:20Z
3,587,269
11
2010-08-27T18:55:53Z
[ "python", "list", "nested" ]
So I'm trying to generate a nested list in Python based on a width and a height. This is what I have so far: ``` width = 4 height = 5 row = [None]*width map = [row]*height ``` Now, this obviously isn't quite right. When printed it looks fine: ``` [[None, None, None, None], [None, None, None, None], ...
When you do `[row]*height` you end up with the same list object in each row. The `row` array reference is repeated in each row which means each row is actually pointing to the same list object. Hence modifying one row actually modifies all rows. Take a look at what happens when you print the [`id()`](http://docs.pytho...
Check that a function raises a warning with nose tests
3,587,407
7
2010-08-27T19:13:48Z
3,587,600
9
2010-08-27T19:41:26Z
[ "python", "unit-testing", "warnings", "nose" ]
I'm writing unit tests using [nose](http://somethingaboutorange.com/mrl/projects/nose/0.11.2/), and I'd like to check whether a function raises a warning (the function uses `warnings.warn`). Is this something that can easily be done?
``` def your_code(): # ... warnings.warn("deprecated", DeprecationWarning) # ... def your_test(): with warnings.catch_warnings(record=True) as w: your_code() assert len(w) > 1 ``` Instead of just checking the lenght, you can check it in-depth, of course: `assert str(w.args[0]) == "dep...
Foreignkeyfield - verbose name not shown in form
3,587,613
6
2010-08-27T19:43:42Z
3,587,830
9
2010-08-27T20:18:49Z
[ "python", "django", "django-models" ]
my `verbose_name` of a foreignkeyfield isn't printed in my forms. (I create the modelforms via `modelformset_factory` model ``` class MOrders(models.Model): amount = models.IntegerField('Bestellmenge', null=True, blank=True) order_date = models.DateField('Bestelldatum') id = models.AutoField(primary_key=T...
``` m_product_types = models.ForeignKey(MProductTypes, verbose_name = u'Produktart', ) ```
Number of floats between two floats
3,587,880
8
2010-08-27T20:26:50Z
3,587,987
9
2010-08-27T20:43:15Z
[ "python", "floating-point", "ieee-754" ]
Say I have two Python floats `a` and `b`, is there an easy way to find out how many representable real numbers are between the two in IEEE-754 representation (or whatever representation the machine used is using)?
I don'tknow what you will be using this for - but, if both floats have the same exponent, it should be possible. As the exponent is kept on the high order bits, loading the float bytes (8 bytes in this case) as an integer and subtracting one from another should give the number you want. I use the struct model to pack t...
Number of floats between two floats
3,587,880
8
2010-08-27T20:26:50Z
3,588,000
12
2010-08-27T20:45:29Z
[ "python", "floating-point", "ieee-754" ]
Say I have two Python floats `a` and `b`, is there an easy way to find out how many representable real numbers are between the two in IEEE-754 representation (or whatever representation the machine used is using)?
AFAIK, IEEE754 floats have an interesting property. If you have float f, then ``` (*(int*)&f + 1) ``` under certain conditions, is the next representable floating point number. So for floats a and b ``` *(int*)&a - *(int*)&b ``` Will give you the amount of floating point numbers between those numbers. See <http://...
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3'
3,588,083
20
2010-08-27T20:59:08Z
3,588,183
8
2010-08-27T21:16:12Z
[ "python", "character-encoding" ]
I have an Excel spreadsheet that I'm reading in that contains some £ signs. When I try to read it in using the xlrd module, I get the following error: ``` x = table.cell_value(row, col) x = x.decode("ISO-8859-1") UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 0: ordinal not in range(128...
Your code snippet says `x.decode`, but you're getting an **encode** error -- meaning `x` is Unicode already, so, to "decode" it, it must be first turned into a string of bytes (and that's where the default codec `ansi` comes up and fails). In your text then you say "if I rewrite ot to x.**encode**"... which seems to im...
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3'
3,588,083
20
2010-08-27T20:59:08Z
3,588,979
9
2010-08-28T00:47:07Z
[ "python", "character-encoding" ]
I have an Excel spreadsheet that I'm reading in that contains some £ signs. When I try to read it in using the xlrd module, I get the following error: ``` x = table.cell_value(row, col) x = x.decode("ISO-8859-1") UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 0: ordinal not in range(128...
For what it's worth: I'm the author of `xlrd`. Does `xlrd` produce unicode? Option 1: Read the Unicode section at the bottom of the first screenful of `xlrd` doc: **This module presents all text strings as Python unicode objects.** Option 2: `print type(text), repr(text)` You say """If I rewrite this to x.encode(...
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3'
3,588,083
20
2010-08-27T20:59:08Z
11,456,388
18
2012-07-12T16:29:55Z
[ "python", "character-encoding" ]
I have an Excel spreadsheet that I'm reading in that contains some £ signs. When I try to read it in using the xlrd module, I get the following error: ``` x = table.cell_value(row, col) x = x.decode("ISO-8859-1") UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 0: ordinal not in range(128...
A very easy way around all the "'ascii' codec can't encode character…" issues with csvwriter is to instead use [unicodecsv](http://pypi.python.org/pypi/unicodecsv), a drop-in replacement for csvwriter. Install unicodecsv with pip and then you can use it in the exact same way, eg: ``` import unicodecsv file = open('...
how do replace all occurrences of certain characters?
3,588,361
4
2010-08-27T21:50:24Z
3,588,390
18
2010-08-27T21:55:00Z
[ "python", "csv" ]
I am reading a csv into `a`: ``` import csv import collections import pdb import math import urllib def do_work(): a=get_file('c:/pythonwork/cds/cds.csv') a=remove_chars(a) print a[0:10] def get_file(start_file): #opens original file, reads it to array with open(start_file,'rb') as f: data=list(csv.reade...
The problem is you're not doing anything with the result of `replace`. In Python strings are immutable so anything that manipulates a string returns a new string instead of modifying the original string. ``` line[8] = line[8].replace(letter, "") ```
How is __eq__ handled in Python and in what order?
3,588,776
28
2010-08-27T23:34:19Z
3,588,809
42
2010-08-27T23:45:53Z
[ "python", "comparison", "user-defined" ]
Since Python does not provide left/right versions of its comparison operators, how does it decide which function to call? ``` class A(object): def __eq__(self, other): print "A __eq__ called" return self.value == other class B(object): def __eq__(self, other): print "B __eq__ called" ...
The `a == b` expression invokes `A.__eq__`, since it exists. Its code includes `self.value == other`. Since int's don't know how to compare themselves to B's, Python tries invoking `B.__eq__` to see if it knows how to compare itself to an int. If you amend your code to show what values are being compared: ``` class A...
How is __eq__ handled in Python and in what order?
3,588,776
28
2010-08-27T23:34:19Z
12,984,987
31
2012-10-20T03:28:45Z
[ "python", "comparison", "user-defined" ]
Since Python does not provide left/right versions of its comparison operators, how does it decide which function to call? ``` class A(object): def __eq__(self, other): print "A __eq__ called" return self.value == other class B(object): def __eq__(self, other): print "B __eq__ called" ...
When Python2.x sees `a == b`, it tries the following. * If `type(b)` is a new-style class, and `type(b)` is a subclass of `type(a)`, and `type(b)` has overridden `__eq__`, then the result is `b.__eq__(a)`. * If `type(a)` has overridden `__eq__` (that is, `type(a).__eq__` isn’t `object.__eq__`), then the result is `a...
Where is my local App Engine datastore?
3,588,817
10
2010-08-27T23:49:26Z
3,588,898
8
2010-08-28T00:19:33Z
[ "python", "google-app-engine", "gae-datastore" ]
How can I find where my local development datastore is located? I am using the *Python SDK* and *Linux*.
I think it depends on if you got Java or Python SDK. For Python, here's what the instructions say from Google: "The web server prints the location of the datastore file it is using to the terminal when it starts up. You can make a copy of the file, then restore them later to reset the datastore to a known state. Be su...
Where is my local App Engine datastore?
3,588,817
10
2010-08-27T23:49:26Z
3,593,315
10
2010-08-29T02:28:48Z
[ "python", "google-app-engine", "gae-datastore" ]
How can I find where my local development datastore is located? I am using the *Python SDK* and *Linux*.
I'm using Windows 7 with the Python SDK. My local datastore is located at ``` C:\Users\[username]\AppData\Local\Temp\dev_appserver.datastore ```
Generate multiple random numbers to equal a value in python
3,589,214
23
2010-08-28T02:37:01Z
3,589,261
12
2010-08-28T02:54:43Z
[ "python", "random" ]
So here is the deal: I want to (for example) generate 4 pseudo-random numbers, that when added together would equal 40. How could this be dome in python? I could generate a random number 1-40, then generate another number between 1 and the remainder,etc, but then the first number would have a greater chance of "grabbin...
``` b = random.randint(2, 38) a = random.randint(1, b - 1) c = random.randint(b + 1, 39) return [a, b - a, c - b, 40 - c] ``` (I assume you wanted integers since you said "1-40", but this could be easily generalized for floats.) Here's how it works: * cut the total range in two randomly, that's b. The odd range is b...
Generate multiple random numbers to equal a value in python
3,589,214
23
2010-08-28T02:37:01Z
3,590,105
54
2010-08-28T08:46:02Z
[ "python", "random" ]
So here is the deal: I want to (for example) generate 4 pseudo-random numbers, that when added together would equal 40. How could this be dome in python? I could generate a random number 1-40, then generate another number between 1 and the remainder,etc, but then the first number would have a greater chance of "grabbin...
Here's the standard solution. It's similar to Laurence Gonsalves' answer, but has two advantages over that answer. (1) It's uniform: each combination of 4 positive integers adding up to 40 is equally likely to come up with this scheme, and (2) it's easy to adapt to other totals (7 numbers adding up to 100, etc.): ``` ...
Get defining class of unbound method object in Python 3
3,589,311
14
2010-08-28T03:12:47Z
3,589,335
23
2010-08-28T03:20:19Z
[ "python", "python-3.x" ]
Say I want to make a decorator for methods defined in a class. I want that decorator, when invoked, to be able to set an attribute on the class defining the method (in order to register it in a list of methods that serve a particular purpose). In Python 2, the `im_class` method accomplishes this nicely: ``` def decor...
The point you appear to be missing is, in Python 3 the "unbound method" type has entirely disappeared -- a method, until and unless it's bound, is just a function, without the weird "type-checking" unbound methods used to perform. This makes the language simpler! To wit...: ``` >>> class X: ... def Y(self): pass .....
Get defining class of unbound method object in Python 3
3,589,311
14
2010-08-28T03:12:47Z
25,959,545
19
2014-09-21T13:10:14Z
[ "python", "python-3.x" ]
Say I want to make a decorator for methods defined in a class. I want that decorator, when invoked, to be able to set an attribute on the class defining the method (in order to register it in a list of methods that serve a particular purpose). In Python 2, the `im_class` method accomplishes this nicely: ``` def decor...
I thought it would be worthwhile writing something that does it best at guessing the defining class. For completeness' sake this answer also addresses bound methods. At worst, guessing should fail altogether, with the function returning `None`. However, under any circumstances, it shouldn't return an incorrect class. ...
Efficient way to read a specific line number of a file. (BONUS: Python Manual Misprint)
3,589,327
6
2010-08-28T03:17:54Z
3,589,364
8
2010-08-28T03:31:04Z
[ "c#", ".net", "python", "file" ]
I have a 100 GB text file, which is a BCP dump from a database. When I try to import it with `BULK INSERT`, I get a cryptic error on line number 219506324. Before solving this issue I would like to see this line, but alas my favorite method of ``` import linecache print linecache.getline(filename, linenumber) ``` is ...
Here's my elegant version in C#: ``` Console.Write(File.ReadLines(@"s:\source\transactions.dat").ElementAt(219506323)); ``` or more general: ``` Console.Write(File.ReadLines(filename).ElementAt(linenumber - 1)); ``` Of course, you may want to show some context before and after the given line: ``` Console.Write(str...
Joining List has integer values with python
3,590,165
98
2010-08-28T09:07:38Z
3,590,168
194
2010-08-28T09:09:59Z
[ "python", "string", "list" ]
I need to join a list of items. Many of the items in the list are integer values returned from a function. ie: ``` myList.append(munfunc()) ``` How should I convert the returned result to a string in order to join it with the list? Do i need to do the following for every integer value : ``` myList.append (str(myfun...
Calling `str(...)` is the Pythonic way to convert something to a string. You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can do this: ...
Joining List has integer values with python
3,590,165
98
2010-08-28T09:07:38Z
3,590,175
58
2010-08-28T09:11:48Z
[ "python", "string", "list" ]
I need to join a list of items. Many of the items in the list are integer values returned from a function. ie: ``` myList.append(munfunc()) ``` How should I convert the returned result to a string in order to join it with the list? Do i need to do the following for every integer value : ``` myList.append (str(myfun...
I'm not really sure what you mean by "join", because the grammar you use in your question is pretty bad, but if I understand your question correctly, there's nothing wrong with passing integers to str. One reason you might not do this is that myList is really supposed to be a list of integers e.g. it would be reasonabl...
Joining List has integer values with python
3,590,165
98
2010-08-28T09:07:38Z
32,477,633
7
2015-09-09T10:55:00Z
[ "python", "string", "list" ]
I need to join a list of items. Many of the items in the list are integer values returned from a function. ie: ``` myList.append(munfunc()) ``` How should I convert the returned result to a string in order to join it with the list? Do i need to do the following for every integer value : ``` myList.append (str(myfun...
map function in python can be used. It takes two arguments. First argument is the **function** which has to be used for each element of the list. Second argument is the **iterable**. ``` a = [1, 2, 3] map(str, a) ['1', '2', '3'] ``` After converting the list into string you can use simple **join** function to co...
django static annotation
3,590,306
6
2010-08-28T10:03:27Z
36,719,467
11
2016-04-19T13:10:26Z
[ "python", "django" ]
I want to add a static value to the results of a database query using django (so not using 'raw' SQL) For example, if I have an object Car with fields make, model, and color, then I want my results set with extra static value to look something like this: ``` make model color sales ---- ----- ----- ...
As of Django 1.8, `annotate` features [`Value` expression](https://docs.djangoproject.com/en/1.9/ref/models/expressions/#value-expressions): ``` cars= Car.objects.all().annotate(sales=Value(0, IntegerField())) ``` Instead of `IntegerField` you can use all available db fields classes.
Federated identity on Google App Engine
3,590,335
6
2010-08-28T10:11:48Z
3,591,050
11
2010-08-28T14:18:01Z
[ "python", "google-app-engine", "openid", "federated-identity" ]
I am successful with the both methods below, to log on using federated log in for my site on Google App Engine (Python) ``` users.create_login_url("\", "google", "https://www.google.com/accounts/o8/id") users.create_login_url("\", "yahoo", "http://open.login.yahooapis.com/openid20/www.yahoo.com/xrds") ``` I wish to p...
Google [documentation](https://developers.google.com/appengine/articles/openid) mentions following direct providers of federated identities ... * google.com/accounts/o8/id (shorter alternative: gmail.com) * yahoo.com * myspace.com * aol.com * myopenid.com ... as well as username provider federated identities: * flic...
Uses of Jython while programming
3,591,171
5
2010-08-28T14:53:07Z
3,591,212
14
2010-08-28T15:04:08Z
[ "python", "jython" ]
I recently started learning Python and came accross the term [Jython](http://en.wikipedia.org/wiki/Jython). From the Google search results, I thereby concluded that it is indeed a very important term. What is the experience programming/coding using Jython?
[Jython](http://www.jython.org/) is just an implementation of the Python interpreter that runs on the JVM (Java Virtual Machine). > ### What is JPython? > > JPython is an implementation of the > Python programming language which is > designed to run on the Java(tm) > Platform. It consists of a compiler to > compile Py...
Why are sets bigger than lists in python?
3,591,727
9
2010-08-28T17:29:08Z
3,591,734
15
2010-08-28T17:33:53Z
[ "python", "list", "set" ]
Why is the size of sets in Python noticeably larger than that of lists with same elements? ``` a = set(range(10000)) b = list(range(10000)) print('set size = ', a.__sizeof__()) print('list size = ', b.__sizeof__()) ``` output: ``` set size = 524488 list size = 90088 ```
The `set` uses more memory than the `list` as it stores a table of hashes of all the elements so it can quickly detect duplicate entries and so on. This is why every set member must [be `hashable`](http://docs.python.org/glossary.html#term-hashable).
Python import X or from X import Y? (performance)
3,591,962
17
2010-08-28T18:36:56Z
3,591,972
8
2010-08-28T18:40:23Z
[ "python", "performance" ]
I'm just wondering - if there is a library from which I'm going to use at least 2 methods, is there any difference in performance or ram usage between: from X import method1, method2 and this import X I know about namespaces and stuff, but I'm just wondering if python is smart enough to know that I'll use only 2 method...
There is no memory or speed difference (the whole module has to be evaluated either way, because the last line could be `Y = something_else`). Unless your computer is from the 1980s it doesn't matter anyways.
Python import X or from X import Y? (performance)
3,591,962
17
2010-08-28T18:36:56Z
3,592,137
23
2010-08-28T19:31:29Z
[ "python", "performance" ]
I'm just wondering - if there is a library from which I'm going to use at least 2 methods, is there any difference in performance or ram usage between: from X import method1, method2 and this import X I know about namespaces and stuff, but I'm just wondering if python is smart enough to know that I'll use only 2 method...
There is a difference, because in the `import x` version there are two name lookups: one for the module name, and the second for the function name; on the other hand, using `from x import y`, you have only one lookup. You can see this quite well, using the dis module: ``` import random def f_1(): random.seed() d...
Export mail from Gmail
3,592,015
5
2010-08-28T18:52:16Z
3,592,032
8
2010-08-28T18:58:09Z
[ "python", "gmail" ]
At one point it was possible to use scripts like [libgmail](http://libgmail.sourceforge.net/) and gmail.py (can't post more than one hyperlink) to export mail from Gmail accounts. Both of those seem to not work anymore — I can't even log in with them. I assume it's because there's been some changes in Gmail. Is ther...
Gmail [supports IMAP](http://mail.google.com/support/bin/answer.py?hl=en&ctx=mail&answer=75725) and [POP](http://mail.google.com/support/bin/answer.py?hl=en&ctx=mail&answer=10350), which are common protocols for accessing email. You should be able to use use any working IMAP or POP library for Python to download your e...
Iterative printing over parallel lists to print columns in Python
3,593,040
2
2010-08-29T00:23:07Z
3,593,043
8
2010-08-29T00:25:30Z
[ "python", "list", "collections", "printing" ]
I have vsort and vsorta, both lists with equal numbers of items that should be right next to each other (about 250 elements per list). I want to print them as parallel columns, like so: ``` >>> for x,y in vsort,vsorta: ... print x, y ... Traceback (most recent call last): File "<stdin>", line 1, in <module> Val...
Try: ``` for x, y in zip(vsort, vsorta): print x, y ``` `zip` takes some number of lists and makes them into one list of tuples.
Add page break to Reportlab Canvas object
3,593,193
6
2010-08-29T01:31:36Z
3,593,232
15
2010-08-29T01:48:43Z
[ "python", "reportlab" ]
I need to generate a 2 pages pdf report. Pages are completely independent. tried using: ``` mycanvas.drawString(x, y, "Printing on Page 1") mycanvas._pageNumer = 2 mycanvas.drawString(x, y, "Printing on Page 2") ``` and: ``` mycanvas.drawString(x, y, "Printing on Page 1") P = PageBreak() P.drawOn(mycanvas, 0, 1000) ...
Just call `mycanvas.showPage()` once page 1 is done -- this way, the rest of the output goes to page 2. See [the docs](http://python-reportlab.sourcearchive.com/documentation/2.1dfsg-2/classreportlab_1_1pdfgen_1_1canvas_1_1Canvas_59e0175d607333b23b5bad9c58763a5c.html).
How to remove elements from XML using Python
3,593,204
8
2010-08-29T01:38:42Z
3,593,300
9
2010-08-29T02:18:25Z
[ "python", "xml" ]
I got stuck with XML and Python. The task is simple but I couldn't resolve it so far and spent on that long time. I came here for an advice how to solve it with couple of lines. Thanks for any help with traversing the tree. I always ended up with too many or too few elements. Elements can be nested without limit. Give...
Using [lxml](http://lxml.de/): ``` import lxml.etree as le with open('doc.xml','r') as f: doc=le.parse(f) for elem in doc.xpath('//*[attribute::lang]'): if elem.attrib['lang']=='en': elem.attrib.pop('lang') else: parent=elem.getparent() parent.remove(elem) ...
Why doesn't sys.stdout.write('\b') backspace against newlines?
3,593,339
8
2010-08-29T02:42:14Z
3,593,352
16
2010-08-29T02:49:55Z
[ "python" ]
Compare: ``` for item in range(0, 5): sys.stdout.write('c') for item in range(0, 5): sys.stdout.write('\b') ``` Works as you would imagine, but: ``` for item in range(0, 5): sys.stdout.write('\n') for item in range(0, 5): sys.stdout.write('\b') ``` still leaves you with five newline characters. Any ...
It may seem reasonable today to expect backspace to be able to work over newline characters, on a console but that would not be backward compatible with teletypes as there is no reverse linefeed.
How do I make bar plots automatically cycle across different colors?
3,593,578
11
2010-08-29T04:58:14Z
3,593,716
22
2010-08-29T05:57:16Z
[ "python", "colors", "matplotlib", "plot", "color-scheme" ]
In `matplotlib`, line plots color cycle automatically. These two line plots would have different colors. ``` axes.plot(x1, y) axes.plot(x2, y) ``` However, bar plots don't. Both these data series will have blue bars. ``` axes.bar(x1, y) axes.bar(x2, y) ``` How do I make bar plots cycle automatically across a predef...
Would something along these lines do it for you? ``` #!/usr/bin/python from matplotlib import cm import matplotlib.pyplot as plt #data x=[1,2,4] y=[11,12,8] for i in range(0,len(x)): plt.bar(x[i],y[i],color=cm.jet(1.*i/len(x))) plt.show() ``` More on [colormaps](http://matplotlib.org/1.2.1/examples/pylab_exampl...
Real-world Jython applications
3,593,861
6
2010-08-29T07:01:59Z
3,593,873
10
2010-08-29T07:10:28Z
[ "python", "jython" ]
I recently started learning Python. Not yet ventured into coding. During one of my learning sessions, i came accross the term Jython. I googled it & got some information. I would like to know if anyone has implemented any real-world program using Jython.
Most of the time, Jython isn't used directly to write full read-world programs, but a lot of programs actually embed Jython to use it as a scripting language. The official Jython website gives a list of projects, some written in Jython, others using Jython for scripting: <http://wiki.python.org/jython/JythonUsers>
How to find most common elements of a list?
3,594,514
16
2010-08-29T11:21:21Z
3,594,522
33
2010-08-29T11:25:12Z
[ "python", "list", "frequency" ]
Given the following list ``` ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cat...
In Python 2.7 and above there is a class called [Counter](http://docs.python.org/dev/library/collections.html#counter-objects) which can help you: ``` from collections import Counter words_to_count = (word for word in word_list if word[:1].isupper()) c = Counter(words_to_count) print c.most_common(3) ``` Result: ```...
How to find most common elements of a list?
3,594,514
16
2010-08-29T11:21:21Z
3,594,640
8
2010-08-29T12:05:50Z
[ "python", "list", "frequency" ]
Given the following list ``` ['Jellicle', 'Cats', 'are', 'black', 'and', 'white,', 'Jellicle', 'Cats', 'are', 'rather', 'small;', 'Jellicle', 'Cats', 'are', 'merry', 'and', 'bright,', 'And', 'pleasant', 'to', 'hear', 'when', 'they', 'caterwaul.', 'Jellicle', 'Cats', 'have', 'cheerful', 'faces,', 'Jellicle', 'Cat...
If you are using an earlier version of Python or you have a very good reason to roll your own word counter (I'd like to hear it!), you could try the following approach using a `dict`. ``` Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits"...
Properties file in python (similar to Java Properties)
3,595,363
66
2010-08-29T15:36:29Z
3,595,383
38
2010-08-29T15:39:56Z
[ "python", "properties" ]
Given the following format (**.properties** or **.ini**): ``` propertyName1=propertyValue1 propertyName2=propertyValue2 ... propertyNameN=propertyValueN ``` For **Java** there is the [Properties](http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html) class that offers functionality to parse / interact wi...
For .ini files there is the [ConfigParser](http://docs.python.org/library/configparser.html) module that provides a format compatible with .ini files. Anyway there's nothing available for parsing complete .properties files, when I have to do that I simply use jython (I'm talking about scripting).
Properties file in python (similar to Java Properties)
3,595,363
66
2010-08-29T15:36:29Z
8,220,790
47
2011-11-22T01:13:13Z
[ "python", "properties" ]
Given the following format (**.properties** or **.ini**): ``` propertyName1=propertyValue1 propertyName2=propertyValue2 ... propertyNameN=propertyValueN ``` For **Java** there is the [Properties](http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html) class that offers functionality to parse / interact wi...
A java properties file is often valid python code as well. You could rename your myconfig.properties file to myconfig.py. Then just import your file, like this ``` import myconfig ``` and access the properties directly ``` print myconfig.propertyName1 ```
Properties file in python (similar to Java Properties)
3,595,363
66
2010-08-29T15:36:29Z
8,319,992
9
2011-11-30T01:16:25Z
[ "python", "properties" ]
Given the following format (**.properties** or **.ini**): ``` propertyName1=propertyValue1 propertyName2=propertyValue2 ... propertyNameN=propertyValueN ``` For **Java** there is the [Properties](http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html) class that offers functionality to parse / interact wi...
If you have an option of file formats I suggest using .ini and Python's ConfigParser as mentioned. If you need compatibility with Java .properties files I have written a library for it called [jprops](http://mgood.github.com/jprops/). We were using pyjavaproperties, but after encountering various limitations I ended up...
Properties file in python (similar to Java Properties)
3,595,363
66
2010-08-29T15:36:29Z
26,221,097
22
2014-10-06T16:59:40Z
[ "python", "properties" ]
Given the following format (**.properties** or **.ini**): ``` propertyName1=propertyValue1 propertyName2=propertyValue2 ... propertyNameN=propertyValueN ``` For **Java** there is the [Properties](http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html) class that offers functionality to parse / interact wi...
I was able to get this to work with `ConfigParser`, no one showed any examples on how to do this, so here is a simple python reader of a property file and example of the property file. Note that the extension is still `.properties`, but I had to add a section header similar to what you see in .ini files... a bit of a b...
Properties file in python (similar to Java Properties)
3,595,363
66
2010-08-29T15:36:29Z
31,852,401
17
2015-08-06T09:47:06Z
[ "python", "properties" ]
Given the following format (**.properties** or **.ini**): ``` propertyName1=propertyValue1 propertyName2=propertyValue2 ... propertyNameN=propertyValueN ``` For **Java** there is the [Properties](http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html) class that offers functionality to parse / interact wi...
I know that this is a very old question, but I need it just now and I decided to implement my own solution, a pure python solution, that covers most uses cases (not all): ``` def load_properties(filepath, sep='=', comment_char='#'): """ Read the file passed as parameter as a properties file. """ props ...
How to send an e-mail from a Python script that is being run on "Google App Engine"?
3,595,438
5
2010-08-29T15:54:53Z
3,595,516
10
2010-08-29T16:13:44Z
[ "python", "google-app-engine", "email" ]
How could I send an e-mail from my Python script that is being run on ["**Google App Engines**"](http://code.google.com/intl/en/appengine/) to one of my mail boxes? I am just a beginner and I have never tried sending a message from a Python script. I have found this script [**(IN THIS TUTORIAL)**](http://www.yak.net/f...
Sure - just use the Mail API as outlined in the docs: * [Python](http://code.google.com/appengine/docs/python/mail/overview.html#Sending_Mail_in_Python) * [Java](http://code.google.com/appengine/docs/java/mail/usingjavamail.html)
Running multiple instances of a python program efficiently & economically?
3,596,029
5
2010-08-29T18:26:49Z
3,596,255
9
2010-08-29T19:31:52Z
[ "python", "numpy", "cython" ]
I wrote a program that calls a function with the following prototype: ``` def Process(n): # the function uses data that is stored as binary files on the hard drive and # -- based on the value of 'n' -- scans it using functions from numpy & cython. # the function creates new binary files and saves the...
Check out PiCloud: <http://www.picloud.com/> ``` import cloud cloud.call(function) ``` Maybe it's an easy solution.
Is it possible to change the color of one individual pixel in Python?
3,596,433
12
2010-08-29T20:18:51Z
3,606,295
15
2010-08-31T05:38:14Z
[ "python", "python-imaging-library", "pixel" ]
I need python to change the color of one individual pixel on a picture, how do I go about that?
To build upon the example given in Gabi Purcaru's [link](http://stackoverflow.com/questions/138250/read-the-rgb-value-of-a-given-pixel-in-python-programaticly), here's something cobbled together from the [PIL docs](http://www.pythonware.com/library/pil/handbook/image.htm). The simplest way to reliably modify a single ...
How to get (sub)class name from a static method in Python?
3,596,641
15
2010-08-29T21:18:13Z
3,596,670
22
2010-08-29T21:25:43Z
[ "python", "reflection", "function-call", "static-methods" ]
If I define: ``` class Bar(object): @staticmethod def bar(): # code pass class Foo(Bar): # code pass ``` Is it possible for a function call Foo.bar() to determine the class name Foo?
Replace the staticmethod with a classmethod. This will be passed the class when it is called, so you can get the class name from that. ``` class Bar(object): @classmethod def bar(cls): # code print cls.__name__ class Foo(Bar): # code pass >>> Bar.bar() Bar >>> Foo.bar() Foo ```
MANIFEST.in ignored on "python setup.py install" - no data files installed?
3,596,979
36
2010-08-29T23:12:50Z
3,597,263
38
2010-08-30T01:09:13Z
[ "python", "build", "install", "distutils" ]
Here's my stripped-down setup.py script with non-code stuff removed: ``` #!/usr/bin/env python from distutils.core import setup from whyteboard.misc import meta setup( name = 'Whyteboard', version = meta.version, packages = ['whyteboard', 'whyteboard.gui', 'whyteboard.lib', 'whyteboard.lib.pubsub', ...
`MANIFEST.in` tells Distutils what files to include in the source distribution but it does not directly affect what files are installed. For that you need to include the appropriate files in the `setup.py` file, generally either as [package data](http://docs.python.org/distutils/setupscript.html#installing-package-data...
MANIFEST.in ignored on "python setup.py install" - no data files installed?
3,596,979
36
2010-08-29T23:12:50Z
3,600,913
17
2010-08-30T13:45:42Z
[ "python", "build", "install", "distutils" ]
Here's my stripped-down setup.py script with non-code stuff removed: ``` #!/usr/bin/env python from distutils.core import setup from whyteboard.misc import meta setup( name = 'Whyteboard', version = meta.version, packages = ['whyteboard', 'whyteboard.gui', 'whyteboard.lib', 'whyteboard.lib.pubsub', ...
Some notes in addition to Ned's answer (which hits on the core problem): Distutils does not install Python packages and modules inside a per-project subdirectory within `site-packages` (or `dist-packages` on Debian/Ubuntu): they are installed directly into `site-packages`, as you've seen. So the containing `whyteboard...
MANIFEST.in ignored on "python setup.py install" - no data files installed?
3,596,979
36
2010-08-29T23:12:50Z
7,288,382
7
2011-09-02T19:30:31Z
[ "python", "build", "install", "distutils" ]
Here's my stripped-down setup.py script with non-code stuff removed: ``` #!/usr/bin/env python from distutils.core import setup from whyteboard.misc import meta setup( name = 'Whyteboard', version = meta.version, packages = ['whyteboard', 'whyteboard.gui', 'whyteboard.lib', 'whyteboard.lib.pubsub', ...
Running python 2.6.1 on Mac OSX, I had absolutely no luck except by using the **data\_files** parameter in setup.py. Everything with MANIFEST.in simply resulted in files being included in the dist package, but never installed. I checked some other packages and they were indeed using data\_files to specify additional fi...
create a tar file in a string using python
3,597,382
2
2010-08-30T01:49:51Z
3,597,489
14
2010-08-30T02:30:54Z
[ "python", "tar" ]
I need to generate a tar file but as a string in memory rather than as an actual file. What I have as input is a single filename and a string containing the assosiated contents. I'm looking for a python lib I can use and avoid having to role my own. --- A little more work found [these functions](http://www.daniweb.co...
Use [tarfile](http://docs.python.org/library/tarfile.html) in conjunction with [cStringIO](http://docs.python.org/library/stringio.html#module-cStringIO): ``` c = cStringIO.StringIO() t = tarfile.open(mode='w', fileobj=c) # here: do your work on t, then...: s = c.getvalue() # extract the bytestring you need ```
avoid regex [python]
3,597,399
2
2010-08-30T01:57:39Z
3,597,413
17
2010-08-30T02:05:29Z
[ "python", "regex" ]
I'd like to know if it's a good idea avoid regex. actually I have avoided it in any case and some peoples has been giving me advice that i shouldn't avoid it, since if you know what means every thing like: > > [] '|' \A \B \d \D \W \w \S \Z $ \* ? ... it would be easy to read, right? but i fell like avoiding regex i...
No, don't avoid regular expressions. They're actually quite a nifty little tool and will save you a lot of work if you use them wisely. What you *do* need to avoid is trying to use it for everything, a malaise that appears to strike those new to regular expressions before they become a little more tempered and a littl...
How to make python 3 print() utf8
3,597,480
21
2010-08-30T02:26:24Z
3,597,849
9
2010-08-30T04:20:19Z
[ "python", "utf-8", "printing", "python-3.x", "stdout" ]
How to make python 3 (3.1) to print("Some text") to stdout in utf8 ... or how to output raw bytes.. Test.py > ``` > TestText = "Test - āĀēĒčČ..šŠūŪžŽ" # this is UTF-8 > TestText2 = b"Test2 - \xc4\x81\xc4\x80\xc4\x93\xc4\x92\xc4\x8d\xc4\x8c..\xc5\xa1\xc5\xa0\xc5\xab\xc5\xaa\xc5\xbe\xc5\xbd" # just byte...
This is the best I can dope out from the manual, and it's a bit of a dirty hack: ``` utf8stdout = open(1, 'w', encoding='utf-8', closefd=False) # fd 1 is stdout print(whatever, file=utf8stdout) ``` It seems like file objects should have a method to change their encoding, but AFAICT there isn't one. If you write to u...
How to make python 3 print() utf8
3,597,480
21
2010-08-30T02:26:24Z
3,603,160
35
2010-08-30T18:31:26Z
[ "python", "utf-8", "printing", "python-3.x", "stdout" ]
How to make python 3 (3.1) to print("Some text") to stdout in utf8 ... or how to output raw bytes.. Test.py > ``` > TestText = "Test - āĀēĒčČ..šŠūŪžŽ" # this is UTF-8 > TestText2 = b"Test2 - \xc4\x81\xc4\x80\xc4\x93\xc4\x92\xc4\x8d\xc4\x8c..\xc5\xa1\xc5\xa0\xc5\xab\xc5\xaa\xc5\xbe\xc5\xbd" # just byte...
First, a correction: ``` TestText = "Test - āĀēĒčČ..šŠūŪžŽ" # this NOT utf-8...it is a Unicode string in Python 3.X. TestText2 = TestText.encode('utf8') # THIS is "just bytes" in UTF-8. ``` Now, to send UTF-8 to stdout, regardless of the console's encoding, use the right tool for the job: ``` import sys ...