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
"pythonic" method to parse a string of comma-separated integers into a list of integers?
3,477,502
5
2010-08-13T13:56:24Z
3,477,535
12
2010-08-13T13:59:54Z
[ "python" ]
I am reading in a string of integers such as `"3 ,2 ,6 "` and want them in the list `[3,2,6]` as integers. This is easy to hack about, but what is the "pythonic" way of doing it?
``` map( int, myString.split(',') ) ```
Java - How to do Python's Try Except Else
3,478,222
22
2010-08-13T15:14:10Z
3,478,608
16
2010-08-13T15:57:25Z
[ "java", "python", "exception" ]
How do I do a try except else in Java like I would in Python? Example: ``` try: something() except SomethingException,err: print 'error' else: print 'succeeded' ``` I see try and catch mentioned but nothing else.
I'm not entirely convinced that I like it, but this would be equivalent of Python's else. It eliminates the problem's identified with putting the success code at the end of the try block. ``` bool success = true; try { something(); } catch (Exception e) { success = false; // other exception handling } if (...
How do I dynamically add an attribute to a module from within that module?
3,478,716
3
2010-08-13T16:10:50Z
3,478,793
10
2010-08-13T16:20:22Z
[ "python" ]
Say in a module I want to define: ``` a = 'a' b = 'b' ... z = 'z' ``` For some set (in this case I chose letters). How do I dynamically set attributes on the current module? Something like: ``` for letter in ['a', ..., 'z']: setattr(globals(), letter, letter) ``` This doesn't work, but what would? (Also my unde...
globals() returns the dictionary of the current module, so you add items to it as you would to any other dictionary. Try: ``` for letter in ['a', ..., 'z']: globals()[letter] = letter ``` or to eliminate the repeated call to globals(): ``` global_dict = globals() for letter in ['a', ..., 'z']: global_dict[le...
Is it good style to call bash commands within a Python script using os.system("bash code")?
3,479,728
7
2010-08-13T18:35:28Z
3,479,981
12
2010-08-13T19:05:32Z
[ "python", "security", "bash", "scripting", "embedding" ]
I was wondering whether or not it is considered a good style to call bash commands within a Python script using os.system(). I was also wondering whether or not it is safe to do so as well. I know how to implement some of the functionality I need in Bash and in Python, but it is much simpler and more intuitive to impl...
First of all, your example uses *mv*, which is a program in *coreutils*, not bash. Using os.system() calls to external programs is considered poor style because: * You are creating platform-specific dependencies * You are creating version-specific dependencies (Yes, even coreutils change sometimes!) * You need to che...
Distribute points on a circle as evenly as possible
3,479,736
29
2010-08-13T18:37:08Z
3,479,843
10
2010-08-13T18:50:42Z
[ "python", "algorithm", "geometry" ]
## Problem statement I have the following problem: I have a circle with a certain number (zero or more) of points on it. These positions are fixed. Now I have to position another set of points on the circle, such as all points together are as evenly distributed around the circle as possible. ## Goal My goal is now t...
Suppose you have `M` points already given, and `N` more need to be added. If all points were evenly spaced, then you would have gaps of `2*pi/(N+M)` between them. So, if you cut at your `M` points to give `M` segments of angle, you can certainly place points into a segment (evenly spaced from each other) until the spac...
Unicode error using matplotlib with log scale on Windows
3,479,887
5
2010-08-13T18:55:01Z
3,731,322
8
2010-09-16T22:24:25Z
[ "python", "matplotlib" ]
I'm using python 2.6 and matplotlib. If I run the sample histogram\_demo.py provided in the matplotlib gallery page, it works fine. I've simplified this script greatly: ``` import numpy as np import matplotlib.pyplot as plt mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) fig = plt.figure() ax = fig.add_s...
This is a bug in the font management of matplotlib, on my machine this is the file /usr/lib/pymodules/python2.6/matplotlib/font\_manager.py:1220. I've highlighted the change in the code snippet below; this is fixed in the newest version of matplotlib. ``` if best_font is None or best_score >= 10.0: verbose.report(...
Python proxy.. A simple one!
3,480,147
6
2010-08-13T19:34:48Z
3,480,314
7
2010-08-13T20:05:08Z
[ "python", "proxy" ]
I have been surfing around on google, googling away in order to find the source of a Python HTTP proxy server, because i wish to write my own. Good news is: I found lots! Bad news is: I think they are too complicated. At least for me to properly grasp. I have seen python do stuff like this before in very simple and com...
One incredibly simple one is [python-proxy](http://code.google.com/p/python-proxy/). I found it on the list of python proxies at [xhaus](http://proxies.xhaus.com/python/), which was the top result when I googled "python proxy server" (sans quotes).
Unpack a list in Python?
3,480,184
80
2010-08-13T19:40:06Z
3,480,190
98
2010-08-13T19:40:59Z
[ "python", "list", "argument-passing" ]
I think 'unpack' might be the wrong vocabulary here - apologies because I'm sure this is a duplicate question. My question is pretty simple: in a function that expects a list of items, how can I pass a Python list item without getting an error? ``` my_list = ['red', 'blue', 'orange'] function_that_needs_strings('red'...
``` function_that_needs_strings(*my_list) # works! ``` [You can read all about it here.](https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists)
Unpack a list in Python?
3,480,184
80
2010-08-13T19:40:06Z
20,643,158
8
2013-12-17T19:37:36Z
[ "python", "list", "argument-passing" ]
I think 'unpack' might be the wrong vocabulary here - apologies because I'm sure this is a duplicate question. My question is pretty simple: in a function that expects a list of items, how can I pass a Python list item without getting an error? ``` my_list = ['red', 'blue', 'orange'] function_that_needs_strings('red'...
Yes, you can use the `*args` (splat) syntax: ``` function_that_needs_strings(*my_list) ``` where `my_list` can be any iterable; Python will loop over the given object and use each element as a separate argument to the function. See the [call expression documentation](https://docs.python.org/2/reference/expressions.h...
Does Python have something as robust as Ruby's rvm?
3,480,233
19
2010-08-13T19:49:51Z
10,107,239
7
2012-04-11T13:47:05Z
[ "python", "virtualenv", "pip", "virtualenvwrapper" ]
This is not a duplicate of [this question](http://stackoverflow.com/questions/2812471/). I am already aware of [virtualenv](http://pypi.python.org/pypi/virtualenv) and [virtualenvwrapper](http://www.doughellmann.com/projects/virtualenvwrapper/) and [pip](http://pypi.python.org/pypi/pip) but they don't quite seem to ha...
I believe [pythonbrew](https://github.com/yyuu/pyenv) is what you're looking for. **Edit**: [pyenv](https://github.com/yyuu/pyenv) looks like the preferred solution since 2013.
Union-within-structure syntax in ctypes
3,480,240
7
2010-08-13T19:50:41Z
3,480,860
7
2010-08-13T21:42:44Z
[ "python", "ctypes" ]
Quick question about ctypes syntax, as documentation for Unions isn't clear for a beginner like me. Say I want to implement an INPUT structure (see [here](http://msdn.microsoft.com/en-us/library/ms646270%28v=VS.85%29.aspx)): ``` typedef struct tagINPUT { DWORD type; union { MOUSEINPUT mi; KEYBDINPUT ...
Your Structure syntax isn't valid: ``` AttributeError: '_fields_' must be a sequence of pairs ``` I believe you want to use the [anonymous](http://docs.python.org/library/ctypes.html#ctypes.Structure._anonymous_) attribute in your ctypes.Structure. It looks like the ctypes documentation creates a [TYPEDESC](http://ms...
Converting a Python Float to a String without losing precision
3,481,289
20
2010-08-13T23:33:41Z
3,481,575
38
2010-08-14T01:09:12Z
[ "python", "excel", "floating-point", "xlrd" ]
I am maintaining a Python script that uses `xlrd` to retrieve values from Excel spreadsheets, and then do various things with them. Some of the cells in the spreadsheet are high-precision numbers, and they must remain as such. When retrieving the values of one of these cells, `xlrd` gives me a `float` such as 0.3828874...
I'm the author of xlrd. There is so much confusion in other answers and comments to rebut in comments so I'm doing it in an answer. @katriealex: """precision being lost in the guts of xlrd""" --- entirely unfounded and untrue. xlrd reproduces exactly the 64-bit float that's stored in the XLS file. @katriealex: """It ...
Python ctypes not loading dynamic library on Mac OS X
3,481,508
6
2010-08-14T00:40:11Z
3,481,544
10
2010-08-14T00:55:43Z
[ "python", "linux", "osx", "ctypes", "dynamic-linking" ]
I have a C++ library `repeater.so` that I can load from Python in Linux the following way: ``` import numpy as np repeater = np.ctypeslib.load_library('librepeater.so', '.') ``` However, when I compile the same library on Mac OS X (Snow Leopard, 32 bit) and get `repeater.dylib`, an...
It's not just a question of what architectures are available in the dylib; it's also a matter of which architecture the Python interpreter is running in. If you are using the Apple-supplied Python 2.6.1 in OS X 10.6, by default it runs in 64-bit mode if possible. Since you say your library was compiled as 32-bit, you'l...
Why is this variable being changed?
3,481,863
2
2010-08-14T03:13:09Z
3,481,873
7
2010-08-14T03:16:52Z
[ "python", "equality", "while-loop" ]
``` tokens_raw = {"foo": "bar"} tokens_raw_old = { } while not tokens_raw == tokens_raw_old: tokens_raw_old = tokens_raw # while loop that modifies tokens_raw goes here; # tokens_raw_old is never referenced print tokens_raw_old == tokens_raw ``` This outputs True after the first time for some reason. `...
`tokens_raw_old = tokens_raw` means: make a new reference called `token_raw_old` to the **same** object to which name `tokens_raw` refers at this time. It's the **same** object, **not** a copy of the object! So, changes to this one and only object made through one of the references obviously also affect the very same o...
How to update the image of a Tkinter Label widget?
3,482,081
17
2010-08-14T04:59:32Z
3,482,156
20
2010-08-14T05:28:58Z
[ "python", "python-2.7", "tkinter", "python-imaging-library" ]
I would like to be able to swap out an image on a Tkinter label, but I'm not sure how to do it, except for replacing the widget itself. Currently, I can display and image like so: ``` import Tkinter as tk import ImageTk root = tk.Tk() img = ImageTk.PhotoImage(Image.open(path)) panel = tk.Label(root, image = img) pan...
The method `label.configure` does work in `panel.configure(image=img)`. What I forgot to do was include the `panel.image=img`, to prevent garbage collection from deleting the image. The following is the new version: ``` import Tkinter as tk import ImageTk root = tk.Tk() img = ImageTk.PhotoImage(Image.open(path)) ...
How can I make a simple counter with Jinja2 templates?
3,482,297
10
2010-08-14T06:30:25Z
3,486,511
13
2010-08-15T06:59:12Z
[ "python", "templates", "jinja2" ]
I have two for loops, both alike in dignity. I'd like to have a counter incremented during each inner iteration. For example, consider this template: ``` from jinja2 import Template print Template(""" {% set count = 0 -%} {% for i in 'a', 'b', 'c' -%} {% for j in 'x', 'y', 'z' -%} i={{i}}, j={{j}}, count={{cou...
With variable inner group sizes, this will work: ``` from jinja2 import Template items = [ ['foo', 'bar'], ['bax', 'quux', 'ketchup', 'mustard'], ['bacon', 'eggs'], ] print Template(""" {% set counter = 0 -%} {% for group in items -%} {% for item in group -%} item={{ item }}, count={{ counter +...
Autocompletion in dynamic language IDEs, specifically Python in PyDev
3,482,622
4
2010-08-14T08:38:15Z
3,482,716
8
2010-08-14T09:15:17Z
[ "python", "ide", "autocomplete", "duck-typing", "built-in" ]
I'm new to Python, with a background in statically typed languages including lots and lots of Java. I decided on PyDev in eclipse as an IDE after checking features/popularity etc. I was stunned that auto-complete doesn't seem to work properly for builtins. For example if I try automcomplete on datafile after: datafi...
In my opinion, the Python shell is a much better place to explore new modules than relying on an IDE. Don't forget, in Python you can do anything in the shell that you can do in a program, because there's no separate compilation step. And in the shell, you can use `dir(x)` to find all the properties and methods of x, w...
Invoke and control GDB from Python
3,482,869
17
2010-08-14T10:15:45Z
3,492,512
13
2010-08-16T11:01:56Z
[ "python", "gdb" ]
I am running a Python GUI application. I want to invoke and control GDB from it, like load an executable file, set breakpoints etc. I see that GDB has a command line interface which can be used by sending strings to the GDB process, but I want to do it the Python way. Is there a `gdb.py`? I see that "archer" branch has...
Yes, you can control GDB from Python. The Python documentation is at <http://sourceware.org/gdb/current/onlinedocs/gdb/Python.html#Python>. If you want an example of some scripting, take a look at <http://tromey.com/blog/?p=548>
Django query select distinct by field pairs
3,483,307
8
2010-08-14T12:38:42Z
3,483,995
10
2010-08-14T15:31:17Z
[ "python", "django", "django-queryset" ]
I have the field 'submission' which has a user and a problem. How can I get an SQL search result which will give a list of only one result per user-problem pair? Models are like this: ``` class Problem(models.Model): title = models.CharField('Title', max_length = 100) question = models.TextField('Question') ...
Try this: ``` distinct_users_problems = Submission.objects.all().values("user", "problem").distinct() ``` It will give you a list of dicts like this one: ``` [{'problem': 1, 'user': 1}, {'problem': 2, 'user': 1}, {'problem': 3, 'user': 1}] ``` containing all the distinct pairs. It actually results in your usual SE...
Use cases for the 'setdefault' dict method
3,483,520
114
2010-08-14T13:32:58Z
3,483,652
114
2010-08-14T14:05:51Z
[ "python", "dictionary", "setdefault" ]
The addition of `collections.defaultdict` in Python 2.5 greatly reduced the need for `dict`'s `setdefault` method. This question is for our collective education: 1. What is `setdefault` still useful for, today in Python 2.6/2.7? 2. What popular use cases of `setdefault` were superseded with `collections.defaultdict`?
You could say `defaultdict` is useful for settings defaults *before filling the dict* and `setdefault` is useful for setting defaults *while or after filling the dict*. Probably the most common use case: Grouping items (in unsorted data, else use `itertools.groupby`) ``` # really verbose new = {} for (key, value) in ...
Use cases for the 'setdefault' dict method
3,483,520
114
2010-08-14T13:32:58Z
3,483,890
20
2010-08-14T15:01:17Z
[ "python", "dictionary", "setdefault" ]
The addition of `collections.defaultdict` in Python 2.5 greatly reduced the need for `dict`'s `setdefault` method. This question is for our collective education: 1. What is `setdefault` still useful for, today in Python 2.6/2.7? 2. What popular use cases of `setdefault` were superseded with `collections.defaultdict`?
I commonly use `setdefault` for keyword argument dicts, such as in this function: ``` def notify(self, level, *pargs, **kwargs): kwargs.setdefault("persist", level >= DANGER) self.__defcon.set(level, **kwargs) try: kwargs.setdefault("name", self.client.player_entity().name) except pytibia.Playe...
Use cases for the 'setdefault' dict method
3,483,520
114
2010-08-14T13:32:58Z
6,173,641
10
2011-05-30T07:54:57Z
[ "python", "dictionary", "setdefault" ]
The addition of `collections.defaultdict` in Python 2.5 greatly reduced the need for `dict`'s `setdefault` method. This question is for our collective education: 1. What is `setdefault` still useful for, today in Python 2.6/2.7? 2. What popular use cases of `setdefault` were superseded with `collections.defaultdict`?
`defaultdict` is great when the default value is static, like a new list, but not so much if it's dynamic. For example, I need a dictionary to map strings to unique ints. `defaultdict(int)` will always use 0 for the default value. Likewise, `defaultdict(intGen())` always produces 1. Instead, I used a regular dict: `...
When to inline definitions of metaclass in Python?
3,483,718
14
2010-08-14T14:21:35Z
3,483,860
18
2010-08-14T14:52:12Z
[ "python", "metaclass" ]
Today I have come across a surprising definition of a metaclass in Python [here](http://effbot.org/zone/metaclass-plugins.htm), with the metaclass definition effectively inlined. The relevant part is ``` class Plugin(object): class __metaclass__(type): def __init__(cls, name, bases, dict): type...
Like every other form of nested class definition, a nested metaclass may be more "compact and convenient" (as long as you're OK with not reusing that metaclass except by inheritance) for many kinds of "production use", but can be somewhat inconvenient for debugging and introspection. Basically, instead of giving the m...
Python interactive mode history and arrow keys
3,483,723
15
2010-08-14T14:24:29Z
12,005,666
12
2012-08-17T12:18:23Z
[ "python", "osx" ]
I was wondering if anyone can explain why all of a sudden in Python interactive mode all arrow keys are failing? When I press up button for example to go through command history I get "^[[A". Same with any other arrow keys. I have no idea why this happened and it was working before (on OS X Snow Leopard). Does anyone...
I finally got this working. I just had to install readline with easy\_install and cursors and backspace started magically working. ``` sudo /opt/local/bin/easy_install-2.5 readline ```
Is there a description of how __cmp__ works for dict objects in Python 2?
3,484,293
13
2010-08-14T17:05:53Z
3,484,456
20
2010-08-14T17:49:19Z
[ "python", "python-2.x" ]
I've been trying to make a `dict` subclass inheriting from `UserDict.DictMixin` that supports non-hashable keys. Performance isn't a concern. Unfortunately, Python implements some of the functions in `DictMixin` by trying to create a dict object from the subclass. I can implement these myself, but I am stuck on `__cmp_...
If you are asking how comparing dictionaries works, it is this: To compare dicts A and B, first compare their lengths. If they are unequal, then return cmp(len(A), len(B). Next, find the key adiff in A that is the smallest key for which A[adiff] != B[adiff]. Also find the smallest key bdiff in B for which A[bdiff] != ...
Django admin - process field before database insert / update
3,485,369
3
2010-08-14T22:28:11Z
3,485,940
9
2010-08-15T02:24:35Z
[ "python", "django", "django-admin" ]
I have a django model with a text field. I'm using a rich text editor (nicEdit) on the admin site to allow the client to easily enter markup into the field. I'd like to process the contents of the field and perform a few actions before anything is inserted into the database. For example, I want to strip junk generated...
To manipulate data in your model before saving it, use the save() method like: ``` def save(self): self.NameOfTextField = myCustomCleanFunction(self.NameOfTextField) super(YourModelName, self).save() ``` Nothing will be saved until super(modelname, self).save() is executed. If you want the possibilit...
Tkinter dropdown Menu with keyboard shortcuts?
3,485,397
12
2010-08-14T22:34:54Z
3,485,519
29
2010-08-14T23:20:39Z
[ "python", "keyboard-shortcuts", "tkinter" ]
I would like to have a Dropdown Menu in Tkinter, that includes the shortcut key associated with this command. Is this possible? How would I also add the underline under a certain character, to allow for `Alt-F-S` (File->Save)?
``` import tkinter as tk import sys class App(tk.Tk): def __init__(self): tk.Tk.__init__(self) menubar = tk.Menu(self) fileMenu = tk.Menu(menubar, tearoff=False) menubar.add_cascade(label="File", underline=0, menu=fileMenu) fileMenu.add_command(label="Exit", underline=1, ...
Creating multiple SSH connections at a time using Paramiko
3,485,428
11
2010-08-14T22:43:53Z
3,485,469
21
2010-08-14T23:03:28Z
[ "python", "ssh", "paramiko" ]
The code below runs grep in one machine through SSH and prints the results: ``` import sys, os, string import paramiko cmd = "grep -h 'king' /opt/data/horror_20100810*" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('10.10.3.10', username='xy', password='xy') stdin, ...
You'll need to put the calls into separate threads (or processes, but that would be overkill) which in turn requires the code to be in a function (which is a good idea anyway: don't have substantial code at a module's top level). For example: ``` import sys, os, string, threading import paramiko cmd = "grep -h 'king...
Can I create a "view" on a Python list?
3,485,475
28
2010-08-14T23:05:46Z
3,485,490
24
2010-08-14T23:11:25Z
[ "python", "c", "arrays", "list" ]
I have a large list `l`. I want to create a view from element 4 to 6. I can do it with sequence slice. ``` >>> l=range(10) >>> lv=l[3:6] >>> lv [3, 4, 5] ``` However lv is copy of a slice of l. If I change the underlying list, lv does not reflect the change. ``` >>> l[4] = -1 >>> lv [3, 4, 5] ``` Vice versa I want ...
There is no "list slice" class in the Python standard library (nor is one built-in). So, you do need a class, though it need not be big -- especially if you're content with a "readonly" and "compact" slice. E.g.: ``` import collections class ROListSlice(collections.Sequence): def __init__(self, alist, start, ale...
Can I create a "view" on a Python list?
3,485,475
28
2010-08-14T23:05:46Z
3,485,537
20
2010-08-14T23:25:44Z
[ "python", "c", "arrays", "list" ]
I have a large list `l`. I want to create a view from element 4 to 6. I can do it with sequence slice. ``` >>> l=range(10) >>> lv=l[3:6] >>> lv [3, 4, 5] ``` However lv is copy of a slice of l. If I change the underlying list, lv does not reflect the change. ``` >>> l[4] = -1 >>> lv [3, 4, 5] ``` Vice versa I want ...
Perhaps just use a numpy array: ``` In [19]: import numpy as np In [20]: l=np.arange(10) ``` Basic slicing numpy arrays [returns a view](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#basic-slicing), not a copy: ``` In [21]: lv=l[3:6] In [22]: lv Out[22]: array([3, 4, 5]) ``` Altering `l` affects ...
How to plot data against specific dates on the x-axis using matplotlib
3,486,121
14
2010-08-15T03:48:51Z
3,488,013
27
2010-08-15T15:31:38Z
[ "python", "date", "matplotlib" ]
I have a dataset consisting of date-value pairs. I want to plot them in a bar graph with the specific dates in the x-axis. My problem is that `matplotlib` distributes the `xticks` over the entire date range; and also plots the data using points. The dates are all `datetime` objects. Here's a sample of the dataset: `...
What you're doing is simple enough that it's easiest to just using plot, rather than plot\_date. plot\_date is great for more complex cases, but setting up what you need can be easily accomplished without it. e.g., Based on your example above: ``` import datetime as DT from matplotlib import pyplot as plt from matplo...
How can I install aggdraw after this error?
3,486,187
2
2010-08-15T04:25:34Z
7,973,528
8
2011-11-01T22:08:25Z
[ "python", "graphics", "aggdraw" ]
I am trying to install the aggdraw python library to create high quality graphics but I keep getting this error: ``` agg22/include/agg_array.h: In member function `agg::int8u* ``` What is the workaround for this? How can I install it?
You should follow the instructions in <http://www.pocketuniverse.ca/archive/2008/december/11/pil-and-aggdraw/> to patch AGG rather than just have the compiler allow the 64-bit incompatible code to compile. Here's one way you could do it in the shell: ``` cd /tmp svn co http://svn.effbot.org/public/tags/aggdraw-1.2a3-...
Output first 100 characters in a string
3,486,384
29
2010-08-15T05:54:51Z
3,486,387
58
2010-08-15T05:55:58Z
[ "python" ]
Can seem to find a substring function in python. Say I want to output the first 100 characters in a string, how can I do this? I want to do it safely also, meaing if the string is 50 characters it shouldn't fail.
``` print my_string[0:100] ```
Output first 100 characters in a string
3,486,384
29
2010-08-15T05:54:51Z
3,486,388
16
2010-08-15T05:56:04Z
[ "python" ]
Can seem to find a substring function in python. Say I want to output the first 100 characters in a string, how can I do this? I want to do it safely also, meaing if the string is 50 characters it shouldn't fail.
Easy: ``` print mystring[:100] ```
Output first 100 characters in a string
3,486,384
29
2010-08-15T05:54:51Z
3,486,420
33
2010-08-15T06:09:43Z
[ "python" ]
Can seem to find a substring function in python. Say I want to output the first 100 characters in a string, how can I do this? I want to do it safely also, meaing if the string is 50 characters it shouldn't fail.
From [python tutorial](http://docs.python.org/tutorial/introduction.html): > Degenerate slice indices are handled > gracefully: **an index that is too large > is replaced by the string size**, an > upper bound smaller than the lower > bound returns an empty string. So it is safe to use `x[:100]`.
How can I check a Python unicode string to see that it *actually* is proper Unicode?
3,487,377
5
2010-08-15T12:38:02Z
3,510,831
8
2010-08-18T09:51:07Z
[ "python", "postgresql", "unicode" ]
So I have this page: <http://hub.iis.sinica.edu.tw/cytoHubba/> Apparently it's all kinds of messed up, as it gets decoded properly but when I try to save it in postgres I get: ``` DatabaseError: invalid byte sequence for encoding "UTF8": 0xedbdbf ``` The database clams up after that and refuses to do anything witho...
There is a **bug** in python 2.x that is only fixed python 3.x. In fact, this bug is even in OS X's iconv (but not the glibc one). Here's what's happening: Python 2.x does not recognize UTF8 surrogate pairs [1] as being invalid (which is what your character sequence is) This *should* be all that's needed: ``` foo.d...
Overriding append method after inheriting from a Python List
3,487,434
7
2010-08-15T12:54:38Z
3,487,449
13
2010-08-15T12:59:41Z
[ "python", "list", "inheritance" ]
I want to create a list that can only accept certain types. As such, I'm trying to inherit from a list in Python, and overriding the append() method like so: ``` class TypedList(list): def __init__(self, type): self.type = type def append(item) if not isinstance(item, type): raise ...
I have made some changes to your class. This seems to be working. A couple of suggestions: don't use `type` as a keyword - `type` is a built in function. Python instance variables are accessed using the `self.` prefix. So use `self.<variable name>`. ``` class TypedList(list): def __init__(self, type): sel...
Overriding append method after inheriting from a Python List
3,487,434
7
2010-08-15T12:54:38Z
3,488,283
34
2010-08-15T16:47:07Z
[ "python", "list", "inheritance" ]
I want to create a list that can only accept certain types. As such, I'm trying to inherit from a list in Python, and overriding the append() method like so: ``` class TypedList(list): def __init__(self, type): self.type = type def append(item) if not isinstance(item, type): raise ...
> I want to create a list that can only > accept certain types. As such, I'm > trying to inherit from a list in > Python Not the best approach! Python lists have so many mutating methods that you'd have to be overriding a bunch (and would probably forget some). Rather, **wrap** a list, inherit from `collections.Mutab...
Mongodb - are reliability issues significant still?
3,487,456
12
2010-08-15T13:00:29Z
3,488,790
9
2010-08-15T19:04:26Z
[ "python", "sqlite", "mongodb" ]
I have a couple of sqlite dbs (i'd say about 15GBs), with about 1m rows in total - so not super big. I was looking at mongodb, and it looks pretty easy to work with, especially if I want to try and do some basic natural language processing on the documents which make up the databases. I've never worked with Mongo in t...
Yes, durability is a big problem in mongo. You have to use replication sets in mongodb for durability (you need at least 2 machines), otherwise you can loose upto last 1 minute on a power fail for example. There is no single server durability in mongo, but it'll be developed for 1.7-1.8 as I know. After a crash you hav...
Mongodb - are reliability issues significant still?
3,487,456
12
2010-08-15T13:00:29Z
3,491,117
10
2010-08-16T06:45:33Z
[ "python", "sqlite", "mongodb" ]
I have a couple of sqlite dbs (i'd say about 15GBs), with about 1m rows in total - so not super big. I was looking at mongodb, and it looks pretty easy to work with, especially if I want to try and do some basic natural language processing on the documents which make up the databases. I've never worked with Mongo in t...
As others have said, MongoDB does not have single-server durability right now. Fortunately, it's *dead easy* to set up multi-node replication. You can even set up a second machine in another data center and have data automatically replicated to it live! If a write *must* succeed, you can cause Mongo to not return from...
django Queryset with year(date) = '2010'
3,487,484
13
2010-08-15T13:09:35Z
3,487,495
17
2010-08-15T13:13:37Z
[ "python", "sql", "django", "django-queryset" ]
I'm trying to build this query ``` select * from m_orders where year(order_date) = '2010' ``` the field order\_date is a DateTime field. I just don't want to use raw sql queries here. Is it even possible to use e.g. MySQL functions in django quersets?
You can achieve this without using raw SQL. Use the built in `__` mechanism instead (see the [documentation](http://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters) for more details). Something like this: ``` MyOrder.objects.filter(order_date__year = 2010) ```
Getting Python under control on Mac OS X - setting up environment and libraries
3,487,664
15
2010-08-15T14:02:16Z
3,489,922
14
2010-08-16T00:46:40Z
[ "python", "osx", "development-environment" ]
After starting out with Python on Ubuntu Linux, I've now for a good while been doing most of my sustained work on the Mac, currently Mac OS X 10.6. Unfortunately I've neglected to give proper attention to how Python is installed there and ended up with: * Python 2.6.1 (Mac default version?) in `/usr/bin` (also, 2.5.4,...
`virutalenv` is a great tool and is very useful for managing multiple Python instances on most platforms. On Mac OS X, though, things are more complicated because the use of framework builds makes it common to encounter multiple instances of even the same major version of Python. I suggest you first understand and be c...
Which is generally faster, a yield or an append?
3,487,802
8
2010-08-15T14:34:33Z
3,487,844
9
2010-08-15T14:46:43Z
[ "python", "performance", "return", "generator", "yield" ]
I am currently in a personal learning project where I read in an XML database. I find myself writing functions that gather data and I'm not sure what would be a fast way to return them. Which is generally faster: 1. `yield`s, or 2. several `append()`s within the function then `return` the ensuing `list`? I would be ...
`yield` has the huge advantage of being *lazy* and speed is usually not the *best* reason to use it. But if it works in your context, then there is no reason not to use it: ``` # yield_vs_append.py data = range(1000) def yielding(): def yielder(): for d in data: yield d return list(yielder...
Can I get Python debugger pdb to output with Color?
3,488,076
8
2010-08-15T15:48:57Z
3,488,155
14
2010-08-15T16:08:59Z
[ "python", "debugging", "terminal", "pdb" ]
I'm using PDB a lot and it seems it would be even better if I could add systax highlighting in color. Ideally, I'd like to have to the path to the code a lighter color. The line of actual code would be syntax highlighted. I'm using OS X and the Terminal app. Python 2.7
`pdb` doesn't support colorization. However, it's not that hard to get it, even if you're a command-line addict (as I am;-) -- you don't have to switch to GUIs/IDEs just to get colorization while debugging Python. In particular, command-line tools usually work *much* better when you're accessing a remote machine via SS...
What tricks do you use to avoid being tripped up by python whitespace syntax?
3,488,231
4
2010-08-15T16:33:25Z
3,488,298
8
2010-08-15T16:50:24Z
[ "python", "syntax" ]
I'm an experienced programmer, but still a little green at python. I just got caught by an error in indentation, which cost me a significant amount of debugging time. I was wondering what experienced python programmers do to avoid creating such problems in the first place. Here's the code (Part of a much larger progra...
Put all the class attributes (e.g. `value`) up at the top, right under the `class Wizvar` declaration (below the doc string, but above all method definitions). If you always place class attributes in the same place, you may not run into this particular error as often. Notice that if you follow the above convention and...
Why is there no explicit emptyness check (for example `is Empty`) in Python
3,488,470
21
2010-08-15T17:37:54Z
3,488,502
21
2010-08-15T17:45:32Z
[ "python" ]
[The Zen of Python](https://www.python.org/dev/peps/pep-0020/ "PEP 20 -- The Zen of Python") says "Explicit is better than implicit". Yet the "pythonic" way to check for emptiness is using implicit booleaness: ``` if not some_sequence: some_sequence.fill_sequence() ``` This will be true if `some_sequence` is an e...
Polymorphism in `if foo:` and `if not foo:` isn't a violation of "implicit vs explicit": it *explicitly* delegates to the object being checked the task of knowing whether it's true or false. What that means (and how best to check it) obviously does and must depend on the object's type, so the style guide mandates the d...
Why is there no explicit emptyness check (for example `is Empty`) in Python
3,488,470
21
2010-08-15T17:37:54Z
14,284,398
13
2013-01-11T18:26:42Z
[ "python" ]
[The Zen of Python](https://www.python.org/dev/peps/pep-0020/ "PEP 20 -- The Zen of Python") says "Explicit is better than implicit". Yet the "pythonic" way to check for emptiness is using implicit booleaness: ``` if not some_sequence: some_sequence.fill_sequence() ``` This will be true if `some_sequence` is an e...
The reason why there is no `is Empty` is astoundingly simple once you understand what the `is` operator does. From the [python manual](http://docs.python.org/2/reference/expressions.html#is): > The operators `is` and `is not` test for object identity: `x is y` is true > if and only if `x` and `y` are the same object....
Bandwidth throttling in Python
3,488,616
9
2010-08-15T18:16:08Z
3,488,635
7
2010-08-15T18:19:20Z
[ "python", "networking", "network-programming" ]
What libraries out there let you control the download speed of network requests (http in particular). I don't see anything built-in in urllib2 (nor in (Py)Qt which I intend on using). Can Twisted control bandwidth? If not, how can I control the read buffer size of urllib2 or Twisted? `sleep`ing to suspend network oper...
Of course twisted can. You want [`twisted.protocols.policies.ThrottlingFactory`](http://twistedmatrix.com/documents/10.1.0/api/twisted.protocols.policies.ThrottlingFactory.html). Just wrap your existing factory in it before you pass it to whatever wants a factory.
Bandwidth throttling in Python
3,488,616
9
2010-08-15T18:16:08Z
3,488,770
7
2010-08-15T18:56:50Z
[ "python", "networking", "network-programming" ]
What libraries out there let you control the download speed of network requests (http in particular). I don't see anything built-in in urllib2 (nor in (Py)Qt which I intend on using). Can Twisted control bandwidth? If not, how can I control the read buffer size of urllib2 or Twisted? `sleep`ing to suspend network oper...
urllib2 doesn't offer a way to do this, so you'd have to extend some of the classes it uses and implement rate limiting yourself. You might want to look at [this question](http://stackoverflow.com/questions/94997/how-do-you-rate-limit-an-io-operation). If you decide to write a limiter, read up on the [token bucket](htt...
How to rewrite output in terminal
3,488,704
18
2010-08-15T18:36:18Z
3,488,743
20
2010-08-15T18:49:13Z
[ "python", "linux", "terminal" ]
I have a Python script and I want to make it display a increasing number from 0 to 100% in the terminal. I know how to print the numbers on the terminal but how can I "rewrite" them so 0 turns into 1, 1 into 2, and so on until 100?
Printing a carriage return (`\r`) without a newline resets the cursor to the beginning of the line, making the next print overwriting what's already printed: ``` import time import sys for i in range(100): print i, sys.stdout.flush() time.sleep(1) print "\r", ``` This doesn't clear the line, so if you...
SimpleJSON and NumPy array
3,488,934
32
2010-08-15T19:42:51Z
3,488,999
25
2010-08-15T20:00:28Z
[ "python", "json", "numpy", "simplejson" ]
What is the most efficient way of serializing a numpy array using simplejson?
I'd use `simplejson.dumps(somearray.tolist())` as the most *convenient* approach (if I was still using `simplejson` at all, which implies being stuck with Python 2.5 or earlier; 2.6 and later have a standard library module `json` which works the same way, so of course I'd use that if the Python release in use supported...
SimpleJSON and NumPy array
3,488,934
32
2010-08-15T19:42:51Z
3,489,070
10
2010-08-15T20:22:30Z
[ "python", "json", "numpy", "simplejson" ]
What is the most efficient way of serializing a numpy array using simplejson?
This shows how to convert from a 1D NumPy array to JSON and back to an array: ``` try: import json except ImportError: import simplejson as json import numpy as np def arr2json(arr): return json.dumps(arr.tolist()) def json2arr(astr,dtype): return np.fromiter(json.loads(astr),dtype) arr=np.arange(10)...
SimpleJSON and NumPy array
3,488,934
32
2010-08-15T19:42:51Z
10,367,428
16
2012-04-28T20:51:58Z
[ "python", "json", "numpy", "simplejson" ]
What is the most efficient way of serializing a numpy array using simplejson?
I found this json subclass code for serializing one-dimensional numpy arrays within a dictionary. I tried it and it works for me. ``` class NumpyAwareJSONEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, numpy.ndarray) and obj.ndim == 1: return obj.tolist() return js...
SimpleJSON and NumPy array
3,488,934
32
2010-08-15T19:42:51Z
24,375,113
60
2014-06-23T21:46:30Z
[ "python", "json", "numpy", "simplejson" ]
What is the most efficient way of serializing a numpy array using simplejson?
In order to keep dtype and dimension try this: ``` import base64 import json import numpy as np class NumpyEncoder(json.JSONEncoder): def default(self, obj): """If input object is an ndarray it will be converted into a dict holding dtype, shape and the data, base64 encoded. """ i...
In Python, when to use a Dictionary, List or Set?
3,489,071
142
2010-08-15T20:22:32Z
3,489,078
77
2010-08-15T20:24:56Z
[ "python", "list", "dictionary", "set" ]
When should I use a dictionary, list or set? Are there scenarios that are more suited for each data type?
* Do you just need an ordered sequence of items? Go for a list. * Do you just need to know whether or not you've already *got* a particular value, but without ordering (and you don't need to store duplicates)? Use a set. * Do you need to associate values with keys, so you can look them up efficiently (by key) later on?...
In Python, when to use a Dictionary, List or Set?
3,489,071
142
2010-08-15T20:22:32Z
3,489,081
11
2010-08-15T20:25:44Z
[ "python", "list", "dictionary", "set" ]
When should I use a dictionary, list or set? Are there scenarios that are more suited for each data type?
When you want an unordered collection of unique elements, use a `set`. (For example, when you want the set of all the words used in a document). When you want to collect an immutable ordered list of elements, use a `tuple`. (For example, when you want a (name, phone\_number) pair that you wish to use as an element in ...
In Python, when to use a Dictionary, List or Set?
3,489,071
142
2010-08-15T20:22:32Z
3,489,082
13
2010-08-15T20:25:49Z
[ "python", "list", "dictionary", "set" ]
When should I use a dictionary, list or set? Are there scenarios that are more suited for each data type?
* Use a dictionary when you have a set of unique keys that map to values. * Use a list if you have an ordered collection of items. * Use a set to store an unordered set of items.
In Python, when to use a Dictionary, List or Set?
3,489,071
142
2010-08-15T20:22:32Z
3,489,100
326
2010-08-15T20:30:13Z
[ "python", "list", "dictionary", "set" ]
When should I use a dictionary, list or set? Are there scenarios that are more suited for each data type?
A `list` keeps order, `dict` and `set` don't: when you care about order, therefore, you must use `list` (if your choice of containers is limited to these three, of course;-). `dict` associates with each key a value, while `list` and `set` just contain values: very different use cases, obviously. `set` requires items ...
How can I get a human-readable timezone name in Python?
3,489,183
5
2010-08-15T20:47:55Z
3,489,217
7
2010-08-15T20:54:26Z
[ "python", "timezone" ]
In a Python project I'm working on, I'd like to be able to get a "human-readable" timezone name of the form **America/New\_York**, corresponding to the system local timezone, to display to the user. Every piece of code I've seen that accesses timezone information only returns either a numeric offset (-0400) or a letter...
<http://pytz.sourceforge.net/> may be of help. If nothing else, you may be able to grab a list of all of the timezones and then iterate through until you find one that matches your offset.
How can I get a human-readable timezone name in Python?
3,489,183
5
2010-08-15T20:47:55Z
3,493,225
8
2010-08-16T12:47:31Z
[ "python", "timezone" ]
In a Python project I'm working on, I'd like to be able to get a "human-readable" timezone name of the form **America/New\_York**, corresponding to the system local timezone, to display to the user. Every piece of code I've seen that accesses timezone information only returns either a numeric offset (-0400) or a letter...
The following generates a defaultdict mapping timezone offsets (e.g. '-0400') and abbreviations (e.g. 'EDT') to common geographic timezone names (e.g. 'America/New\_York'). ``` import os import dateutil.tz as dtz import pytz import datetime as dt import collections result=collections.defaultdict(list) for name in pyt...
How to run an AppleScript from within a Python script?
3,489,297
4
2010-08-15T21:16:27Z
3,489,333
9
2010-08-15T21:24:42Z
[ "python", "osx", "applescript" ]
The questions says it all.. (On a Mac obviously)
[this nice article](http://oreilly.com/pub/a/mac/2007/05/08/using-python-and-applescript-to-get-the-most-out-of-your-mac.html) suggests the simple solution ``` cmd = """osascript -e 'tell app "Finder" to sleep'""" def stupidtrick(): os.system(cmd) ``` though today you'd use the `subprocess` module instead of `os....
Automatically readdress all variables referring to an object
3,489,380
4
2010-08-15T21:37:24Z
3,489,590
7
2010-08-15T22:43:34Z
[ "python" ]
Suppose I have in python this object ``` class Foo: def __init__(self, val): self.val = val ``` and these two variables ``` a=Foo(5) b=a ``` both `b` and `a` refer to the same instance of `Foo()`, so any modification to the attribute `.val` will be seen equally and synchronized as `a.val` and `b.val`....
As Aaron points out, there may be very hacky and fragile solutions but there is likely nothing that would be guaranteed to work across all Python implementations (e.g. CPython, IronPython, Jython, PyPy, etc). But why would one realistically want to do something that is so contrary to the design and idiomatic use of the...
Python GTK+ widget name
3,489,520
10
2010-08-15T22:25:14Z
3,490,245
12
2010-08-16T02:30:29Z
[ "python", "gtk" ]
How do I get a widget's "name"? When I define a GUI using Glade, I can "name" the widgets of the window but how do I recover that property when I have a widget object instance? I've tried `get_property()`, `get_name()` and `$widget.name` to no avail. **Update:** I am using GtkBuilder file format (i.e. XML format). ...
There has been a long standing bug where GTKBuilder sets the widget name to be the builder ID, or (somehow) doesn't set it at all. See [this Ubuntu bug](https://bugs.launchpad.net/ubuntu/+source/pygtk/+bug/507739) and this [GNOME bug](https://bugzilla.gnome.org/show_bug.cgi?id=591085). (I have no idea why the bug says...
How can I speed up fetching pages with urllib2 in python?
3,490,173
19
2010-08-16T02:03:08Z
3,490,368
16
2010-08-16T03:20:01Z
[ "python", "time", "urllib2", "urlopen", "cprofile" ]
I have a script that fetches several web pages and parses the info. (An example can be seen at <http://bluedevilbooks.com/search/?DEPT=MATH&CLASS=103&SEC=01> ) I ran cProfile on it, and as I assumed, urlopen takes up a lot of time. Is there a way to fetch the pages faster? Or a way to fetch several pages at once? I'l...
Use [twisted](http://twistedmatrix.com)! It makes this kind of thing absurdly easy compared to, say, using threads. ``` from twisted.internet import defer, reactor from twisted.web.client import getPage import time def processPage(page, url): # do somewthing here. return url, len(page) def printResults(resul...
How can I speed up fetching pages with urllib2 in python?
3,490,173
19
2010-08-16T02:03:08Z
3,490,944
22
2010-08-16T06:05:20Z
[ "python", "time", "urllib2", "urlopen", "cprofile" ]
I have a script that fetches several web pages and parses the info. (An example can be seen at <http://bluedevilbooks.com/search/?DEPT=MATH&CLASS=103&SEC=01> ) I ran cProfile on it, and as I assumed, urlopen takes up a lot of time. Is there a way to fetch the pages faster? Or a way to fetch several pages at once? I'l...
**EDIT**: I'm expanding the answer to include a more polished example. I have found a lot hostility and misinformation in this post regarding threading v.s. async I/O. Therefore I also adding more argument to refute certain invalid claim. I hope this will help people to choose the right tool for the right job. This is...
What are some methods to analyze image brightness using Python?
3,490,727
13
2010-08-16T05:09:42Z
3,498,247
22
2010-08-16T23:35:26Z
[ "python", "image-processing" ]
I'd like some advice on performing a simple image analysis in python. I need to calculate a value for the "brightness" of an image. I know [PIL](http://www.pythonware.com/products/pil/) is the goto library for doing something like this. There is a built-in histogram function. What I need is a ["perceived brightness"](...
Using the techniques mentioned in question, I came up with a few different versions. Each method returns a value close, but not exactly the same as the others. Also, all methods run about the same speed except for the last one, which is much slower depending on the image size. 1. Covert image to greyscale, return ave...
How to sum dict elements
3,490,738
23
2010-08-16T05:12:13Z
3,490,778
10
2010-08-16T05:23:53Z
[ "python", "dictionary", "sum" ]
In Python, I have list of dicts: ``` dict1 = [{'a':2, 'b':3},{'a':3, 'b':4}] ``` I want one final dict that will contain the sum of all dicts. I.e the result will be: `{'a':5, 'b':7}` N.B: every dict in the list will contain same number of key, value pairs.
A little ugly, but a one-liner: ``` dictf = reduce(lambda x, y: dict((k, v + y[k]) for k, v in x.iteritems()), dict1) ```
How to sum dict elements
3,490,738
23
2010-08-16T05:12:13Z
3,490,999
8
2010-08-16T06:19:45Z
[ "python", "dictionary", "sum" ]
In Python, I have list of dicts: ``` dict1 = [{'a':2, 'b':3},{'a':3, 'b':4}] ``` I want one final dict that will contain the sum of all dicts. I.e the result will be: `{'a':5, 'b':7}` N.B: every dict in the list will contain same number of key, value pairs.
Leveraging `sum()` should get better performance when adding more than a few dicts ``` >>> dict1 = [{'a':2, 'b':3},{'a':3, 'b':4}] >>> from operator import itemgetter >>> {k:sum(map(itemgetter(k), dict1)) for k in dict1[0]} # Python2.7+ {'a': 5, 'b': 7} >>> dict((k,sum(map(itemgetter(k), dict1))) for k in dict1...
How to sum dict elements
3,490,738
23
2010-08-16T05:12:13Z
3,491,086
28
2010-08-16T06:38:19Z
[ "python", "dictionary", "sum" ]
In Python, I have list of dicts: ``` dict1 = [{'a':2, 'b':3},{'a':3, 'b':4}] ``` I want one final dict that will contain the sum of all dicts. I.e the result will be: `{'a':5, 'b':7}` N.B: every dict in the list will contain same number of key, value pairs.
You can use the [collections.Counter](http://docs.python.org/dev/library/collections.html#collections.Counter) ``` counter = collections.Counter() for d in dict1: counter.update(d) ``` Or, if you prefer oneliners: ``` functools.reduce(operator.add, map(collections.Counter, dict1)) ```
Twisted logging
3,491,294
8
2010-08-16T07:24:11Z
5,861,936
11
2011-05-02T20:07:25Z
[ "python", "twisted" ]
I have 3 processes running under my twisted reactor: Orbited, WSGI (running django), and Twisted itself. I am currently using ``` log.startLogging(sys.stdout) ``` When all the log are directed to the same place, there is too much flooding. One line of my log from WSGI is like this: ``` 2010-08-16 02:21:12-0500 [-]...
You can use the `system` keyword argument to `twisted.python.log.msg` to customize the message. Assuming you've got: ``` log.msg("Service ready for eBusiness!", system="enterprise") ``` You'll get logging output like this: ``` 2010-08-16 02:21:12-0500 [enterprise] Service ready for eBusiness! ``` You could then ha...
What is the preferred way to preallocate NumPy arrays?
3,491,802
17
2010-08-16T09:02:48Z
3,492,576
14
2010-08-16T11:10:39Z
[ "python", "numpy" ]
I am new to NumPy/SciPy. From the documentation, it seems more efficient to preallocate a single array rather than call append/insert/concatenate. For example, to add a column of 1's to an array, i think that this: ``` ar0 = np.linspace(10, 20, 16).reshape(4, 4) ar0[:,-1] = np.ones_like(ar0[:,0]) ``` is preferred to...
Preallocation mallocs all the memory you need in one call, while resizing the array (through calls to append,insert,concatenate or resize) may require copying the array to a larger block of memory. So you are correct, preallocation is preferred over (and should be faster than) resizing. There are a number of "preferre...
Why does updating a set in a tuple cause an error?
3,492,216
3
2010-08-16T10:13:37Z
3,492,715
11
2010-08-16T11:37:18Z
[ "python", "tuples" ]
I have just tried the following in Python 2.6: ``` >>> foo = (set(),) >>> foo[0] |= set(range(5)) TypeError: 'tuple' object does not support item assignment >>> foo (set([0, 1, 2, 3, 4]),) >>> foo[0].update(set(range(10))) >>> foo (set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]),) ``` I have several questions here: * Why does `...
``` >>> def f(): ... x = (set(),) ... y = set([0]) ... x[0] |= y ... return ... >>> import dis >>> dis.dis(f) 2 0 LOAD_GLOBAL 0 (set) 3 CALL_FUNCTION 0 6 BUILD_TUPLE 1 9 STORE_FAST 0 (x) 3 12...
Convert image to a matrix in python
3,493,092
14
2010-08-16T12:29:56Z
3,494,982
17
2010-08-16T16:03:47Z
[ "python", "image-processing", "numpy", "python-imaging-library" ]
I want to do some image processing using Python. Is there a simple way to import `.png` image as a matrix of greyscale/RGB values (possibly using PIL)?
`scipy.misc.imread()` will return a Numpy array, which is handy for lots of things.
How can I convert the time in a datetime string from 24:00 to 00:00 in Python?
3,493,924
7
2010-08-16T14:09:19Z
3,493,966
8
2010-08-16T14:14:31Z
[ "python", "datetime" ]
I have a lot of date strings like `Mon, 16 Aug 2010 24:00:00` and some of them are in `00-23` hour format and some of them in `01-24` hour format. I want to get a list of date objects of them, but when I try to transform the example string into a date object, I have to transform it from `Mon, 16 Aug 2010 24:00:00` to `...
``` import email.utils as eutils import time import datetime ntuple=eutils.parsedate('Mon, 16 Aug 2010 24:00:00') print(ntuple) # (2010, 8, 16, 24, 0, 0, 0, 1, -1) timestamp=time.mktime(ntuple) print(timestamp) # 1282017600.0 date=datetime.datetime.fromtimestamp(timestamp) print(date) # 2010-08-17 00:00:00 print(date....
Passing a list of strings to from python/ctypes to C function expecting char **
3,494,598
16
2010-08-16T15:24:07Z
3,494,857
16
2010-08-16T15:50:39Z
[ "python", "c", "ctypes" ]
I have a C function which expects a list \0 terminated strings as input: ``` void external_C( int length , const char ** string_list) { // Inspect the content of string_list - but not modify it. } ``` From python (with ctypes) I would like to call this function based on a list of python strings: ``` def call_c( ...
``` def call_c(L): arr = (ctypes.c_char_p * len(L))() arr[:] = L lib.external_C(len(L), arr) ```
How do I merge a list of dicts into a single dict?
3,494,906
31
2010-08-16T15:55:58Z
3,495,395
53
2010-08-16T16:56:47Z
[ "python" ]
**EDIT** i have: ``` [{'a':1},{'b':2},{'c':1},{'d':2}] ``` the output should be: ``` {'a':1,'b':2,'c':1,'d':2} ```
This works for dictionaries of any length: ``` >>> result = {} >>> for d in L: ... result.update(d) ... >>> result {'a':1,'c':2,'b':1,'d':2} ``` And as generator-oneliner: ``` dict(pair for d in L for pair in d.items()) ``` In Python 2.7 and 3.x this can and should be written as dict comprehension (thanks, @kat...
How to organize GUI Code (for PyQt)?
3,495,703
5
2010-08-16T17:37:50Z
3,495,856
7
2010-08-16T17:56:01Z
[ "python", "pyqt4", "code-organization" ]
i am looking for something similar to <http://stackoverflow.com/questions/836218/organizing-gui-code>, but for Python and PyQt4. Especially, I am looking at tips and examples of how to handle and store the configuration data, general state etc. EDIT: I have found some hints regarding older versions under: <http://www....
Here's an overview of what we did w/some example names and their functions (we have a lot more in the actual app.) ``` ProjectFolder/ - src/ - my_project/ - model/ - preference.py # Interact with config params - api.py # Interact with our REST api - controller/ ...
LDAP connection problem with self-signed cert
3,495,739
6
2010-08-16T17:42:16Z
8,795,694
14
2012-01-09T21:52:16Z
[ "python", "ldap" ]
The code I am using: ``` # Create LDAPObject instance conn = ldap.initialize(url) conn.protocol_version=ldap.VERSION3 conn.simple_bind_s(binddn,bindpw) # This raises: # ldap.SERVER_DOWN: {'info': 'error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed', 'desc': "Can't contact LDAP serv...
I came here looking for a solution to my problem related to this. This Q&A did not solve my exact problem, but others looking for my exact problem's solution will find the following useful: For those using SSL/TLS for basic transport encryption and not identity verification (self-signed certificates), you just turn of...
In django, how do I call the subcommand 'syncdb' from the initialization script?
3,495,964
33
2010-08-16T18:10:53Z
3,496,275
56
2010-08-16T18:51:27Z
[ "python", "django", "in-memory-database", "django-syncdb" ]
I'm new to python and django, and when following the [Django Book](http://www.djangobook.com/en/1.0/chapter05/) I learned about the command 'python manage.py syncdb' which generated database tables for me. In development environment I use sqlite in memory database, so it is automatically erased everytime I restart the ...
All Django management commands [can be accessed programmatically](https://docs.djangoproject.com/en/dev/ref/django-admin/#running-management-commands-from-your-code): ``` from django.core.management import call_command call_command('syncdb', interactive=True) ``` Ideally you'd use a pre-init signal on `runserver` to ...
In django, how do I call the subcommand 'syncdb' from the initialization script?
3,495,964
33
2010-08-16T18:10:53Z
3,496,460
8
2010-08-16T19:13:29Z
[ "python", "django", "in-memory-database", "django-syncdb" ]
I'm new to python and django, and when following the [Django Book](http://www.djangobook.com/en/1.0/chapter05/) I learned about the command 'python manage.py syncdb' which generated database tables for me. In development environment I use sqlite in memory database, so it is automatically erased everytime I restart the ...
As suggested by "[Where to put Django startup code?](http://stackoverflow.com/questions/2781383/where-to-put-django-startup-code)", you can use middleware for your startup code. The Django docs are [here](http://docs.djangoproject.com/en/dev/topics/http/middleware/#marking-middleware-as-unused). For example (untested)...
What is the difference between a parameterized class and a metaclass (code examples in Python please)?
3,496,029
4
2010-08-16T18:18:02Z
3,496,251
13
2010-08-16T18:48:17Z
[ "python", "class", "metaclass", "parameterized" ]
Hello Stack Overflow contributers, I'm a novice programmer learning Python right now, and I came upon [this site](http://www.ipipan.gda.pl/~marek/objects/TOA/oobasics/oobasics.html) which helps explain object-oriented paradigms. I know that metaclasses are classes of classes (like how meta-directories are directories ...
Python doesn't have (or need) "parameterized classes", so it's hard to provide examples of them in Python;-). A metaclass is simply "the class of a class": normally `type` (as long, in Py2, as you remember to make the class new-style by inheriting from `object`, or some other built-in type or other new-style class -- o...
Conditional import of modules in Python
3,496,592
53
2010-08-16T19:28:29Z
3,496,632
23
2010-08-16T19:33:04Z
[ "python" ]
In my program I want to import simplejson or json based on whether the OS the user is on is Windows or Linux. I take the OS name as input from the user. Now, is it correct to do the following? ``` osys = raw_input("Press w for windows,l for linux") if (osys == "w"): import json as simplejson else: import simpl...
Perfectly correct, tons of packages do this. It's probably better to figure out the OS yourself instead of relying on the user; here's pySerial doing it as an example. [**`serial/__init__.py`**](http://svn.code.sf.net/p/pyserial/code/trunk/pyserial/serial/__init__.py) ``` import sys if sys.platform == 'cli': fro...
Conditional import of modules in Python
3,496,592
53
2010-08-16T19:28:29Z
3,496,790
91
2010-08-16T19:51:46Z
[ "python" ]
In my program I want to import simplejson or json based on whether the OS the user is on is Windows or Linux. I take the OS name as input from the user. Now, is it correct to do the following? ``` osys = raw_input("Press w for windows,l for linux") if (osys == "w"): import json as simplejson else: import simpl...
I've seen this idiom used a lot, so you don't even have to do OS sniffing: ``` try: import json except ImportError: import simplejson as json ```
Convert Z-score (Z-value, standard score) to p-value for normal distribution in Python
3,496,656
18
2010-08-16T19:35:15Z
3,496,745
7
2010-08-16T19:46:39Z
[ "python", "statistics", "scipy" ]
How does one convert a [Z-score](http://en.wikipedia.org/wiki/Standard_score) from the [Z-distribution (standard normal distribution, Gaussian distribution)](http://en.wikipedia.org/wiki/Normal_distribution) to a [*p*-value](http://en.wikipedia.org/wiki/P-value)? I have yet to find the magical function in [Scipy's `sta...
Aha! I found it: [`scipy.special.ndtr`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.special.ndtr.html#scipy.special.ndtr)! This also appears to be under `scipy.stats.stats.zprob` as well (which is just a pointer to `ndtr`). Specifically, given a one-dimensional `numpy.array` instance `z_scores`, one can ...
Convert Z-score (Z-value, standard score) to p-value for normal distribution in Python
3,496,656
18
2010-08-16T19:35:15Z
3,508,321
20
2010-08-18T01:30:01Z
[ "python", "statistics", "scipy" ]
How does one convert a [Z-score](http://en.wikipedia.org/wiki/Standard_score) from the [Z-distribution (standard normal distribution, Gaussian distribution)](http://en.wikipedia.org/wiki/Normal_distribution) to a [*p*-value](http://en.wikipedia.org/wiki/P-value)? I have yet to find the magical function in [Scipy's `sta...
I like the survival function (upper tail probability) of the normal distribution a bit better, because the function name is more informative: ``` p_values = scipy.stats.norm.sf(abs(z_scores)) #one-sided p_values = scipy.stats.norm.sf(abs(z_scores))*2 #twosided ``` normal distribution "norm" is one of around 90 distr...
Why doesn't my TimedRotatingFileHandler rotate at midnight?
3,496,727
5
2010-08-16T19:44:29Z
3,497,410
12
2010-08-16T21:13:07Z
[ "python", "logging" ]
This is my config file: ``` [loggers] keys=root [handlers] keys=TimedRotatingFileHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=TimedRotatingFileHandler [handler_TimedRotatingFileHandler] class=handlers.TimedRotatingFileHandler level=DEBUG formatter=simpleFormatter args=('driver.log',...
The answer is that the process must be running all the time for this to work properly. From <http://bytes.com/topic/python/answers/595931-timedrotatingfilehandler-isnt-rotating-midnight>: > Rotating should happen when the > logging process creates the handler > before midnight and makes a logging > call destined for ...
Find what is in a PYC file
3,497,075
3
2010-08-16T20:32:17Z
3,497,108
9
2010-08-16T20:38:09Z
[ "python", "pyc" ]
This may be a noobie questions, but... So I have a pyc file that I need to use, but I don't have any documentation on it. Is there a way to find out what classes and functions are in it and what variables they take? I don't need to code, just how to run it. Thanks
As long as you can import the file, you can inspect it; it doesn't matter whether it comes from a .py or .pyc. ``` >>> import getopt >>> dir(getopt) ['GetoptError', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'do_longs', 'do_shorts', 'error', 'getopt', 'gnu_getopt', 'long_has_args', 'o...
python try/finally for flow control
3,497,371
5
2010-08-16T21:08:18Z
3,497,439
11
2010-08-16T21:16:35Z
[ "python", "try-catch-finally", "flow-control" ]
I'm sure this concept has come up before but I can't find a good, simple answer. Is using try/finally a bad way to handle functions with multiple returns? For example I have ``` try: if x: return update(1) else: return update(2) finally: notifyUpdated() ``` This just seems nicer than stori...
I wouldn't recommend it. First because `notifyUpdated()` will be called even if the code in either branch throws an exception. You would need something like this to really get the intended behavior: ``` try: if x: return update(1) else: return update(2) except: raise else: notifyUpdated...
python try/finally for flow control
3,497,371
5
2010-08-16T21:08:18Z
3,497,477
11
2010-08-16T21:22:00Z
[ "python", "try-catch-finally", "flow-control" ]
I'm sure this concept has come up before but I can't find a good, simple answer. Is using try/finally a bad way to handle functions with multiple returns? For example I have ``` try: if x: return update(1) else: return update(2) finally: notifyUpdated() ``` This just seems nicer than stori...
I would not use try/finally for flow that doesn't involve exceptions. It's too tricky for its own good. This is better: ``` if x: ret = update(1) else: ret = update(2) notifyUpdated() return ret ```
matplotlib plot and imshow
3,497,578
4
2010-08-16T21:36:37Z
3,497,922
9
2010-08-16T22:26:25Z
[ "python", "matplotlib" ]
The behavior of matplotlib's plot and imshow is confusing to me. ``` import matplotlib as mpl import matplotlib.pyplot as plt ``` If I call plt.show() prior to calling plt.imshow(i), then an error results. If I call plt.imshow(i) prior to calling plt.show(), then everything works perfectly. However, if I close the fi...
> If I call plt.show() prior to calling > plt.imshow(i), then an error results. > If I call plt.imshow(i) prior to > calling plt.show(), then everything > works perfectly. `plt.show()` displays the figure (and enters the mainloop of whatever gui backend you're using). You shouldn't call it until you've plotted things ...
In Python is it bad to create an attribute called 'id'?
3,497,883
11
2010-08-16T22:20:21Z
3,497,915
14
2010-08-16T22:25:14Z
[ "python" ]
I know that there's a function called id so I wouldn't create a function or a variable called id, but what about an attribute on an object?
That's ok, and is pretty common. For example, objects mapped to a database record will often have an "id" attribute mapped to the database "id" column value. Attributes are always "namespaced" so you have to refer to them via `self.id` or `obj.id` so there's no conflict with the built-in function.
Using Linux redirect to overwrite file from Python script
3,498,106
2
2010-08-16T23:02:49Z
3,498,127
7
2010-08-16T23:06:19Z
[ "python", "linux", "shell", "redirect" ]
I have a simple python script that just takes in a filename, and spits out a modified version of that file. I would like to redirect stdout (using '>' from the command line) so that I can use my script to overwrite a file with my modifications, e.g. `python myScript.py test.txt > test.txt` When I do this, the resultin...
The reason it works that way is that, before Python even starts, Bash interprets the redirection operator and opens an output stream to write stdout to the file. That operation truncates the file to size 0 - in other words, it clears the contents of the file. So by the time your Python script starts, it sees an empty i...
organising classes and modules in python
3,498,200
11
2010-08-16T23:23:30Z
3,498,303
12
2010-08-16T23:46:42Z
[ "python", "oop", "class", "module" ]
I'm getting a bit of a headache trying to figure out how to organise modules and classes together. Coming from C++, I'm used to classes encapsulating all the data and methods required to process that data. In python there are modules however and from code I have looked at, some people have a lot of *loose* functions st...
It seems like loose functions bother you. This is the python way. It makes sense because a module in python is really just an object on the same footing as any other object. It does have language level support for loading it from a file but other than that, it's just an object. so if I have a module `foo.py`: ``` imp...
How to trigger from Python playing of a WAV or MP3 audio file on a Mac?
3,498,313
4
2010-08-16T23:49:41Z
3,498,622
20
2010-08-17T01:12:55Z
[ "python", "osx", "audio" ]
I'm looking for an elegant way, without a ton of dependencies as in some of the solutions I googled up. Thanks for any ideas.
If you want to do away with external dependencies entirely, and are running OS X 10.5+, you can use the included command-line audio player, [afplay](http://developer.apple.com/mac/library/documentation/Darwin/Reference/ManPages/man1/afplay.1.html), along with the [subprocess](http://docs.python.org/library/subprocess.h...
Django Boto S3 Access
3,498,464
7
2010-08-17T00:29:32Z
3,498,831
7
2010-08-17T02:08:03Z
[ "python", "django", "amazon-s3", "boto" ]
I can't figure this out. Here's what I want to happen ... I have an applications that users upload files to S3 using boto and django. I want those files to be private and only accessible through my app using my api credentials. So if a user uploads a photo via my app, the only way he or anyone else can download it i...
The docs for boto's ACLs are [here](http://boto.readthedocs.org/en/latest/s3_tut.html#setting-getting-the-access-control-list-for-buckets-and-keys). I suggest just using the `private` "canned policy" -- since your users don't have S3 accounts anyway, it's by far the simplest idea. Your app will of course have to keep t...
How to configure Eclipse for PyDev? Python doesn't appear in Preferences window
3,498,655
7
2010-08-17T01:25:31Z
3,499,286
9
2010-08-17T04:14:00Z
[ "python", "eclipse", "plugins", "configuration", "pydev" ]
I'm trying to install PyDev in Eclipse 3.6 on Windows 7. I have Python 2.7 successfully installed. I installed PyDev through Eclipse, and restarted. When attempting to configure Eclipse to find my installed Python, (`Window -> Preferences`) the list that appears does not contain Python. (See image below.) If I go ba...
There's an issue when installing plugins under Windows 7 with UAC (User Access Control) active. You need to run as administrator. Read [my blog post](http://blog.zvikico.com/2010/08/eclipse-plugin-installation-and-windows-user-access-control.html) for more details.
find a minimum value in an array of floats
3,499,026
9
2010-08-17T03:02:08Z
3,499,027
24
2010-08-17T03:03:48Z
[ "python", "arrays", "numpy", "minimum" ]
how would one go about finding the minimum value in an array of 100 floats in python? I have tried `minindex=darr.argmin()` and `print darr[minindex]` with `import numpy` (darr is the name of the array) but i get: `minindex=darr.argmin()` `AttributeError: 'list' object has no attribute 'argmin'` what might be the pr...
Python has a [`min()` built-in function](http://docs.python.org/library/functions.html#min): ``` >>> darr = [1, 3.14159, 1e100, -2.71828] >>> min(darr) -2.71828 ```
find a minimum value in an array of floats
3,499,026
9
2010-08-17T03:02:08Z
3,499,042
17
2010-08-17T03:08:29Z
[ "python", "arrays", "numpy", "minimum" ]
how would one go about finding the minimum value in an array of 100 floats in python? I have tried `minindex=darr.argmin()` and `print darr[minindex]` with `import numpy` (darr is the name of the array) but i get: `minindex=darr.argmin()` `AttributeError: 'list' object has no attribute 'argmin'` what might be the pr...
If you want to use numpy, you must define `darr` to be a numpy array, not a `list`: ``` import numpy as np darr = np.array([1, 3.14159, 1e100, -2.71828]) print(darr.min()) ``` `darr.argmin()` will give you the index corresponding to the minimum. The reason you were getting an error is because `argmin` is a method un...
How should I structure a video streaming web app?
3,499,227
5
2010-08-17T04:00:20Z
3,499,379
13
2010-08-17T04:43:47Z
[ "python", "web-applications", "video", "video-streaming" ]
I want a user to be able to create an account and upload a video to the site. How should I structure this web app, how should I start thinking about the project, how should I store the videos, and what stack would you recommend for this project? How should I think about the front-end, the server, and the database? Th...
I'd start by breaking it down into more manageable chunks. * A python web framework to work in: + [Django](http://www.djangoproject.com/) + [Pylons](http://pylonshq.com/) + [Google App Engine](http://code.google.com/appengine/) ([webapp](http://code.google.com/appengine/docs/python/tools/webapp/)) * Video storag...
Erase whole array Python
3,499,233
19
2010-08-17T04:01:30Z
3,499,238
12
2010-08-17T04:02:28Z
[ "python", "arrays", "erase" ]
How do I erase a whole array, leaving it with no items? I want to do this so I can store new values in it (a new set of 100 floats) and find the minimum. Right now my program is reading the minimum from sets before I think because it is appending itself with the previous set still in there. I use .append by the way.
It's simple: ``` array = [] ``` will set `array` to be an empty list. (They're called lists in Python, by the way, not arrays) If that doesn't work for you, edit your question to include a code sample that demonstrates your problem.