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 |
|---|---|---|---|---|---|---|---|---|---|
Find object by its member inside a List in python | 10,858,575 | 11 | 2012-06-01T23:36:09Z | 10,858,616 | 19 | 2012-06-01T23:44:32Z | [
"python",
"list",
"search",
"find"
] | lets assume the following simple Object:
```
class Mock:
def __init__(self, name, age):
self.name = name
self.age = age
```
then I have a list with some Objects like this:
```
myList = [Mock("Dan", 34), Mock("Jack", 30), Mock("Oli", 23)...]
```
Is there some built-in feature where I can get all ... | You might want to pre-index them -
```
from collections import defaultdict
class Mock(object):
age_index = defaultdict(list)
def __init__(self, name, age):
self.name = name
self.age = age
Mock.age_index[age].append(self)
@classmethod
def find_by_age(cls, age):
return ... |
Python deep reverse in a list | 10,859,135 | 2 | 2012-06-02T01:30:11Z | 10,859,154 | 7 | 2012-06-02T01:34:46Z | [
"python",
"list",
"reverse"
] | I have a nested list, and I need to reverse every element in the list. But I dont know whether the list is a list of list of list or not.
So example is:
```
p = [1, [2, 3, [4, [5, 6]]]]
print deep_reverse(p)
#>>> [[[[6, 5], 4], 3, 2], 1]
q = [1, [2,3], 4, [5,6]]
print deep_reverse(q)
#>>> [ [6,5], 4, [3, 2], 1]
```
... | Hmmm... If only there were a way to deeply reverse all of the sublists as well....
\*\*wink\*\* |
python proxy list check | 10,860,983 | 4 | 2012-06-02T08:45:54Z | 10,862,054 | 10 | 2012-06-02T11:46:43Z | [
"python"
] | i have some text file which contain proxy ip .
which look like following
```
130.14.29.111:80
130.14.29.120:80
130.159.235.31:80
14.198.198.220:8909
141.105.26.183:8000
16... | Is this what you want?
```
#!/usr/bin/env python
import Queue
import threading
import urllib2
import time
input_file = 'proxylist.txt'
threads = 10
queue = Queue.Queue()
output = []
class ThreadUrl(threading.Thread):
"""Threaded Url Grab"""
def __init__(self, queue):
threading.Thread.__init__(self)
... |
Intersection of variable number of lists | 10,861,236 | 3 | 2012-06-02T09:34:39Z | 10,861,261 | 13 | 2012-06-02T09:37:55Z | [
"python",
"list",
"function",
"set",
"intersection"
] | I define intersection of two lists as follows:
```
def intersect(a, b):
return list(set(a) & set(b))
```
For three arguments it would look like:
```
def intersect(a, b, c):
return (list(set(a) & set(b) & set(c))
```
Can I generalize this function for variable number of lists?
The call would look for example li... | Use the [`*`-list-to-argument operator](http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists) and instead of your custom function use `set.intersection`:
```
>>> lists = [[1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2]]
>>> list(set.intersection(*map(set, lists)))
[2]
```
If you want the list-to-set-t... |
Python get number from group of numbers | 10,862,776 | 3 | 2012-06-02T13:46:56Z | 10,862,820 | 11 | 2012-06-02T13:52:08Z | [
"python",
"numbers"
] | I want to find out with how many times I can build a number from a group of numbers:
```
possible_numbers = 1, 2, 4, 8, 16
```
If I want number 23 I need
```
1x 16
0x 8
1x 4
1x 2
1x 1
```
Is there any built in function in Python to do this?
Edit: The numbers are fixed to 1,2,4,8,16,32,64,128. Multiple selections a... | Assuming that the possible numbers are always powers of two, you basically want to convert the number to binary format. This is easy with the built-in [bin function](http://docs.python.org/release/3.1.5/library/functions.html#bin):
```
>>> mylist = [int(x) for x in bin(23)[2:]]
>>> print mylist
[1, 0, 1, 1, 1]
```
To... |
Metro-like full-screen browser using PyQT/PySide | 10,863,131 | 3 | 2012-06-02T14:31:42Z | 10,863,272 | 8 | 2012-06-02T14:50:56Z | [
"python",
"pyqt",
"pyside"
] | I've seen sample code that allows one to use PyQT or PySide with QtWebKit to launch a fullscreen browser. I am not familiar with how Qt works. Is it possible to create a web-browser that emulates a Windows 8 Metro-like UI?
I am looking at the following features:
* right clicking anywhere brings up a sliding panel
* h... | Yes that seems possible.
To get your application to show fullscreen:
```
mainwindow.setWindowFlags(QtCore.Qt.FramelessWindowHint)
mainwindow.showFullScreen()
```
Setting up hotkeys and mouse event handling is definitely possible, there are plenty of tutorials online ([mouse event handling example](http://www.rkblog.... |
How is an empty __init__.py file correct? | 10,863,268 | 18 | 2012-06-02T14:50:03Z | 10,863,282 | 21 | 2012-06-02T14:51:42Z | [
"python"
] | I have several, empty, `__init__.py` files in my packages. Is it correct if I keep them empty or do I have to place a `pass` inside them?
Are there any PEP, or other, guidelines about the subject? | Empty files are [perfectly fine](http://docs.python.org/tutorial/modules.html#packages):
> The `__init__.py` files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later... |
why DuplicateKeyError: E11000 duplicate key error index: test.test.$notification_1 dup key: { : null } | 10,863,561 | 3 | 2012-06-02T15:27:23Z | 10,864,061 | 16 | 2012-06-02T16:30:57Z | [
"python",
"mongodb",
"pymongo"
] | i create unique index like this:
```
self.db_database[co_name].ensure_index([('src_md5',-1),('src_time',-1),('src_size',-1)],unique=True)
self.db_database[co_name].ensure_index(('notification'),unique=True)
self.db_database[co_name].ensure_index(('version'),unique=True)`
```
before insert i creat a record as follows:... | You probably already have a document in your collection which either has `notification: NULL` or a document that doesn't have the notification field set. If a field is not set, then it's regarded as null. Because a unique index only allows one value per field, you can not have two documents that don't have a field set.... |
How to convert gettext .mo file into .po file | 10,863,840 | 21 | 2012-06-02T16:02:20Z | 12,354,354 | 27 | 2012-09-10T14:59:39Z | [
"python",
"translation",
"gettext"
] | Is there any way to convert a .mo file into a .po file source, when the .po file is no longer available? I need to edit the content of a .mo file but I don't have the .po file. Is it possible? | ```
msgunfmt [path_to_file.mo] > [path_to_file.po]
``` |
How to convert gettext .mo file into .po file | 10,863,840 | 21 | 2012-06-02T16:02:20Z | 20,584,335 | 7 | 2013-12-14T14:13:42Z | [
"python",
"translation",
"gettext"
] | Is there any way to convert a .mo file into a .po file source, when the .po file is no longer available? I need to edit the content of a .mo file but I don't have the .po file. Is it possible? | You can use [Online Tools for WordPress Developers](http://tools.konstruktors.com/)
Convert .mo to/from .po translation files |
How to check python version that vim was compiled with? | 10,864,042 | 21 | 2012-06-02T16:28:21Z | 10,864,128 | 8 | 2012-06-02T16:39:35Z | [
"python",
"vim"
] | In the terminal, it works to do
```
python -c "import sys; print(sys.version)"
```
but doing
```
:python -c "import sys; print(sys.version)"
```
in vim throws a SyntaxError. | I think you want this:
Type:
```
:python << EOF
import sys;
print(sys.version);
EOF
```
If vim was compiled with python, when you type `:python << EOF` in the command line, the command line will expand with newlines and wait for the EOF. Before the EOF, type your python code, and terminate with an EOF.
**Edit:** as... |
How to check python version that vim was compiled with? | 10,864,042 | 21 | 2012-06-02T16:28:21Z | 10,864,154 | 38 | 2012-06-02T16:44:18Z | [
"python",
"vim"
] | In the terminal, it works to do
```
python -c "import sys; print(sys.version)"
```
but doing
```
:python -c "import sys; print(sys.version)"
```
in vim throws a SyntaxError. | I just discovered [here](http://stackoverflow.com/questions/5872079/compiling-vim-with-specific-version-of-python) that you can also do it with
```
:python import sys; print(sys.version)
``` |
Python tkinter creating buttons in for loop passing command arguments | 10,865,116 | 11 | 2012-06-02T19:07:13Z | 10,865,170 | 19 | 2012-06-02T19:15:21Z | [
"python",
"button",
"tkinter"
] | I am trying to create buttons in tkinter within a for loop. And with each loop pass the i count value out as an argument in the command value. So when the function is called from the command value I can tell which button was pressed and act accordingly. The problem is, lets say len is 3, it will create 3 buttons with t... | Change your lambda to `lambda i=i: self.open_this(i)`.
This may look magical, but here's what's happening. When you use that lambda to define your function, the open\_this call doesn't get the value of the variable i at the time you define the function. Instead, it makes a closure, which is sort of like a note to itse... |
Descriptor 'date' requires a 'datetime.datetime' object but received a 'unicode' | 10,865,143 | 2 | 2012-06-02T19:12:10Z | 10,865,199 | 7 | 2012-06-02T19:19:04Z | [
"python",
"django",
"django-piston"
] | I am using piston to write a JSON api for an application I am writing which handles recurring calendar events.
My API was working for regular events, when I attempted to add logic to handle the recurrence, I started getting the following error:
> descriptor 'date' requires a 'datetime.datetime' object but received a ... | By using `from datetime import datetime, timedelta` you have imported the datetime type from the datetime module. Thus when you call `datetime.date` you are calling a method on the datetime type.
I think what you want is to use the date type from the datetime module:
1. Change your import to `from datetime import dat... |
Unicode values in strings are escaped when dumping to JSON in Python | 10,865,180 | 4 | 2012-06-02T19:16:48Z | 10,865,213 | 8 | 2012-06-02T19:21:12Z | [
"python",
"json",
"unicode"
] | For example:
```
>>> print json.dumps('růže')
"r\u016f\u017ee"
```
(Of course, in the real program it's not just a single string, and it also appears like this in the file, when using `json.dump()`) I'd like it to output simply "růže" as well, how to do that? | Pass the `ensure_ascii=False` argument to json.dumps:
```
>>> print json.dumps('růže', ensure_ascii=False)
"růže"
``` |
Determining the number of parameters in a lambda | 10,865,325 | 33 | 2012-06-02T19:33:53Z | 10,865,349 | 36 | 2012-06-02T19:37:18Z | [
"python",
"lambda"
] | I am wondering if there is a way to determine (given a variable containing a lambda) the number of parameters the lambda it contains. The reason being, I wish to call a function conditionally dependent on the number of parameters.
What I'm looking for
```
def magic_lambda_parameter_counting_function(lambda_function):... | I'm skipping the part about how to count the arguments, because I don't know how you want to consider varargs and keywords. But this should get you started.
```
>>> import inspect
>>> foo = lambda x, y, z: x + y + z
>>> inspect.getargspec(foo)
ArgSpec(args=['x', 'y', 'z'], varargs=None, keywords=None, defaults=None)
`... |
Determining the number of parameters in a lambda | 10,865,325 | 33 | 2012-06-02T19:33:53Z | 10,865,355 | 48 | 2012-06-02T19:37:46Z | [
"python",
"lambda"
] | I am wondering if there is a way to determine (given a variable containing a lambda) the number of parameters the lambda it contains. The reason being, I wish to call a function conditionally dependent on the number of parameters.
What I'm looking for
```
def magic_lambda_parameter_counting_function(lambda_function):... | Lambdas are functions like any other. The argument count is stored in `func.__code__.co_argcount`.
```
>>> foo = lambda x, y=2: x+y
>>> foo.__code__.co_argcount
2
>>> foo = lambda x, y=2, z=3: x+y+z
>>> foo.__code__.co_argcount
3
``` |
Determining the number of parameters in a lambda | 10,865,325 | 33 | 2012-06-02T19:33:53Z | 10,865,410 | 10 | 2012-06-02T19:46:19Z | [
"python",
"lambda"
] | I am wondering if there is a way to determine (given a variable containing a lambda) the number of parameters the lambda it contains. The reason being, I wish to call a function conditionally dependent on the number of parameters.
What I'm looking for
```
def magic_lambda_parameter_counting_function(lambda_function):... | From the documentation on [callable types](http://docs.python.org/reference/datamodel.html#the-standard-type-hierarchy), the `func_code` attribute of functions contains a code object, and from the inspect module documentation on [code objects](http://docs.python.org/library/inspect.html#types-and-members) there is a `c... |
Print results in MySQL format with Python | 10,865,483 | 3 | 2012-06-02T19:57:57Z | 20,383,011 | 8 | 2013-12-04T18:26:08Z | [
"python",
"mysql"
] | What is the easiest way to print the result from MySQL query in the same way MySQL print them in the console using Python? For example I would like to get something like that:
```
+---------------------+-----------+---------+
| font | documents | domains |
+---------------------+-----------+---------+
|... | There is no need for an external library. The prints out the data with the column names. All lines with the 'columns' variable can be eliminated if you do not need the column names.
```
sql = "SELECT * FROM someTable"
cursor.execute(sql)
conn.commit()
results = cursor.fetchall()
widths = []
columns = []
tavnit = '|'
... |
How to make editable install of Python package from vcs into specific directory using pip? | 10,866,199 | 7 | 2012-06-02T21:46:59Z | 11,016,214 | 7 | 2012-06-13T13:45:56Z | [
"python",
"version-control",
"pip"
] | By default pip installs *editable* packages into `src` subdirectory of the directory where Python is installed.
I'd like to install a package from version control to a directory of my choosing using pip's support for checking out a package from source control, for example:
```
pip install -e git+https://github.com/ke... | `pip help install` says:
```
--src=DIR, --source=DIR, --source-dir=DIR, --source-directory=DIR
Check out --editable packages into DIR
```
For example:
```
pip install -e git+https://github.com/kennethreitz/requests.git@355b97165c#egg=requests-org --source-directory=/tmp
```
Will install the re... |
Is it possible to make an iterable from a linked list without writing a generator function? | 10,866,264 | 3 | 2012-06-02T22:01:17Z | 10,866,414 | 7 | 2012-06-02T22:28:07Z | [
"python",
"generator"
] | In a Python program I'm writing, I've built up a linked list using a dictionary which maps each node to its successor (with the last node mapped to None).
(Actually, the dictionary holds what Wikipedia tells me is called a [spaghetti stack](http://en.wikipedia.org/wiki/Spaghetti_stack), which is a tree where each node... | The essential problem you face is that every time another value is taken from your iterable, your iterable has to *remember* that value, so that it knows how to generate the next value. In other words, your iterable needs to maintain its own *state*.
That means that, whether or not there's a good answer to your questi... |
Python - Sort files in directory and use latest file in code | 10,866,928 | 2 | 2012-06-03T00:11:34Z | 10,866,945 | 8 | 2012-06-03T00:13:39Z | [
"python"
] | Long time reader, first time poster. I am very new to python and I will try to ask my question properly.
I have posted a snippet of the .py code I am using below. I am attempting to get the latest modified file in the current directory to be listed and then pass it along later in the code.
This is the error I get in ... | `os.listdir` returns the names of files, not full paths to those files. Generally, when you use `os.listdir(SOME_DIR)`, you then need `os.path.join(SOME_DIR, fname)` to get a path you can use to work with the file.
This might work for you:
```
files = [os.path.join("/", fname) for fname in os.listdir("/")]
latest = m... |
Get pandas.read_csv to read empty values as empty string instead of nan | 10,867,028 | 15 | 2012-06-03T00:38:37Z | 11,005,208 | 15 | 2012-06-12T21:33:20Z | [
"python",
"csv",
"pandas"
] | I'm using the pandas library to read in some CSV data. In my data, certain columns contain strings. The string "nan" is a possible value, as is an empty string. I managed to get pandas to read "nan" as a string, but I can't figure out how to get it not to read an empty value as NaN. Here's sample data and output
```
O... | I added a ticket to add an option of some sort here:
<https://github.com/pydata/pandas/issues/1450>
In the meantime, `result.fillna('')` should do what you want
EDIT: in the development version (to be 0.8.0 final) if you specify an empty list of `na_values`, empty strings will stay empty strings in the result |
Tuple unpacking in for loops | 10,867,882 | 11 | 2012-06-03T04:24:10Z | 10,867,891 | 27 | 2012-06-03T04:27:54Z | [
"python",
"python-3.x"
] | I stumbled across the following code:
```
for i,a in enumerate(attributes):
labels.append(Label(root, text = a, justify = LEFT).grid(sticky = W))
e = Entry(root)
e.grid(column=1, row=i)
entries.append(e)
entries[i].insert(INSERT,"text to insert")
```
I don't understand the 'i,a' bit and searching googl... | You could google on "tuple unpacking". This can be used in various places in Python. The simplest is in assignment
```
>>> x = (1,2)
>>> a, b = x
>>> a
1
>>> b
2
```
In a for loop it works similarly. If each element of the iterable is a tuple, then you can specify two variables and each element in the loop will be un... |
How to test if every element in a numpy array is masked | 10,867,994 | 2 | 2012-06-03T04:52:47Z | 10,868,055 | 9 | 2012-06-03T05:09:41Z | [
"python",
"numpy"
] | How do I test if every element in a numpy array is masked? Here's what I'd like to do:
```
x = #is a maksed numpy array
masked_min = numpy.ma.min(x)
if masked_min IS NOT A MASKED ELEMENT:
#do some stuff only if masked_min is a value
```
In practice I see this:
```
>>> x = numpy.ma.array(numpy.array([1,2,3]),mask=[... | If by "test if an entire array is masked in numpy" you mean whether every element is masked, since the mask itself an array, you could use `.mask.all()`:
```
>>> x = numpy.ma.array(numpy.array([1,2,3]),mask=[True,True,True])
>>> x
masked_array(data = [-- -- --],
mask = [ True True True],
fill_val... |
How to use dj-database-url while connecting with postgresql in heroku using python | 10,868,040 | 3 | 2012-06-03T05:05:19Z | 10,869,728 | 12 | 2012-06-03T10:56:50Z | [
"python",
"postgresql",
"heroku"
] | I'm here because I'm really really new with heroku-python-django-postgresql group. I have googled for a usage for dj-database-url and I don't understand why i have to use it when developing a python application that needs to connect with postgresql. I have added postgresql (dev version) as add-on to my application, but... | dj-database-url is a utility to help you load your database into your dictionary from the DATABASE\_URL environment variable. Heroku uses environment variables for your database and other addons. To begin using your database you'd simply use the below command to setup your DATABASES dictionary:
```
import dj_database_... |
Understanding global variable in Python | 10,868,530 | 6 | 2012-06-03T07:05:37Z | 10,868,550 | 11 | 2012-06-03T07:10:34Z | [
"python",
"global-variables"
] | I came across a strange issue in Python when using global variables.
I have two modules(files):`mod1.py` and `mod2.py`
`mod1` tries to modify the global variable `var` defined in `mod2`. But the `var` in mod2 and `var` in `mod` seems to be two different things. Thus, the result shows that such modification does not w... | When you import `var` into `mod1`:
```
from mod2 import var,fun_of_mod2
```
You are giving it the name `var` *in mod1's namespace.* It is as if you did this:
```
import mod2
var = mod2.var
fun_of_mod2 = mod2.fun_of_mod2
del mod2
```
In other words, there are now two names for the value, `mod1.var` and `mod2.var`. T... |
How to define constant like this in lisp? | 10,870,836 | 2 | 2012-06-03T13:38:12Z | 10,872,861 | 8 | 2012-06-03T18:36:18Z | [
"python",
"common-lisp"
] | In python it's possible to do this
```
EMPTY, PAWN, KNIGHT, BISHOP, ROOK, QUEEN, KING, BPAWN = range(8)
```
How would you do equivalent in lisp? | It would be more idiomatic in Lisp to just use symbols. Typically as self-evaluating keyword symbols:
```
(defparameter *chess-pieces*
'(:EMPTY :PAWN :KNIGHT :BISHOP :ROOK :QUEEN :KING :BPAWN))
```
There are reasons to define numeric values - sometimes. Especially when you need to talk to foreign functions. In Lisp... |
json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object? | 10,872,604 | 18 | 2012-06-03T17:52:15Z | 10,872,643 | 24 | 2012-06-03T17:57:07Z | [
"python",
"json",
"typeerror"
] | **Background**: I am writing a python program which should manage my music files. It crawls directories and puts the files and their meta data (via mutagen), encoded in JSON, in a file as a simple "database". I have the directory searching fine, but when I try and save the database, or encode to JSON, it throws a "Type... | Because it's not actually a dictionary; it's another mapping type that *looks* like a dictionary. Use `type()` to verify. Pass it to `dict()` to get a real dictionary from it. |
Differences between subprocess module, envoy, sarge and pexpect? | 10,872,767 | 5 | 2012-06-03T18:25:22Z | 11,032,170 | 10 | 2012-06-14T11:32:00Z | [
"python"
] | I am thinking about making a program that will need to send input and take output from the various aircrack-ng suite tools. I know of a couple of python modules like subprocess, envoy, sarge and pexpect that would provide the necessary functionality. Can anyone advise on what I should be using or not using, especially ... | As the maintainer of `sarge`, I can tell you that its goals are broadly similar to `envoy` (in terms of ease of use over `subprocess`) and there is (IMO) more functionality in `sarge` with respect to:
* Cross-platform support for bash-like syntax (e.g.use of `&&`, `||`, `&` in command lines)
* Better support for captu... |
Python interactive CLI application? | 10,873,157 | 9 | 2012-06-03T19:14:29Z | 10,873,178 | 11 | 2012-06-03T19:17:07Z | [
"python",
"command-line-interface"
] | I'm not even sure what these would be called? I used to write them in ADA running on VAX-VMS!
I want to make a simple menu-driven application that would let me display menus and use the cursor keys to navigate around them, choose items and navigate around the app. All fully old school text based.
I want to be able to... | Check out the Python HOWTO on [Curses Programming with Python](http://docs.python.org/howto/curses.html) and here is the [library reference](http://docs.python.org/library/curses.html).
[Developing Console Interfaces Using Python and Curses](http://www.dev-explorer.com/articles/python-with-curses) might also be helpfu... |
Python interactive CLI application? | 10,873,157 | 9 | 2012-06-03T19:14:29Z | 15,043,863 | 7 | 2013-02-23T18:13:45Z | [
"python",
"command-line-interface"
] | I'm not even sure what these would be called? I used to write them in ADA running on VAX-VMS!
I want to make a simple menu-driven application that would let me display menus and use the cursor keys to navigate around them, choose items and navigate around the app. All fully old school text based.
I want to be able to... | Another easy to use library is `Urwid` - Console User Interface Library.
<http://excess.org/urwid/>
<http://excess.org/urwid/examples.html> |
Django filter() lookup type documentation | 10,873,249 | 6 | 2012-06-03T19:25:22Z | 10,873,320 | 18 | 2012-06-03T19:35:06Z | [
"python",
"django",
"filter",
"lookup"
] | I looked on Django's documentation and Googled every varation of the phrase but I cannot find any documentation that exactly describes the behaviour of lookuptypes.
```
app.objects.filter(column__lookuptype=criteria)
```
I have found documentation on which lookuptypes I *can* use but not what they do or how to use th... | They are called "field lookups" in Django. Field lookups have pretty comprehensive documentation: <https://docs.djangoproject.com/en/dev/ref/models/querysets/#id4>
These are pretty well documented:
* [`exact`](https://docs.djangoproject.com/en/dev/ref/models/querysets/#exact)
* [`iexact`](https://docs.djangoproject.c... |
shutil.rmtree() clarification | 10,873,364 | 16 | 2012-06-03T19:40:43Z | 10,873,495 | 19 | 2012-06-03T19:58:46Z | [
"python",
"python-2.7",
"shutil"
] | I have read the doc's on this function, however, I dont think i am understanding this properly,and if anyone can tell me what im thinking wrong, or if i am correct, it would be a great help. Here is my understanding:
using the `shutil.rmtree(path)` function, it will delete only the directory specified, not the entire ... | This will definitely only delete the last directory in the specified path.
Just try it out:
```
mkdir -p foo/bar
python
import shutil
shutil.rmtree('foo/bar')
```
...will only remove `'bar'`. |
shutil.rmtree() clarification | 10,873,364 | 16 | 2012-06-03T19:40:43Z | 10,873,516 | 25 | 2012-06-03T20:01:00Z | [
"python",
"python-2.7",
"shutil"
] | I have read the doc's on this function, however, I dont think i am understanding this properly,and if anyone can tell me what im thinking wrong, or if i am correct, it would be a great help. Here is my understanding:
using the `shutil.rmtree(path)` function, it will delete only the directory specified, not the entire ... | If noob is a directory, the `shutil.rmtree()` function will delete `noob` and all files and subdirectories below it. That is, `noob` is the root of the tree to be removed. |
shutil.rmtree() clarification | 10,873,364 | 16 | 2012-06-03T19:40:43Z | 19,902,923 | 9 | 2013-11-11T09:31:25Z | [
"python",
"python-2.7",
"shutil"
] | I have read the doc's on this function, however, I dont think i am understanding this properly,and if anyone can tell me what im thinking wrong, or if i am correct, it would be a great help. Here is my understanding:
using the `shutil.rmtree(path)` function, it will delete only the directory specified, not the entire ... | There is some misunderstanding here.
Imagine a tree like this:
```
- user
- tester
- noob
- developer
- guru
```
If you want to delete `user`, just do `shutil.rmtree('user')`. This will also delete `user/tester` and `user/tester/noob` as they are inside `user`. However, it will also delete `user/dev... |
Is there a python alternative to Ruby's VCR library? | 10,873,368 | 17 | 2012-06-03T19:41:06Z | 10,875,154 | 17 | 2012-06-04T00:39:29Z | [
"python",
"testing",
"integration-testing",
"vcr"
] | I'd like to use the awesome "record/playback" mechanism of [Ruby's VCR library](https://github.com/myronmarston/vcr) or [Betamax for the JVM](http://freeside.co/betamax/). Is there a Python library that works the same way? If not, how do you test your REST client calls without worrying about the test being slow and fla... | The project is pretty new (at this point, it's less than a week old), but there's an in-progress python port of VCR called [VCR.py](https://github.com/kevin1024/vcrpy).
If you already know how to use VCR and are comfortable with it, you might also consider running a local ruby proxy server (using something like rack) ... |
How to convert 2D float numpy array to 2D int numpy array? | 10,873,824 | 120 | 2012-06-03T20:46:28Z | 10,873,843 | 164 | 2012-06-03T20:48:30Z | [
"python",
"numpy"
] | How to convert real numpy array to int numpy array?
Tried using map directly to array but it did not work. | Use the `astype` method.
```
>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. , 2.3],
[ 1.3, 2.9]])
>>> x.astype(int)
array([[1, 2],
[1, 2]])
``` |
How to convert 2D float numpy array to 2D int numpy array? | 10,873,824 | 120 | 2012-06-03T20:46:28Z | 10,873,972 | 39 | 2012-06-03T21:09:39Z | [
"python",
"numpy"
] | How to convert real numpy array to int numpy array?
Tried using map directly to array but it did not work. | Some numpy functions for how to control the rounding: [rint](http://docs.scipy.org/doc/numpy/reference/generated/numpy.rint.html#numpy.rint), [floor](http://docs.scipy.org/doc/numpy/reference/generated/numpy.floor.html#numpy.floor),[trunc](http://docs.scipy.org/doc/numpy/reference/generated/numpy.trunc.html#numpy.trunc... |
Accidently did system-wide install of flask and sqlalchemy | 10,874,113 | 4 | 2012-06-03T21:33:58Z | 10,874,131 | 11 | 2012-06-03T21:38:32Z | [
"python",
"sqlalchemy",
"flask"
] | I accidentally did a system-wide install of flask and sqlalchemy. I "sudo pip install"ed both of them, and now I'm wondering how i can uninstall both of those off my system. I already have virtualenv all set up, so I don't want flask or sqlalchemy attached to my system. I read that having it directly installed can caus... | `sudo pip uninstall flask` should do the trick. And yes, having it installed globally can cause issues if you're working with different versions of other packages. |
Built in way to apply a function to successive members of a list and return a new list | 10,874,495 | 2 | 2012-06-03T22:38:36Z | 10,874,503 | 10 | 2012-06-03T22:40:15Z | [
"python",
"functional-programming",
"python-2.7"
] | I'm looking for a built in function in python that applies a function to each element and the next element within a list (or other iterable), returning the set of results in a new list. I don't know if one is built in or not, but I'm attempting to approach this in a functional way if possible.
Example:
```
l = [1,2,3... | You want [`pairwise()`](http://docs.python.org/library/itertools.html#recipes) and `map()`. |
ImportError: cannot import name normalize | 10,874,945 | 4 | 2012-06-03T23:58:31Z | 10,875,148 | 9 | 2012-06-04T00:38:29Z | [
"python",
"django",
"locale",
"gettext"
] | I tried to use djangos i18n and therefor had to install gettext. Now I'm getting this awkward error any time I try to start my application:
```
Traceback (most recent call last):
File "/var/www/mydjangoproject/manage.py", line 8, in <module>
from django.core.management import execute_from_command_line
File "/u... | I guess you have somewhere inside your project a folder locale with an \_\_init\_\_.py file in it.
Delete this file (you don't need it for translation to work) and you should be good to go. |
Using .format() to format a list with field width arguments | 10,875,121 | 16 | 2012-06-04T00:31:31Z | 10,875,142 | 29 | 2012-06-04T00:36:35Z | [
"python",
"list",
"string-formatting"
] | I recently (finally?) started to use `.format()` and
have a perhaps a bit obscure question about it.
Given
```
res = ['Irene Adler', 35, 24.798]
```
and
```
(1) print('{0[0]:10s} {0[1]:5d} {0[2]:.2f}'.format(res))
(2) print('{:{}s} {:{}d} {:{}f}'.format(res[0], 10, res[1], 5, res[2], .2))
```
work great and both ... | The error message
```
ValueError: cannot switch from manual field specification to automatic field numbering
```
pretty much says it all: You need to give explicit field indices everwhere, and
```
print('{0[0]:{1}s} {0[1]:{2}d} {0[2]:{3}f}'.format(res, 10, 5, .2))
```
works fine. |
Possible to change a function's repr in python? | 10,875,442 | 10 | 2012-06-04T01:36:49Z | 10,875,517 | 12 | 2012-06-04T01:52:58Z | [
"python",
"function",
"repr"
] | I've only seen examples for setting the `__repr__` method in class definitions. Is it possible to change the `__repr__` for functions either in their definitions or after defining them?
I've attempted without success...
```
>>> def f():
pass
>>> f
<function f at 0x1026730c8>
>>> f.__repr__ = lambda: '<New repr>'
... | Yes, if you're willing to forgo the function actually being a function.
First, define a class for our new type:
```
import functools
class reprwrapper(object):
def __init__(self, repr, func):
self._repr = repr
self._func = func
functools.update_wrapper(self, func)
def __call__(self, *a... |
Create a border abound a HBox/Any Widget | 10,875,937 | 2 | 2012-06-04T03:12:41Z | 10,877,019 | 7 | 2012-06-04T06:13:23Z | [
"python",
"gtk",
"pygtk"
] | **How can I create a border around a box/any widget in gtk?**
When I say border I mean the light gray rounded rectangle you see in the image below:

The functions I have attempted/looked for don't create a border, ie, set\_border() creates a inner ga... | Use a `gtk.Frame`:
```
import gtk
w = gtk.Window()
w.connect('destroy', lambda x: gtk.main_quit())
f = gtk.Frame()
b = gtk.HBox()
f.add(b)
w.add(f)
w.show_all()
gtk.main()
``` |
How do I know which python script is running in taskmgr? | 10,875,955 | 3 | 2012-06-04T03:16:49Z | 10,875,986 | 8 | 2012-06-04T03:23:00Z | [
"python",
"windows",
"taskmanager"
] | It seems that in the task manager all I get is the process of the python/pythonwin. So How can I figure out which python script is running? | The usual answer to such questions is [Process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx). You can see the full command line for any instance of `python.exe` or `pythonw.exe` in the tooltip.
To get the same information in Python, you can use the [psutil module](http://code.google.com/p/ps... |
Python list of tuples | 10,877,281 | 3 | 2012-06-04T06:43:15Z | 10,877,340 | 14 | 2012-06-04T06:49:33Z | [
"python"
] | ```
L1 = ['A', 'B', 'C', 'D']
L2 = [('A', 10)], ('B', 20)]
```
Now from these two list how can i generate common elements
```
output_list = [('A', 10), ('B', 20), ('C', ''), ('D', '')]
```
How can i get output\_list using L1 and L2?
I tried the following
```
for i in L2:
for j in L1:
if i[0] == j:
... | `[(k, dict(L2).get(k, '')) for k in L1]`
You can pull the `dict(L2)` out of the list comprehension if you don't want to recalculate it each time (e.g., if L2 is large).
```
d = dict(L2)
[(k, d.get(k, '')) for k in L1]
``` |
How can I memoize a class instantiation in Python? | 10,879,137 | 11 | 2012-06-04T09:32:08Z | 10,882,094 | 8 | 2012-06-04T13:22:36Z | [
"python",
"caching",
"singleton",
"unique",
"memoization"
] | Ok, here is the real world scenario: I'm writing an application, and I have a class that represents a certain type of files (in my case this is photographs but that detail is irrelevant to the problem). Each instance of the Photograph class should be unique to the photo's filename.
The problem is, when a user tells my... | Let us see two points about your question.
# Using memoize
You can use memoization, but you should decorate the *class*, not the `__init__` method. Suppose we have this memoizator:
```
def get_id_tuple(f, args, kwargs, mark=object()):
"""
Some quick'n'dirty way to generate a unique key for an specific call.... |
supervisord environment variables setting up application | 10,879,350 | 5 | 2012-06-04T09:49:22Z | 10,879,736 | 8 | 2012-06-04T10:21:14Z | [
"python",
"tornado",
"supervisord"
] | I'm running an application from supervisord and I have to set up an environment for it. There are about 30 environment variables that need to be set. I've tried putting all on one big
environment=
line and that doesn't seem to work. I've also tried multiple enviroment= lines, and that doesn't seem to work either. I'v... | The [`relevant documentation section`](http://supervisord.org/configuration.html#supervisord-section-values) explains that you need to list the variables as comma-separated key/value pairs:
> environment
>
> A list of key/value pairs in the form KEY=val,KEY2=val2 that will be placed in the supervisord processâ envir... |
Python : How to intercept a method call which does-not exists? | 10,879,806 | 6 | 2012-06-04T10:26:29Z | 10,879,860 | 19 | 2012-06-04T10:31:23Z | [
"python"
] | I want to create a class that doesn't gives an `Attribute Error` on call of any method that may or may not exists:
**My class:**
```
class magic_class:
...
# How to over-ride method calls
...
```
**Expected Output:**
```
ob = magic_class()
ob.unknown_method()
# Prints 'unknown_method' was called
ob.unk... | Overwrite the `__getattr__()` magic method:
```
class MagicClass(object):
def __getattr__(self, name):
def wrapper(*args, **kwargs):
print "'%s' was called" % name
return wrapper
ob = MagicClass()
ob.unknown_method()
ob.unknown_method2()
```
prints
```
'unknown_method' was called
'un... |
Sum / Average an attribute of a list of objects in Python | 10,879,867 | 23 | 2012-06-04T10:31:57Z | 10,879,883 | 62 | 2012-06-04T10:33:15Z | [
"python",
"list"
] | Lets say I have class `C` which has attribute `a`.
What is the best way to get the sum of `a` from a list of `C` in Python? | Use a [generator expression](http://docs.python.org/reference/expressions.html#generator-expressions):
```
sum(c.A for c in c_list)
``` |
Python - If given dictionary create a list of keys in order of the values | 10,880,112 | 2 | 2012-06-04T10:55:13Z | 10,880,123 | 10 | 2012-06-04T10:56:12Z | [
"python"
] | I have a dictionary that looks like the below.
```
ex1_pattern = {'ex':0,'country':1,'dow':2,'hod':3,'adx':4,'vid1':5}
```
I would like to create a lists of the keys e.g.
```
ex1_pattern.keys()
```
but..I would like the list to be in the order of the ranks. e.g.:
```
[ex,country,dow,hod,adx,vid1]
```
What is the ... | ```
sorted(ex1_pattern, key=ex1_pattern.get)
``` |
Robust algorithm for detection of peak widths | 10,880,266 | 12 | 2012-06-04T11:08:31Z | 10,884,446 | 16 | 2012-06-04T16:09:36Z | [
"python",
"scipy"
] | 
I asked [how to programmatically judge spectrum bands](http://stackoverflow.com/questions/10764569/these-spectrum-bands-used-to-be-judged-by-eye-how-to-do-it-programmatically) and [@detly](http://stackoverflow.com/users/188535/detly) suggested using F... | Fitting Gaussians is a good approach. And if you have okish guesses to the initial parameter values you can try and guess them all at once. A big problem is noise, really you probably want to either fit each peak in isolation (ie. only consider the range that a given peak is in at a time), or get a base line noise curv... |
TypeError: sequence item 0: expected string, int found | 10,880,813 | 62 | 2012-06-04T11:53:35Z | 10,880,820 | 117 | 2012-06-04T11:54:32Z | [
"python"
] | I am attempting to insert data from a dictionary into a database. I want to iterate over the values and format them accordingly, depending on the data type. Here is a snippet of the code I am using:
```
def _db_inserts(dbinfo):
try:
rows = dbinfo['datarows']
for row in rows:
field_name... | `string.join` connects elements inside list of strings, not ints.
Use this generator expression instead :
```
values = ','.join(str(v) for v in value_list)
``` |
Plotting vectors in a coordinate system with R or python | 10,882,336 | 6 | 2012-06-04T13:39:56Z | 10,882,498 | 11 | 2012-06-04T13:51:55Z | [
"python",
"vector",
"plot",
"coordinate-systems"
] | I am looking for advice on plotting vectors in the cartesian plane. The task is to plot points (coordinates) and then to link them with an arrow to some source point (say 0,0). The image below should give an idea. I don't care about colours and naming vectors/points, it's just about plotting arrows in the coordinate pl... | Or you can use `arrows` function in R.
```
plot(c(0,1),c(0,1))
arrows(0,0,1,1)
``` |
Plotting vectors in a coordinate system with R or python | 10,882,336 | 6 | 2012-06-04T13:39:56Z | 10,884,724 | 9 | 2012-06-04T16:30:00Z | [
"python",
"vector",
"plot",
"coordinate-systems"
] | I am looking for advice on plotting vectors in the cartesian plane. The task is to plot points (coordinates) and then to link them with an arrow to some source point (say 0,0). The image below should give an idea. I don't care about colours and naming vectors/points, it's just about plotting arrows in the coordinate pl... | ```
plot(NA, xlim=c(0,5), ylim=c(0,5), xlab="X", ylab="Y")
vecs <- data.frame(vname=c("a","b","a+b", "transb"),
x0=c(0,0,0,2),y0=c(0,0,0,1), x1=c(2,1,3,3) ,y1=c(1,2,3,3),
col=1:4)
with( vecs, mapply("arrows", x0, y0, x1,y1,col=col) )
```
It will look a bit better if you add lwd=... |
What's the Groovy equivalent to Python's dir()? | 10,882,469 | 6 | 2012-06-04T13:49:40Z | 10,882,525 | 8 | 2012-06-04T13:53:37Z | [
"python",
"groovy"
] | In Python I can see what methods and fields an object has with:
```
print dir(my_object)
```
What's the equivalent of that in Groovy (assuming it has one)? | Looks particulary nice in Groovy (untested, [taken from this link](http://noor.ojuba.org/2008/07/groovy-introspection-know-what-you-have/) so code credit should go there):
```
// Introspection, know all the details about classes :
// List all constructors of a class
String.constructors.each{println it}
// List all in... |
model and instance methods: session aware (sqlalchemy) | 10,882,980 | 6 | 2012-06-04T14:26:52Z | 10,884,953 | 14 | 2012-06-04T16:47:56Z | [
"python",
"sqlalchemy"
] | So, using and learning with sqlalchemy.
I have an instance, I need to get a value. If that value exists, return it.
If not calculate and return it.
Invariably someone will say 'you're doing it wrong' and input on improvement is appreciated in general.
However I am looking into how I can do this without explicitly hav... | Your question is so common, that the answer to it is in the [Session Frequently Asked Questions](http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#session-frequently-asked-questions) of SA documentation:
* How can I get the Session for a certain object?
Use the [object\_session()](http://docs.sqlalchemy.o... |
Why is the initial value to the reduce function not mandatory? | 10,882,986 | 2 | 2012-06-04T14:27:17Z | 10,883,109 | 7 | 2012-06-04T14:35:26Z | [
"python",
"functional-programming"
] | In haskell, the initial value for the `foldl` operator is clearly mandatory
```
Prelude> foldl (+) 0 [1]
1
Prelude> foldl (+) 0 []
0
Prelude> :t foldl
(a -> b -> a) -> a -> [b] -> a
```
But in the reduce function (or `functools.reduce`), the initial value is optional
```
reduce(function, sequence[, initial]) -> valu... | Recall that in Haskell there are two versions of folds - one that takes a seed of some result type, and one that assumes the seed is the first element of the sequence.
```
foldr :: (a -> b -> b) -> b -> [a] -> b
foldr k z = go
where
go [] = z
go (y:ys) = y `k` go ys
```
and
```
fo... |
How to time how long a Python program takes to run? | 10,883,387 | 5 | 2012-06-04T14:54:11Z | 10,883,406 | 8 | 2012-06-04T14:55:54Z | [
"python",
"time"
] | Is there a simple way to time a Python program's execution?
clarification: Entire programs | Use [`timeit`](http://docs.python.org/library/timeit.html):
> This module provides a simple way to time small bits of Python code. It has both command line as well as callable interfaces. It avoids a number of common traps for measuring execution times.
You'll need a python statement in a string; if you have a main f... |
Unable to encode/decode pprint output | 10,883,399 | 11 | 2012-06-04T14:55:40Z | 10,883,893 | 29 | 2012-06-04T15:28:41Z | [
"python",
"django",
"unicode",
"formatting"
] | This question is based on a side-effect of [that one](http://stackoverflow.com/q/10881326/257972).
My `.py` files are all have `# -*- coding: utf-8 -*-` encoding definer on the first line, like my `api.py`
As I mention on the related question, I use `HttpResponse` to return the api documentation. Since I defined enco... | `pprint` appears to use `repr` by default, you can work around this by overriding [`PrettyPrinter.format`](http://docs.python.org/library/pprint.html#pprint.PrettyPrinter.format):
```
# coding=utf8
import pprint
class MyPrettyPrinter(pprint.PrettyPrinter):
def format(self, object, context, maxlevels, level):
... |
Two-sample Kolmogorov-Smirnov Test in Python Scipy | 10,884,668 | 30 | 2012-06-04T16:25:37Z | 10,884,762 | 52 | 2012-06-04T16:32:07Z | [
"python",
"numpy",
"statistics",
"scipy"
] | I can't figure out how to do a Two-sample KS test in Scipy.
After reading the documentation [scipy kstest](http://docs.scipy.org/doc/scipy-0.7.x/reference/generated/scipy.stats.kstest.html)
I can see how to test where a distribution is identical to standard normal distribution
```
from scipy.stats import kstest
impo... | You're using the one-sample KS test. You probably want [ks\_2samp](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.ks_2samp.html):
```
>>> from scipy.stats import ks_2samp
>>> import numpy as np
>>>
>>> np.random.seed(12345678);
>>> x = np.random.normal(0,1,1000)
>>> y = np.random.normal(0,1,1000)
>>>... |
Python timeit and program output | 10,884,751 | 9 | 2012-06-04T16:31:22Z | 10,884,888 | 11 | 2012-06-04T16:42:50Z | [
"python",
"time",
"timeit"
] | Is there any way to use the timeit function to output both the function result and the time it took to process at the same time?
Right now I am using
```
timer = Timer('func()', 'from __main__ import func')
print timer.timeit(1)
```
But this just outputs the time and not the program output, which returns something a... | Two options:
1. Include 'print' in your timed code. Ugly, but hey.
```
timer = Timer('print func()', 'from __main__ import func')
print timer.timeit(1)
```
2. If all you do is run your function once, then dispense with the `timeit` module altogether and time the code directly using the same method:
``... |
raw_input("") has been eliminated from python 3.2 | 10,885,537 | 18 | 2012-06-04T17:34:23Z | 10,885,555 | 41 | 2012-06-04T17:35:50Z | [
"python",
"python-3.x",
"python-2.7"
] | I have tried a lot to run `raw_input("")` on the python console but that gives an error. Moreover I watch some videos that might have been made on old python. so `input("")` is the only method and why `raw_input("")` is discarded in the new version is there any reason ? | `raw_input()` was renamed to `input()` in Python v3.x
The old `input()` is gone, but you can emulate it with `eval(input())`
[What's new in Python 3](http://docs.python.org/dev/py3k/whatsnew/3.0.html) will mention this (and more):
> [PEP 3111](http://www.python.org/dev/peps/pep-3111/): raw\_input() was renamed to [i... |
Python 'list' object is not callable | 10,886,003 | 2 | 2012-06-04T18:09:27Z | 10,886,035 | 8 | 2012-06-04T18:11:28Z | [
"python",
"pyscripter"
] | I tried running the following code in Pyscripter but it keeps returning the error "'list' object is not callable". I ran the code through the Python shell and it worked perfectly fine. I'm not quite understanding why it isn't working in Pyscripter. Also, I'm using Python 2.7.
```
import itertools
print list(itertools.... | Almost certainly you've rebound the name list to a list instance:
```
>>> import itertools
>>> print list(itertools.permutations([1,2,3,4], 2))
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]
>>>
>>> list = [2,3,4]
>>> list(itertools.permutations([1,2,3,4], 2))
Traceba... |
Is it possible to create .mobi files with python? if so, how? | 10,886,499 | 4 | 2012-06-04T18:43:36Z | 10,893,632 | 8 | 2012-06-05T07:59:27Z | [
"python",
"kindle"
] | I want to be able to create .mobi files with python, but i haven't found anything about it after an hour of searching. I don't want to use Calibre or softwares like it, just plain python. | I'd recommend to take a look at [this repo](https://github.com/mhl/guardian-for-kindle), if you don't want to use `calibre` (which is great and has a CLI). While [this script](https://github.com/mhl/guardian-for-kindle/blob/master/make-guardian-ebook.py) has created for creating a `.mobi` for the Guardian, you can modi... |
Sphinx and argparse - autodocumenting command line scripts? | 10,886,841 | 18 | 2012-06-04T19:08:33Z | 10,893,855 | 14 | 2012-06-05T08:19:09Z | [
"python",
"documentation",
"python-sphinx",
"argparse"
] | I'm building a Python package, and using Sphinx to create the docs. Aside from my package code, I also include a lot of command line Python scripts, which use argparse. I was wondering if there is a way to get Sphinx to autodocument these scripts? The end goal would be a pretty-printed list of scripts, with the associa... | You can use [`sphinxcontrib.programoutput`](http://packages.python.org/sphinxcontrib-programoutput/) to include the help messages from the command line in your documentation.
This is not specific to `argparse` but can be used to document any script printing help messages to the command line. |
Sphinx and argparse - autodocumenting command line scripts? | 10,886,841 | 18 | 2012-06-04T19:08:33Z | 18,634,447 | 12 | 2013-09-05T10:54:24Z | [
"python",
"documentation",
"python-sphinx",
"argparse"
] | I'm building a Python package, and using Sphinx to create the docs. Aside from my package code, I also include a lot of command line Python scripts, which use argparse. I was wondering if there is a way to get Sphinx to autodocument these scripts? The end goal would be a pretty-printed list of scripts, with the associa... | Use sphinx-argparse extension:
<http://sphinx-argparse.readthedocs.org/en/latest/> |
How does IPython's magic %paste work? | 10,886,946 | 67 | 2012-06-04T19:16:04Z | 10,886,947 | 99 | 2012-06-04T19:16:04Z | [
"python",
"ipython"
] | I want to copy already indented Python code / whole functions and classes into IPython. Everytime I try the indentation is screwed up and I get following error message:
`IndentationError: unindent does not match any outer indentation level (<ipython-input-23-354f8c8be51b>, line 12)`
`If you want to paste code into IP... | You can't copy to IPython directly. This are the steps:
1. Copy the lines you want to copy into IPython into the clipboard
2. Enter `%paste` into IPython
3. Press enter
4. Profit! |
How does IPython's magic %paste work? | 10,886,946 | 67 | 2012-06-04T19:16:04Z | 25,129,812 | 25 | 2014-08-05T01:06:45Z | [
"python",
"ipython"
] | I want to copy already indented Python code / whole functions and classes into IPython. Everytime I try the indentation is screwed up and I get following error message:
`IndentationError: unindent does not match any outer indentation level (<ipython-input-23-354f8c8be51b>, line 12)`
`If you want to paste code into IP... | A clarification on the steps:
* First, copy target lines into your clipboard.
* Type into the iPython prompt:
+ If on Tkinter: enter `%paste`
+ Otherwise: enter `%cpaste`
* Paste (Ctrl-V) and hit enter.
* Then type `--` and hit enter.
For example:
```
In [1]: %cpaste
Pasting code; enter '--' alone on the line t... |
Can we run multiple functions each with timeit in the same module | 10,887,131 | 5 | 2012-06-04T19:28:37Z | 10,887,220 | 7 | 2012-06-04T19:37:10Z | [
"python",
"timeit"
] | I would like to write multiple functions in the same Python module, each of which is a separate profiling test using `timeit`, so that I can use command line argument to specify which one to run. A naive example (profiling.py) would be:
```
import sys
import timeit
def foo():
setup = """
import random
""... | This works:
```
import sys
import timeit
def foo():
setup = """
import random
"""
foo_1 = """
for i in range(1000):
random.randint(0, 99) + random.randint(0, 99)
"""
foo_2 = """
for i in range(1000):
random.randint(0, 99) + random.randint(0, 99)
"""
foo_3 = """
for i in range(1000):
ra... |
How can I configure Pyramid's JSON encoding? | 10,887,324 | 5 | 2012-06-04T19:45:07Z | 10,887,526 | 7 | 2012-06-04T20:00:36Z | [
"python",
"json",
"pyramid",
"pymongo"
] | I'm trying to return a function like this:
```
@view_config(route_name='CreateNewAccount', request_method='GET', renderer='json')
def returnJSON(color, message=None):
return json.dumps({ "color" : "color", "message" : "message" }, default=json_util.default)
```
Because of Pyramid's own JSON encoding, it's coming... | It seems like the dictionary is being JSON-encoded twice, the equivalent of:
```
json.dumps(json.dumps({ "color" : "color", "message" : "message" }))
```
Perhaps your Python framework automatically JSON-encodes the result? Try this instead:
```
def returnJSON(color, message=None):
return { "color" : "color", "mess... |
What tracking solutions are available for server side code? | 10,888,403 | 2 | 2012-06-04T21:09:18Z | 14,470,343 | 12 | 2013-01-23T00:10:34Z | [
"python",
"google-analytics",
"tracking",
"google-analytics-api"
] | I'm working on a tracking proxy (for want of a better term) written in Python. It's a simple http (wsgi) application that will run on one (maybe more) server and accepts event data from a desktop client. This service would then forward the tracking data on to some actual tracking platform (DeskMetrics, MixPanel, Google... | We ran into this same problem a bunch of times, we ended up building a suite of server-side analytics libraries to make this easier.
Segment.io has libraries for [Python](https://segment.io/libraries/python), [Ruby](https://segment.io/libraries/ruby), [Java](https://segment.io/libraries/java), [Node](https://segment.i... |
What version of Pyramid do I have and what's the best way to update? | 10,888,577 | 7 | 2012-06-04T21:23:40Z | 10,895,485 | 15 | 2012-06-05T10:17:01Z | [
"python",
"pyramid"
] | I'm using Pyramid and I'm wondering how I can check what version I'm currently using. Also, how can I update my Pyramid? | To know which version of pyramid you have, you can run this in a python console :
```
>>> import pkg_resources
>>> pkg_resources.get_distribution("pyramid").version
```
To update, you could run `pip install --upgrade pyramid`, but in order to update pyramid and all its dependencies, I advice you to replace your curre... |
Using dict_cursor in django | 10,888,844 | 7 | 2012-06-04T21:47:51Z | 14,294,314 | 10 | 2013-01-12T14:35:14Z | [
"python",
"django"
] | To get a cursor in django I do:
```
from django.db import connection
cursor = connection.cursor()
```
How would I get a dict cursor in django, the equivalent of -
```
import MySQLdb
connection = (establish connection)
dict_cursor = connection.cursor(MySQLdb.cursors.DictCursor)
```
Is there a way to do this in djang... | No there is no such support for `DictCursor` in django. But you can write a small function to that for you, see this [ticket](https://code.djangoproject.com/ticket/16293):
```
def dictfetchall(cursor):
"Returns all rows from a cursor as a dict"
desc = cursor.description
return [
dict(zip([co... |
Python subprocess module much slower than commands (deprecated) | 10,888,846 | 7 | 2012-06-04T21:48:12Z | 10,889,177 | 9 | 2012-06-04T22:17:26Z | [
"python",
"performance",
"command",
"subprocess"
] | So I wrote a script that accesses a bunch of servers using nc on the command line, and originally I was using Python's commands module and calling commands.getoutput() and the script ran in about 45 seconds. Since commands is deprecated, I want to change everything over to using the subprocess module, but now the scrip... | I would expect `subprocess` to be slower than `command`. Without meaning to suggest that this is the *only* reason your script is running slowly, you should take a look at the [`commands`](http://hg.python.org/cpython/file/477508efe4ab/Lib/commands.py) source code. There are fewer than 100 lines, and most of the work i... |
Python subprocess module much slower than commands (deprecated) | 10,888,846 | 7 | 2012-06-04T21:48:12Z | 10,889,406 | 11 | 2012-06-04T22:42:37Z | [
"python",
"performance",
"command",
"subprocess"
] | So I wrote a script that accesses a bunch of servers using nc on the command line, and originally I was using Python's commands module and calling commands.getoutput() and the script ran in about 45 seconds. Since commands is deprecated, I want to change everything over to using the subprocess module, but now the scrip... | There seems to be at least two separate issues here.
First, you are improperly using Popen. Here are the problems I see:
1. Spawning multiple processes with one Popen.
2. Passing one string in as args instead of splitting args.
3. Using the shell to pass text to process rather than the builtin communicate method.
4. ... |
Can I make the Django database path (for sqlite3) "cross-platform"? | 10,889,388 | 7 | 2012-06-04T22:40:41Z | 10,889,585 | 21 | 2012-06-04T23:04:19Z | [
"python",
"windows",
"django",
"linux",
"osx"
] | I'm in the process of learning Django and Python (as well as programming in general). For the sake of simplicity, I am using sqlite3 as my database while I'm going through tutorials for Django and such.
I am a multi-platform user (Mac OS, Windows, Linux) depending on where I am at the time. So, what I have done is put... | Using [relative paths in settings.py](http://agiliq.com/books/djangodesignpatterns/misc.html#use-relative-path-in-settings-py) is a common enough to be considered a best practice by many. Something like this may help.
```
from os.path import dirname, join
PROJECT_DIR = dirname(__file__)
DATABASES = {
# ...
'... |
How do I implement a custom MIB in PySNMP? | 10,890,069 | 6 | 2012-06-05T00:18:12Z | 10,900,723 | 7 | 2012-06-05T16:01:00Z | [
"python",
"mib",
"pysnmp"
] | I already have the MIB text file (do I need to make this into a .py file somehow??). I am trying to use PySNMP (not net-snmp). I have been able to connect to my device and print out some info, but the info was not very helpful (just ObjectName, ObjectIdentifier, etc). I want to be able to communicate with the device (s... | To use MIBs with pysnmp you should first convert your MIB into pysnmp format (which is a collection of Python objects). The conversion is done with the pysnmp/tools/build-pysnmp-mib shell script in the following manner:
```
$ sh build-pysnmp-mib -h
build-pysnmp-mib: illegal option -- h
Convert MIB text file into PySNM... |
Django - catch exception | 10,890,368 | 6 | 2012-06-05T01:07:54Z | 10,890,416 | 16 | 2012-06-05T01:16:54Z | [
"python",
"django",
"exception-handling"
] | It might be a Python newbie question...
```
try:
#do something
except:
raise Exception('XYZ has gone wrong...')
```
Even with DEBUG=True, I don't want this `raise Exception` gives me that yellow page. I actually want to handle the exception by redirecting users to an error page or shows the error (give a CSS er... | You have three options here.
1. Provide a [404 handler or 500 handler](https://docs.djangoproject.com/en/dev/topics/http/views/#the-404-page-not-found-view)
2. Catch the exception elsewhere in your code and do appropriate redirection
3. Provide custom middleware with the `process_exception` implemented
Middleware Exa... |
Adding a database to the Django Project using Sqlite3 with Python 2.7 | 10,891,255 | 9 | 2012-06-05T03:38:40Z | 10,894,385 | 16 | 2012-06-05T09:00:20Z | [
"python",
"database",
"django",
"python-2.7"
] | I am trying to add a database to the Django Project using Sqlite3 and Python 2.7.
This is how my setting.py looks like:
```
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'dev.db', # Or pa... | Type this before you execute the python manage.py syncdb
```
export LC_CTYPE=en_US.UTF-8
export LC_ALL=en_US.UTF-8
```
This will solve the error.. Btw i was using mac os x python which was in /usr/bin/python.
Add it to the ./.bash\_profile file so that it calls it automatically.. |
Python: confusions with urljoin | 10,893,374 | 21 | 2012-06-05T07:34:50Z | 10,893,427 | 34 | 2012-06-05T07:39:46Z | [
"python",
"python-3.x"
] | I am trying to form URLs from different pieces, and having trouble understanding the behavior of this method. For example:
**Python 3.x**
```
from urllib.parse import urljoin
>>> urljoin('some', 'thing')
'thing'
>>> urljoin('http://some', 'thing')
'http://some/thing'
>>> urljoin('http://some/more', 'thing')
'http://... | The best way (for me) to think of this is the first argument, `base` is like the page you are on in your browser. The second argument `url` is the href of an anchor on that page. The result is the final url to which you will be directed should you click.
```
>>> urljoin('some', 'thing')
'thing'
```
This one makes sen... |
Please explain why these two builtin functions behave different when passed in keyword arguments | 10,894,135 | 7 | 2012-06-05T08:43:34Z | 10,894,198 | 7 | 2012-06-05T08:48:35Z | [
"python"
] | Consider these different behaviour::
```
>> def minus(a, b):
>> return a - b
>> minus(**dict(b=2, a=1))
-1
>> int(**dict(base=2, x='100'))
4
>> import operator
>> operator.sub.__doc__
'sub(a, b) -- Same as a - b.'
>> operator.sub(**dict(b=2, a=1))
TypeError: sub() takes no keyword arguments
```
Why does `operat... | It is an implementation detail. The [Python C API to retrieve arguments](http://docs.python.org/c-api/arg.html#PyArg_UnpackTuple) separates between positional and keyword arguments. Positional arguments do not even have a name internally.
The code used to retrieve the arguments of the `operator.add` functions (and sim... |
What does the c underscore expression `c_` do exactly? | 10,894,323 | 8 | 2012-06-05T08:56:58Z | 10,948,706 | 10 | 2012-06-08T12:17:06Z | [
"python",
"numpy"
] | It seems to be some kind of horizontal concatenation, but I could not find any documentation online. Here a minimal working example:
```
In [1]: from numpy import c_
In [2]: a = ones(4)
In [3]: b = zeros((4,10))
In [4]: c_[a,b]
Out[4]:
array([[ 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[ 1., ... | Use IPython's `?` syntax to get more information:
```
In [2]: c_?
Type: CClass
Base Class: <class 'numpy.lib.index_tricks.CClass'>
String Form:<numpy.lib.index_tricks.CClass object at 0x9a848cc>
Namespace: Interactive
Length: 0
File: /usr/lib/python2.7/dist-packages/numpy/lib/index_tricks.py
Docstring... |
python: outfile to another text file if exceed certain file size | 10,894,692 | 3 | 2012-06-05T09:21:32Z | 10,896,813 | 11 | 2012-06-05T11:52:24Z | [
"python",
"file-io"
] | I using scapy with python in ubuntu. I would like to ask if anyone would know how to code the example:
let say I have two text files which are writing while the script is running then I would like to check the file is exceed example 500bytes, if does then it will store whatever in the file and create a new text file t... | A simple example if you don't want to use [RotatingFileHandler](http://docs.python.org/library/logging.handlers.html#rotatingfilehandler).
You should use `os.stat('filename').st_size` to check file sizes.
```
import os
import sys
class RotatingFile(object):
def __init__(self, directory='', filename='foo', max_fi... |
jinja2 nested variables | 10,894,693 | 4 | 2012-06-05T09:21:38Z | 10,895,018 | 17 | 2012-06-05T09:42:58Z | [
"python",
"yaml",
"jinja2"
] | I am currently learning jinja2 and i am unsure on how to address variables the correct way:
Here are my variables in yaml:
```
---
hosts:
app201.acme.com: {eth0: {ip: 46.0.0.1, netmask: 255.255.255.255}}
graphite.acme.com: {eth0: {ip: 46.0.0.2, netmask: 255.255.255.255},
eth0.1: {ip: 10.2... | The variable `hosts` is a `dict`. The correct way to access values in `dict` is to use `[]` operator.
```
{{ fqdn }}
{% for interface in hosts[fqdn] %}
{{ interface }}
{{ hosts[fqdn][interface]['ip'] }}
{% endfor %}
```
`.` operator is used to access attribute of an object. |
python append to array in json object | 10,895,028 | 7 | 2012-06-05T09:43:32Z | 10,895,081 | 10 | 2012-06-05T09:47:04Z | [
"python",
"arrays",
"json",
"append"
] | I have the following json object in python:
```
jsonobj = {
"a": {
"b": {
"c": var1,
"d": var2,
"e": [],
},
},
}
```
And I would like to append key-value elements into "e", but can... | ```
jsobj["a"]["b"]["e"].append({"f":var3, "g":var4, "h":var5})
jsobj["a"]["b"]["e"].append({"f":var6, "g":var7, "h":var8})
``` |
Find items within a certain range of given coordinate | 10,895,256 | 4 | 2012-06-05T10:01:13Z | 10,895,674 | 11 | 2012-06-05T10:30:28Z | [
"android",
"python",
"django"
] | I have a django based web app which stores locations.
I have an android mobile app which pulls the locations from the web app and saves locations to the web app. The locations returned back to me I load on a mapoverlay in my app.
I would like to send my current coordinates and return a list of locations which are wit... | [Haversine Equation](http://en.wikipedia.org/wiki/Haversine_formula) is the answer to your question. However it is slightly difficult to decrypt so here I provide you with a simple explanation:
To put it simply:
Here's the sample/example SQL statement that will find the closest 20 locations that are within a radius o... |
scraping the file with html saved in local system | 10,895,419 | 7 | 2012-06-05T10:12:53Z | 10,897,298 | 8 | 2012-06-05T12:27:23Z | [
"python",
"scrapy"
] | For example i had a site `"www.example.com"`
Actually i want to scrape the html of this site by saving on to local system.
so for testing i saved that page on my desktop as `example.html`
Now i had written the spider code for this as below
```
class ExampleSpider(BaseSpider):
name = "example"
start_urls = ["exa... | You can use the HTTPCacheMiddleware, which will give you the ability to to a spider run from cache. The doc for the HTTPCacheMiddleware settings are located [here](http://doc.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings).
Basically, adding the following settings to your settings... |
scraping the file with html saved in local system | 10,895,419 | 7 | 2012-06-05T10:12:53Z | 22,207,892 | 9 | 2014-03-05T19:56:23Z | [
"python",
"scrapy"
] | For example i had a site `"www.example.com"`
Actually i want to scrape the html of this site by saving on to local system.
so for testing i saved that page on my desktop as `example.html`
Now i had written the spider code for this as below
```
class ExampleSpider(BaseSpider):
name = "example"
start_urls = ["exa... | You can crawl a local file using an url of the following form:
```
file://127.0.0.1/path/to/file.html
```
It doesn't require an http server to be installed on your machine. |
Find longest (string) key in dictionary | 10,895,567 | 2 | 2012-06-05T10:22:53Z | 10,895,641 | 8 | 2012-06-05T10:28:17Z | [
"python"
] | This question is similar to [Python - Find longest (most words) key in dictionary](http://stackoverflow.com/questions/4321160/python-find-longest-most-words-key-in-dictionary) - but I need the pure number of characters.
Example input:
```
d = {'group 1': 1, 'group 1000': 0}
```
Output:
```
10
``` | ```
>>> d = {'group 1': 1, 'group 1000': 0}
>>> len(max(d, key=len))
10
```
This solution is the fastest but I prefer the solutions by @eumiro and @ms4py since they do not repeat the `len` function twice and are more pythonic imo. |
Find longest (string) key in dictionary | 10,895,567 | 2 | 2012-06-05T10:22:53Z | 10,895,710 | 8 | 2012-06-05T10:33:20Z | [
"python"
] | This question is similar to [Python - Find longest (most words) key in dictionary](http://stackoverflow.com/questions/4321160/python-find-longest-most-words-key-in-dictionary) - but I need the pure number of characters.
Example input:
```
d = {'group 1': 1, 'group 1000': 0}
```
Output:
```
10
``` | ```
>>> max(len(x) for x in d)
```
or
```
>>> max(map(len, d))
``` |
Find longest (string) key in dictionary | 10,895,567 | 2 | 2012-06-05T10:22:53Z | 10,896,303 | 8 | 2012-06-05T11:15:11Z | [
"python"
] | This question is similar to [Python - Find longest (most words) key in dictionary](http://stackoverflow.com/questions/4321160/python-find-longest-most-words-key-in-dictionary) - but I need the pure number of characters.
Example input:
```
d = {'group 1': 1, 'group 1000': 0}
```
Output:
```
10
``` | Alternative, which is as fast as @jamylak's solution and more pythonic:
```
from itertools import imap
max(imap(len, d))
```
See comparison:
```
$ python -m timeit -s "d = {'group 1': 1, 'group 1000': 0}" "len(max(d,key=len))"
1000000 loops, best of 3: 0.538 usec per loop
$ python -m timeit -s "d = {'group 1': 1, '... |
Simple animation of 2D coordinates using matplotlib and pyplot | 10,896,054 | 4 | 2012-06-05T10:56:52Z | 10,896,688 | 8 | 2012-06-05T11:42:30Z | [
"python",
"animation",
"python-2.7",
"matplotlib"
] | I am new to matplotlib. I have a list of x-y coordinates that I update in python and want to animate using matplotlib's pyplot. I want to specify the x-range and y-range in advance. Below is my current code:
```
import matplotlib.pyplot as plt
x=[1,2,3,4]
y=[5,6,7,8]
for t in range(100):
#lists x and y get updated... | This is adapted from the [animation demo](http://matplotlib.sourceforge.net/examples/pylab_examples/animation_demo.html):
```
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
for t in range(10):
if t == 0:
points, = ax.plot(x, y, marker='o', ... |
Selecting between shelve and sqlite for really large dictionary (Python) | 10,896,395 | 5 | 2012-06-05T11:22:07Z | 10,896,543 | 7 | 2012-06-05T11:32:34Z | [
"python",
"sqlite",
"dictionary",
"persistence",
"shelve"
] | I have a large Python dictionary of vectors (150k vectors, 10k dimensions each) of float numbers that can't be loaded into memory, so I have to use one of the two methods for storing this on disk and retrieving specific vectors when appropriate. The vectors will be created and stored once, but might be read many (thous... | You want sqlite3, then if you use an ORM like [sqlalchemy](http://www.sqlalchemy.org/) then you can easily grow to expand and use other back end databases.
Shelve is more of a "toy" than actually useful in production code.
The other point you are talking about is called normalization and I have personally never been ... |
python float to in int conversion | 10,898,215 | 5 | 2012-06-05T13:28:13Z | 10,898,267 | 13 | 2012-06-05T13:31:06Z | [
"python",
"floating-point"
] | I have an issue that really drives me mad. Normally doing `int(20.0)` would result in `20`. So far so good. But:
```
levels = [int(gex_dict[i]) for i in sorted(gex_dict.keys())]
```
while `gex_dict[i]` returns a float, e.g. `20.0`, results in:
```
"invalid literal for int() with base 10: '20.0'"
```
I am just one s... | `'20.0'` is a string, not a `float`; you can tell by the single-quotes in the error message. You can get an `int` out of it by first parsing it with `float`, then truncating it with `int`:
```
>>> int(float('20.0'))
20
```
(Though maybe you'd want to store floats instead of strings in your dictionary, since that is w... |
How to prevent try catching every possible line in python? | 10,898,873 | 12 | 2012-06-05T14:06:37Z | 10,898,930 | 14 | 2012-06-05T14:09:51Z | [
"python",
"exception",
"exception-handling"
] | I got many lines in a row which may throw an exception, but no matter what, it should still continue the next line. How to do this without individually try catching every single statement that may throw an exception?
```
try:
this_may_cause_an_exception()
but_I_still_wanna_run_this()
and_this()
and_als... | ```
for func in [this_may_cause_an_exception,
but_I_still_wanna_run_this,
and_this,
and_also_this]:
try:
func()
except:
pass
```
There are two things to notice here:
* All actions you want to perform have to represented by callables with the same signatur... |
How to set the margins for a matplotlib figure? | 10,898,919 | 14 | 2012-06-05T14:09:37Z | 10,927,146 | 21 | 2012-06-07T07:03:37Z | [
"python",
"matplotlib"
] | I am generating an on-screen figure that has two subplots: one is an image and the other is a graph. The margins are extremely large around the figures.
How do I adjust the margins around the figures?
---
Most questions that I searched for involved saving images (bbox seemed perfect), and using axes instead of subpl... | Have a look at [`plt.tight_layout()`](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.tight_layout) or [`plt.subplots_adjust()`](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.subplots_adjust) or `fig.savefig(bbox_inches='tight')`.
With `subplots_adjust` you can adjust ... |
Exit python properly | 10,900,748 | 3 | 2012-06-05T16:02:35Z | 10,900,824 | 9 | 2012-06-05T16:07:08Z | [
"python"
] | I knew that sys.exit() raises an Exit exception, so when I run this I knew it wouldn't exit:
```
In [25]: try:
....: sys.exit()
....: except:
....: print "oops"
....:
oops
```
But I thought that os.\_exit() was meant to exit using a C call, but it's also causing an exception:
```
In [28]: tr... | I'm not sure I understand your question, but `os._exit` isn't raising an exception -- you calling `os._exit` with the wrong number of arguments is:
```
try:
os._exit()
except Exception as e:
print e
#output: _exit() takes exactly 1 argument (0 given)
``` |
I want to subclass dict and set default values | 10,901,048 | 2 | 2012-06-05T16:23:17Z | 10,901,498 | 8 | 2012-06-05T16:54:29Z | [
"python",
"dictionary",
"subclass"
] | I have a need to create a special subclass of dict. In it I want to set default values for a set of keys.
I seem to be failing in finding the correct syntax to do this.
Here is what I have been trying:
```
class NewDict(dict):
Key1 = "stuff"
Key2 = "Other stuff"
NoList = []
Nada = None
```
I am then... | No subclassing needed:
```
def predefined_dict(**kwargs):
d = {
'key1': 'stuff',
...
}
d.update(kwargs)
return d
new_dict = predefined_dict()
print new_dict['key1']
```
or just:
```
defaults = {'a':1, 'b':2}
new_dict = defaults.copy()
print new_dict['a']
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.