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 |
|---|---|---|---|---|---|---|---|---|---|
Checking if all elements in a list are unique | 5,278,122 | 51 | 2011-03-11T20:44:28Z | 5,278,195 | 14 | 2011-03-11T20:50:59Z | [
"python",
"algorithm",
"list",
"unique"
] | What is the best way (best as in the conventional way) of checking whether all elements in a list are unique?
My current approach using a `Counter` is:
```
>>> x = [1, 1, 1, 2, 3, 4, 5, 6, 2]
>>> counter = Counter(x)
>>> for values in counter.itervalues():
if values > 1:
# do something
```
Can I... | An early-exit solution could be
```
def unique_values(g):
s = set()
for x in g:
if x in s: return False
s.add(x)
return True
```
however for small cases or if early-exiting is not the common case then I would expect `len(x) != len(set(x))` being the fastest method. |
Checking if all elements in a list are unique | 5,278,122 | 51 | 2011-03-11T20:44:28Z | 5,281,641 | 50 | 2011-03-12T09:12:25Z | [
"python",
"algorithm",
"list",
"unique"
] | What is the best way (best as in the conventional way) of checking whether all elements in a list are unique?
My current approach using a `Counter` is:
```
>>> x = [1, 1, 1, 2, 3, 4, 5, 6, 2]
>>> counter = Counter(x)
>>> for values in counter.itervalues():
if values > 1:
# do something
```
Can I... | Here is a two-liner that will also do early exit:
```
>>> def allUnique(x):
... seen = set()
... return not any(i in seen or seen.add(i) for i in x)
...
>>> allUnique("ABCDEF")
True
>>> allUnique("ABACDEF")
False
```
If the elements of x aren't hashable, then you'll have to resort to using a list for `seen`:
... |
How do I load a file into the python console? | 5,280,178 | 92 | 2011-03-12T01:26:11Z | 5,280,202 | 11 | 2011-03-12T01:33:04Z | [
"python"
] | I have some lines of python code that I'm continuously copying/pasting into the python console. Is there a `load` command or something I can run? e.g. `load file.py` | From the shell command line:
```
python file.py
```
From the Python command line
```
import file
```
or
```
from file import *
``` |
How do I load a file into the python console? | 5,280,178 | 92 | 2011-03-12T01:26:11Z | 5,280,205 | 118 | 2011-03-12T01:34:26Z | [
"python"
] | I have some lines of python code that I'm continuously copying/pasting into the python console. Is there a `load` command or something I can run? e.g. `load file.py` | Give this a try:
```
execfile('file.py')
```
Example usage:
```
C:\junk>copy con execfile_example.py
a = [9, 42, 888]
b = len(a)
^Z
1 file(s) copied.
C:\junk>\python27\python
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license... |
How do I load a file into the python console? | 5,280,178 | 92 | 2011-03-12T01:26:11Z | 5,280,210 | 54 | 2011-03-12T01:35:57Z | [
"python"
] | I have some lines of python code that I'm continuously copying/pasting into the python console. Is there a `load` command or something I can run? e.g. `load file.py` | From the man page:
> -i When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command. It does not read the $PYTHONSTARTUP file. This can be useful to inspect global variables or a stack trace when a script raises an exception.
So this should do w... |
How do I load a file into the python console? | 5,280,178 | 92 | 2011-03-12T01:26:11Z | 36,496,608 | 8 | 2016-04-08T09:53:27Z | [
"python"
] | I have some lines of python code that I'm continuously copying/pasting into the python console. Is there a `load` command or something I can run? e.g. `load file.py` | **Python 3: new exec** *(execfile dropped)* **!**
The execfile solution is valid only for Python 2. Python 3 dropped the execfile function - and promoted the exec statement to a builtin universal function. As the comment in Python 3.0's changelog and Hi-Angels comment suggest:
use
```
exec(open(<filename.py>).read()... |
What does this mean exit (main()) | 5,280,203 | 9 | 2011-03-12T01:34:23Z | 5,280,221 | 12 | 2011-03-12T01:38:21Z | [
"python"
] | I have seen this in a couple of python script I have been reading lately. I have looked at the doc; they only give examples deal with passing a termination value or string of some sort.
I think what this does is call the main method, then exit?
If someone could shed some light on this I would appreciate it.
```
if _... | This will call the function `main()` and when main finishes, it will exit giving the system the return code that is the result of `main()`.
A simplified example where this might be used:
```
def main():
Try:
doSomething()
return 0
Except:
return 1
if __name__ == "__main__":
exit ... |
What does this mean exit (main()) | 5,280,203 | 9 | 2011-03-12T01:34:23Z | 5,280,241 | 10 | 2011-03-12T01:40:53Z | [
"python"
] | I have seen this in a couple of python script I have been reading lately. I have looked at the doc; they only give examples deal with passing a termination value or string of some sort.
I think what this does is call the main method, then exit?
If someone could shed some light on this I would appreciate it.
```
if _... | If you execute a Python script directly, `__name__` is set to `"__main__"`, but if you `import` it from another script, it is not.
So in this case, the script is seeing if you're executing it directly. If it is, it calls the `main()` function to perform some work, and returns the return value of the `main()` function ... |
List.append() changing all elements to the appended item | 5,280,799 | 2 | 2011-03-12T05:35:19Z | 5,280,883 | 7 | 2011-03-12T05:55:24Z | [
"python",
"list",
"append",
"maze"
] | I seem to have a problem with my maze generating program made in Python. I'm trying to randomly create a path that branches out at select points, with the points getting stored as it goes along. When the maze gets to a dead end, it will sort back through the visited points by testing the top value than popping that and... | I believe the `current` list is simply copied multiple times into `past`. So you have multiple copies of the *same* list.
To fix: in the line `past.append(current)` (two lines below `def Gen(x,y):`), change it to `past.append(current[:])`.
The notation `list[:]` creates a copy of the list. Technically, you are creati... |
Get local network interface addresses using only proc? | 5,281,341 | 24 | 2011-03-12T07:42:19Z | 5,281,403 | 10 | 2011-03-12T08:05:24Z | [
"python",
"linux",
"networking",
"ipv4",
"procfs"
] | **How can I obtain the (IPv4) addresses for all network interfaces using only [proc](http://linux.die.net/man/5/proc)?** After some extensive investigation I've discovered the following:
1. `ifconfig` makes use of `SIOCGIFADDR`, which requires open sockets and advance knowledge of all the interface names. It also isn'... | You may find the output of `ip addr show` easier to parse than output from other tools:
```
$ ip addr show
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 16436 qdisc noqueue state UNKNOWN
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
inet6 ::1/128 scope host
valid_lft forev... |
how to set the admin user with GAE dev app server? | 5,283,506 | 3 | 2011-03-12T15:44:11Z | 5,284,906 | 7 | 2011-03-12T19:31:10Z | [
"python",
"google-app-engine"
] | I want to create an Admin-only page for my GAE application. But I found there's no way to set a Admin user, so I cannot log on the page I created and test the function. I tried the local Admin console, but no luck. How can I do this? | Google App Engine provides a pretty straightforward way to create a private admin section of your web application.
**1.**
In your `app.yaml`, any URL handler can have a login setting to restrict visitors to only those users who have signed in, or just those users who are administrators for the application.
If the ... |
Load JavaScript in Google App Engine | 5,283,559 | 3 | 2011-03-12T15:53:10Z | 5,283,643 | 16 | 2011-03-12T16:05:24Z | [
"javascript",
"jquery",
"python",
"google-app-engine"
] | I got so confused loading JavaScript in [Google App Engine](http://en.wikipedia.org/wiki/Google_App_Engine). I am using the Django template.
First, in my **base** HTML file, I can't load my downloaded jQuery code from local say, `d:/jquery.js`, like
```
<script src="d:\jquery.js" type="text/javascript" ></script></he... | AppEngine doesn't know anything about paths on your local system; it will only upload files that you configure it to. Do this by having a line like this in your app.yaml file:
```
handlers:
- url: /js
static_dir: js
```
In this case, `/js` represents a subdirectory of your main project directory, and you can put al... |
Plot smooth line with PyPlot | 5,283,649 | 35 | 2011-03-12T16:06:38Z | 5,284,038 | 42 | 2011-03-12T17:09:24Z | [
"python",
"plot",
"matplotlib",
"curvesmoothing"
] | I've got the following simple script that plots a graph:
```
import matplotlib.pyplot as plt
import numpy as np
T = np.array([6, 7, 8, 9, 10, 11, 12])
power = np.array([1.53E+03, 5.92E+02, 2.04E+02, 7.24E+01, 2.72E+01, 1.10E+01, 4.70E+00])
plt.plot(T,power)
plt.show()
```
As it is now, the line goes straight from p... | You could use `scipy.interpolate.spline` to smooth out your data yourself:
```
from scipy.interpolate import spline
xnew = np.linspace(T.min(),T.max(),300)
power_smooth = spline(T,power,xnew)
plt.plot(xnew,power_smooth)
plt.show()
``` |
Python: Sort list with parallel list | 5,284,183 | 6 | 2011-03-12T17:34:00Z | 5,284,207 | 7 | 2011-03-12T17:37:33Z | [
"python",
"list",
"sorting"
] | I have a list that is filled with HTML elements. I also have a list filled with date/times, which is parallel to the HTML list.
How can I sort the HTML list based on the time/date list? The time/date is in a timestamp format. | Zip the two lists up into tuples, sort, then take the HTML back out of the tuple:
```
zipped = zip(timestamps, htmls)
zipped.sort()
sorted_htmls = [html for (timestamp, html) in zipped]
``` |
Python: Sort list with parallel list | 5,284,183 | 6 | 2011-03-12T17:34:00Z | 5,284,222 | 12 | 2011-03-12T17:39:56Z | [
"python",
"list",
"sorting"
] | I have a list that is filled with HTML elements. I also have a list filled with date/times, which is parallel to the HTML list.
How can I sort the HTML list based on the time/date list? The time/date is in a timestamp format. | You can use [`zip`](http://docs.python.org/library/functions.html#zip).
```
timestamps, elements = zip(*sorted(zip(timestamps, elements)))
```
The result will be two tuples which you can convert to lists if you prefer. |
Python: How to install mysqldb on windows 7 x64? | 5,284,186 | 17 | 2011-03-12T17:34:23Z | 5,284,238 | 34 | 2011-03-12T17:43:39Z | [
"python",
"mysql",
"windows-7",
"64bit"
] | Im trying install **Mysql-python** on **windows x64**.
I installed **python x64**, **setuptools** (checked on the **leaf** lib, successfully installed) but i can't install **mysqldb**.
I trying to execute
> C:\Users\Fedcomp\Desktop\leaf-0.4\MySQL-python-1.2.3>python
> setup.py install
but catch this
```
In file inc... | You can find binary installers [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python) (Python 2.6-3.2), [here](http://www.codegood.com/archives/129) (2.7) or [here](http://www.codegood.com/archives/4) (2.6). Note that you don't have to use 64bit Python on Windows x64. You can just as well use a 32bit build of ... |
Rank items in an array using Python/NumPy | 5,284,646 | 31 | 2011-03-12T18:52:11Z | 5,284,703 | 22 | 2011-03-12T19:01:59Z | [
"python",
"sorting",
"numpy"
] | I have an array of numbers and I'd like to create another array that represents the rank of each item in the first array. I'm using Python and NumPy.
For example:
```
array = [4,2,7,1]
ranks = [2,1,3,0]
```
Here's the best method I've come up with:
```
array = numpy.array([4,2,7,1])
temp = array.argsort()
ranks = n... | Use slicing on the left-hand side in the last step:
```
array = numpy.array([4,2,7,1])
temp = array.argsort()
ranks = numpy.empty(len(array), int)
ranks[temp] = numpy.arange(len(array))
``` |
Rank items in an array using Python/NumPy | 5,284,646 | 31 | 2011-03-12T18:52:11Z | 6,266,510 | 38 | 2011-06-07T14:12:20Z | [
"python",
"sorting",
"numpy"
] | I have an array of numbers and I'd like to create another array that represents the rank of each item in the first array. I'm using Python and NumPy.
For example:
```
array = [4,2,7,1]
ranks = [2,1,3,0]
```
Here's the best method I've come up with:
```
array = numpy.array([4,2,7,1])
temp = array.argsort()
ranks = n... | Use argsort twice, first to obtain the order of the array, then to obtain ranking:
```
array = numpy.array([4,2,7,1])
order = array.argsort()
ranks = order.argsort()
```
When dealing with 2D (or higher dimensional) arrays, be sure to pass an axis argument to argsort to order over the correct axis. |
Rank items in an array using Python/NumPy | 5,284,646 | 31 | 2011-03-12T18:52:11Z | 29,059,978 | 23 | 2015-03-15T11:15:06Z | [
"python",
"sorting",
"numpy"
] | I have an array of numbers and I'd like to create another array that represents the rank of each item in the first array. I'm using Python and NumPy.
For example:
```
array = [4,2,7,1]
ranks = [2,1,3,0]
```
Here's the best method I've come up with:
```
array = numpy.array([4,2,7,1])
temp = array.argsort()
ranks = n... | This question is a few years old, and the accepted answer is great, but I think the following is still worth mentioning. If you don't mind the dependency on `scipy`, you can use [`scipy.stats.rankdata`](http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.rankdata.html):
```
In [22]: from scipy.stats import... |
Beginner friendly, PHP or Django? | 5,285,035 | 16 | 2011-03-12T19:51:05Z | 5,285,075 | 35 | 2011-03-12T19:56:19Z | [
"php",
"python",
"mysql",
"django",
"frameworks"
] | I'm interested in creating some web applications for various projects. I've done some basic scripting in Python, and in the past utilized some PHP scripts.
I don't have an strong background with programming. I mostly code interfaces with xHTML/CSS that support jQuery.
So I was told Django is pretty good, same goes to... | With no programming background, I think django will be extremely easy to pick up because there is one specific way to do things, and because the documentation is simply **amazing**. Unreal. Time bendingly good.
You don't need to know *any* python in my experience to comprehend the docs. It wraps up how to get from sta... |
List Python Operation | 5,285,053 | 4 | 2011-03-12T19:54:57Z | 5,285,068 | 8 | 2011-03-12T19:56:02Z | [
"python",
"list"
] | I got this list:
```
input = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
```
I want to make new lists with each index item:
i.e.
```
output = [[1,5,9],[2,6,10],[3,7,11],[4,8,12]]
``` | This is a canonical example of when to use [zip](http://docs.python.org/library/functions.html#zip):
```
In [6]: inlist = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
In [7]: out=zip(*inlist)
In [8]: out
Out[8]: [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
```
Or, to get a list of lists (rather than list of tuples):
```
... |
Adding data to a nested list in Python | 5,285,521 | 4 | 2011-03-12T21:11:49Z | 5,285,528 | 7 | 2011-03-12T21:12:59Z | [
"python",
"nested-lists"
] | I have a nested list e.g.:
```
nlist = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
]
```
Before I insert this list into a database, I would like to add a "column" to it with the same value in each row of the new column e.g:
```
nlist = [
[a, 1, 2, 3],
[a, 4, 5, 6]... | Why not change the original list (if that is all you want to do):
```
for row in nlist:
row.insert(0, a)
``` |
Determining what version of Flask is installed | 5,285,858 | 19 | 2011-03-12T22:14:35Z | 5,286,788 | 38 | 2011-03-13T01:19:11Z | [
"python",
"flask"
] | What's the easiest way to determine which version of [Flask](http://flask.pocoo.org/) is installed? | As of flask 0.7 (June 28th, 2011), a `__version__` attribute can be found on the flask module.
```
>> import flask
>> flask.__version__
```
Keep in mind that because prior to flask 0.7 there was no `__version__` attribute, the preceding code will result in an attribute error on those older versions.
For versions old... |
Determining what version of Flask is installed | 5,285,858 | 19 | 2011-03-12T22:14:35Z | 7,455,296 | 13 | 2011-09-17T13:59:17Z | [
"python",
"flask"
] | What's the easiest way to determine which version of [Flask](http://flask.pocoo.org/) is installed? | Via the python interpreter.
```
>> import flask
>> flask.__version__
'0.7.2'
```
If flask was installed via pip or easy\_install, you can always use the 'pip freeze' command. |
64-bit python 2.5/2.6+windows 7 "import socket" DLL load error | 5,286,014 | 3 | 2011-03-12T22:43:29Z | 5,286,203 | 7 | 2011-03-12T23:09:58Z | [
"python",
"windows",
"windows-7",
"64bit",
"32bit-64bit"
] | I installed latest 64-bit Python 2.5. I run the shell, and try to `import socket`, and get:
```
>>> import socket
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "c:\python25\lib\socket.py", line 45, in <module>
import _socket
ImportError: DLL load failed with error code 193
```
I ... | These two errors are the same error, code 193, reported two different ways. It is caused because your 64 bit Python is trying to load a 32 bit DLL.
It's hard to say exactly why this has happened. Perhaps you installed some 32 bit Python modules by mistake. Perhaps there is some confusion in paths.
However, often the ... |
Python string replace in a file without touching the file if no substitution was made | 5,286,020 | 4 | 2011-03-12T22:43:52Z | 5,286,152 | 12 | 2011-03-12T23:01:19Z | [
"python",
"file-io",
"replace"
] | What does Python's string.replace return if no string substitution was made?
Does Python's file.open(f, 'w') always touch the file even if no changes were made?
Using Python, I'm trying to replace occurrences of 'oldtext' with 'newtext' in a set of files. If a file contains 'oldtext', I want to do the replacement and ... | > What does Python's string.replace
> return if no string substitution was
> made?
It returns the original string.
> Does Python's file.open(f, 'w') always
> touch the file even if no changes were
> made?
More than merely touching the file, it destroys any content `f` used to contain.
So, you can test if the file n... |
Display Listbox with columns using Tkinter? | 5,286,093 | 9 | 2011-03-12T22:52:32Z | 5,287,037 | 7 | 2011-03-13T03:40:57Z | [
"python",
"listbox",
"tkinter"
] | I'm trying to create a `Listbox` in Tkinter that has columns.
I'm returning from a DB query records and would like to display each entry in it's own column for each record.
Looking at `Listbox`, I feel like there should be this functionality there but can't find it. What widget should I be using to do this? I've been... | Using [TkTreectrl](http://sourceforge.net/projects/tkintertreectrl/files/):
```
import Tkinter as tk
import TkTreectrl as treectrl
import sqlite3
def setup_table(connection):
cursor=connection.cursor()
cursor.execute('''CREATE TABLE foo
(id INTEGER PRIMARY KEY AUTOINCREMENT,
... |
Display Listbox with columns using Tkinter? | 5,286,093 | 9 | 2011-03-12T22:52:32Z | 24,132,955 | 7 | 2014-06-10T04:37:19Z | [
"python",
"listbox",
"tkinter"
] | I'm trying to create a `Listbox` in Tkinter that has columns.
I'm returning from a DB query records and would like to display each entry in it's own column for each record.
Looking at `Listbox`, I feel like there should be this functionality there but can't find it. What widget should I be using to do this? I've been... | You can use Ttk/Tkinker [`Treeview`](http://www.tkdocs.com/tutorial/tree.html) widget, which is used to work with tabular data.
The following is an [example](http://www.daniweb.com/software-development/python/threads/350266/creating-table-in-python) of a class that uses a `Treeview` widget to display a multi-column li... |
Read lists and dicts from file without exec | 5,286,128 | 2 | 2011-03-12T22:57:26Z | 5,286,136 | 7 | 2011-03-12T22:58:46Z | [
"python",
"io",
"exec",
"unsafe"
] | Currently I have this code, which reads from a file containing something similar to `[{'1': {'Score': '2', 'Class': '3'}}]` and assigns it to a variable:
```
exec('assigns = ' + open(r'D:\Dropbox\Dev\Output\dict', 'r').read())
```
However, I have been told that using `exec` is dangerous. How can I write the same code... | Use [`ast.literal_eval()`](http://docs.python.org/library/ast.html#ast.literal_eval):
```
assigns = ast.literal_eval(open(r'D:\Dropbox\Dev\Output\dict', 'r').read())
```
It will only evaluate literals, no function calls or operators. |
mocking functions using python mock | 5,286,390 | 31 | 2011-03-12T23:43:12Z | 5,287,267 | 8 | 2011-03-13T03:49:03Z | [
"python",
"unit-testing",
"mocking"
] | I am trying to Mock a function (that returns some external content) using the python mock module (http://www.voidspace.org.uk/python/mock/index.html).
I'm having some trouble mocking functions that are imported into a module.
For example, in util.py I have
```
def get_content():
return "stuff"
```
I want to mock ... | Let's assume you're creating your mock inside module `foobar`:
```
import util, mock
util.get_content = mock.Mock(return_value="mocked stuff")
```
If you import `mymodule` and call `util.get_content` without first importing `foobar`, your mock will not be installed:
```
import util
def func()
print util.get_cont... |
mocking functions using python mock | 5,286,390 | 31 | 2011-03-12T23:43:12Z | 5,295,212 | 20 | 2011-03-14T05:51:34Z | [
"python",
"unit-testing",
"mocking"
] | I am trying to Mock a function (that returns some external content) using the python mock module (http://www.voidspace.org.uk/python/mock/index.html).
I'm having some trouble mocking functions that are imported into a module.
For example, in util.py I have
```
def get_content():
return "stuff"
```
I want to mock ... | I think I have a workaround, though I'm still not quite clear on how to solve the general case
In mymodule, if I replace
```
from util import get_content
class MyObj:
def func():
get_content()
```
with
```
import util
class MyObj:
def func():
util.get_content()
```
The Mock seems ... |
mocking functions using python mock | 5,286,390 | 31 | 2011-03-12T23:43:12Z | 16,693,949 | 12 | 2013-05-22T14:07:01Z | [
"python",
"unit-testing",
"mocking"
] | I am trying to Mock a function (that returns some external content) using the python mock module (http://www.voidspace.org.uk/python/mock/index.html).
I'm having some trouble mocking functions that are imported into a module.
For example, in util.py I have
```
def get_content():
return "stuff"
```
I want to mock ... | You have to patch the function where it is being used. In your case that would be in the mymodule module.
```
import mymodule
>>> mymodule.get_content = Mock(return_value="mocked stuff")
>>> m = mymodule.MyObj()
>>> m.func()
"mocked stuff"
```
There is a reference in the docs here: <http://docs.python.org/dev/library... |
How can I flatten lists without splitting strings? | 5,286,541 | 9 | 2011-03-13T00:15:26Z | 5,286,571 | 14 | 2011-03-13T00:24:06Z | [
"python"
] | I'd like to flatten lists that may contain other lists *without* breaking strings apart. For example:
```
In [39]: list( itertools.chain(*["cat", ["dog","bird"]]) )
Out[39]: ['c', 'a', 't', 'dog', 'bird']
```
and I would like
```
['cat', 'dog', 'bird']
``` | ```
def flatten(foo):
for x in foo:
if hasattr(x, '__iter__'):
for y in flatten(x):
yield y
else:
yield x
```
(Strings conveniently do not actually have an `__iter__` attribute, unlike pretty much every other iterable object in Python. Note however that this ... |
How do I serve image Content-types with Python BaseHTTPServerRequestHandler do_GET method? | 5,287,219 | 4 | 2011-03-13T03:32:31Z | 5,287,450 | 7 | 2011-03-13T04:34:50Z | [
"python",
"basehttpserver"
] | I'm using BaseHTTPServer to serve web content. I can serve Content-types 'text/html' or 'text/css' or even 'text/js' and it renders on the browser side. But when I try to
`self.send_header('Content-type', 'image/png')`
for a .png file, it doesn't render at all.
Here is a sample:
```
if self.path... | You've opened the file in text mode instead of binary mode. Any newline characters are likely to get messed up. Use this instead:
```
f = open(curdir + sep + self.path, 'rb')
``` |
Is it possible to decompile a compiled .pyc file into a .py file? | 5,287,253 | 62 | 2011-03-13T03:43:47Z | 5,704,079 | 27 | 2011-04-18T14:07:44Z | [
"python",
"decompiling",
"assembly",
"compiled"
] | Is it possible to get some information out of the .pyc file that is generated from a .py file? | Yes, you can get it with `unpyclib` that can be found on *pypi*.
```
$ pip install unpyclib
```
Than you can decompile your .pyc file
```
$ python -m unpyclib.application -Dq path/to/file.pyc
``` |
Is it possible to decompile a compiled .pyc file into a .py file? | 5,287,253 | 62 | 2011-03-13T03:43:47Z | 14,808,336 | 57 | 2013-02-11T08:27:27Z | [
"python",
"decompiling",
"assembly",
"compiled"
] | Is it possible to get some information out of the .pyc file that is generated from a .py file? | [Uncompyle2](https://github.com/wibiti/uncompyle2) worked well for me with Python 2.7 to decompile the .pyc bytecode into .py, whereas unpyclib crashed with an exception.
See [this answer on uncompyle2](http://stackoverflow.com/a/7474393/992887) for some other comments. |
Is it possible to decompile a compiled .pyc file into a .py file? | 5,287,253 | 62 | 2011-03-13T03:43:47Z | 15,648,227 | 11 | 2013-03-26T22:02:30Z | [
"python",
"decompiling",
"assembly",
"compiled"
] | Is it possible to get some information out of the .pyc file that is generated from a .py file? | Decompyle++ (pycdc) was the only one that worked for me: <https://github.com/zrax/pycdc>
was suggested in [Decompile Python 2.7 .pyc](http://stackoverflow.com/questions/8189352/decompile-python-2-7-pyc/10047631#10047631) |
Is it possible to decompile a compiled .pyc file into a .py file? | 5,287,253 | 62 | 2011-03-13T03:43:47Z | 21,916,676 | 15 | 2014-02-20T18:39:42Z | [
"python",
"decompiling",
"assembly",
"compiled"
] | Is it possible to get some information out of the .pyc file that is generated from a .py file? | You may try ***[Easy Python Decompiler](http://sourceforge.net/projects/easypythondecompiler/)***. It's based on Decompyle++ and Uncompyle2.
It's supports decompiling python versions 1.0-3.3
Note: I am the author of the above tool. |
How to stay tab-free in Geany on Ubuntu? | 5,287,849 | 24 | 2011-03-13T06:17:36Z | 5,287,910 | 29 | 2011-03-13T06:39:33Z | [
"python",
"ubuntu",
"editor",
"geany"
] | How to stay tab free in Geany on Ubuntu?
When I am coding in python, tabs have always annoyed me. And the TAB is invisible. So strange.
When I open my code by gEdit, those TAB are visible. | You are looking for 'soft tabs'
<http://www.geany.org/manual/dev/index.html#editor-indentation-preferences>
preferences > editor > indentation > type > spaces |
How to stay tab-free in Geany on Ubuntu? | 5,287,849 | 24 | 2011-03-13T06:17:36Z | 13,761,962 | 29 | 2012-12-07T11:13:03Z | [
"python",
"ubuntu",
"editor",
"geany"
] | How to stay tab free in Geany on Ubuntu?
When I am coding in python, tabs have always annoyed me. And the TAB is invisible. So strange.
When I open my code by gEdit, those TAB are visible. | DTing is right but on thing to remember:
You have to close all files (tabs) in Geany and open them up again to have the new settings work in each file. It took me days to figure out that I not only have to close geany and open it up again but that I also have to re-open each file seperately. |
Adding a field to a structured numpy array (2) | 5,288,736 | 10 | 2011-03-13T10:16:52Z | 5,288,878 | 10 | 2011-03-13T10:45:18Z | [
"python",
"numpy",
"recarray"
] | I know there was already a question about this topic (cleanest way to add a field to a structured numpy array), see
[Adding a field to a structured numpy array](http://stackoverflow.com/questions/1201817/adding-a-field-to-a-structured-numpy-array)
but I have a question about the answer given there ...
> If you're us... | <http://projects.scipy.org/numpy/browser/branches/1.3.x/numpy/lib/recfunctions.py?rev=8229>
did you import?
```
from numpy.lib import recfunctions
recfunctions.append_field(*your_args)
```
Seems like everything is working:
```
Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
[GCC 4.4.5] on linux2
Type "help", "co... |
In Python, what operator to override for "if object:"? | 5,288,990 | 14 | 2011-03-13T11:10:49Z | 5,288,992 | 20 | 2011-03-13T11:11:40Z | [
"python",
"object",
"operator-overloading"
] | I find it very handy to check if an object is "empty" with the following construct:
```
l=[]
if l:
do_stuff()
```
For a standard python list, the `if` will be executed only if the list is not empty.
My question is, how can I implement the same idea for my own objects? | Define a method `__bool__` (Python 3.x) or `__nonzero__` (2.x). Or define both for portability, with one returning the result of the other. |
In Python, what operator to override for "if object:"? | 5,288,990 | 14 | 2011-03-13T11:10:49Z | 5,289,000 | 16 | 2011-03-13T11:12:55Z | [
"python",
"object",
"operator-overloading"
] | I find it very handy to check if an object is "empty" with the following construct:
```
l=[]
if l:
do_stuff()
```
For a standard python list, the `if` will be executed only if the list is not empty.
My question is, how can I implement the same idea for my own objects? | Implement [`__nonzero__`](http://docs.python.org/reference/datamodel.html#object.__nonzero__) for Python 2 and [`__bool__`](http://docs.python.org/py3k/reference/datamodel.html#object.__bool__) for Python 3:
```
class AlwaysTrueObject:
def __bool__(self):
return True
__nonzero__ = __bool__
``` |
In Python, what operator to override for "if object:"? | 5,288,990 | 14 | 2011-03-13T11:10:49Z | 5,289,320 | 7 | 2011-03-13T12:26:13Z | [
"python",
"object",
"operator-overloading"
] | I find it very handy to check if an object is "empty" with the following construct:
```
l=[]
if l:
do_stuff()
```
For a standard python list, the `if` will be executed only if the list is not empty.
My question is, how can I implement the same idea for my own objects? | If you implement `__len__` Python will do that for you under the assumption that a length of 0 means that the object has a boolean value of `False` and that it has a boolean value of `True` otherwise.
If it makes no sense to implement `__len__`, you can implement `__nonzero__` (or `__bool__` in 3.x (only the name has ... |
How to change tag name with BeautifulSoup? | 5,289,189 | 7 | 2011-03-13T11:53:54Z | 5,289,523 | 11 | 2011-03-13T13:03:24Z | [
"python",
"html-parsing",
"beautifulsoup"
] | I am using python + BeautifulSoup to parse an HTML document.
Now I need to replace all `<h2 class="someclass">` elements in an HTML document, with `<h1 class="someclass">`.
How can I change the tag name, without changing anything else in the document? | I don't know how you're accessing `tag` but the following works for me:
```
import BeautifulSoup
if __name__ == "__main__":
data = """
<html>
<h2 class='someclass'>some title</h2>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
<li>Vesti... |
Object has no attribute _state | 5,290,001 | 8 | 2011-03-13T14:29:15Z | 5,290,131 | 12 | 2011-03-13T14:54:42Z | [
"python",
"django"
] | I'm developing Django application, and I have following error
```
'Sheep' object has no attribute _state
```
My models are constructed like this
```
class Animal(models.Model):
aul = models.ForeignKey(Aul)
weight = models.IntegerField()
quality = models.IntegerField()
age = models.IntegerField()
... | firstly, you must be very careful overriding `__init__` to have non-optional arguments. remember it will be called every time you get an object from a queryset!
this is the correct code you want:
```
class Animal(models.Model):
#class Meta: #uncomment this for an abstract class
# abstract = True
... |
App Engine, appcfg and saving uploading credentials | 5,292,103 | 5 | 2011-03-13T20:21:06Z | 13,423,450 | 9 | 2012-11-16T19:51:37Z | [
"python",
"google-app-engine"
] | On Linux, it seems that appcfg.py saves credentials when I use it to upload a new version of my application. However, this doesn't seem to happen OSX, and the password is asked every time.
On Linux, I have local installation. On OSX, I have used binary installer.
Is it possible to do something for OSX, so that it wou... | You can use the OAuth 2.0 feature of `appcfg` to avoid the need to enter your login and password. It is documented for [Java](https://developers.google.com/appengine/docs/java/tools/uploadinganapp#Passwordless_Login_with_OAuth2), [Python](https://developers.google.com/appengine/docs/python/tools/uploadinganapp#oauth) a... |
hash unicode string in python | 5,292,273 | 32 | 2011-03-13T20:46:43Z | 5,292,360 | 66 | 2011-03-13T21:02:23Z | [
"python",
"unicode",
"utf-8"
] | I try to hash some unicode strings:
```
hashlib.sha1(s).hexdigest()
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-81:
ordinal not in range(128)
```
where `s` is something like:
> Åâ¡â¢Â£Â¢â§¶â¢ÂªÂºââ Å⴮⠥¨ËøÏââÃ¥ÃâÆÂ©Ëâˬâ¦Ã¦Î©âçââ«Ëµâ¤â¥Ã... | Apparently `hashlib.sha1` isn't expecting a `unicode` object, but rather a sequence of bytes in a `str` object. Encoding your `unicode` string to a sequence of bytes (using, say, the UTF-8 encoding) should fix it:
```
>>> import hashlib
>>> s = u'é'
>>> hashlib.sha1(s.encode('utf-8'))
<sha1 HASH object @ 029576A0>
``... |
python tuple comparison | 5,292,303 | 66 | 2011-03-13T20:52:29Z | 5,292,330 | 14 | 2011-03-13T20:57:51Z | [
"python",
"comparison",
"tuples"
] | I have been reading the Core Python programming book and the author shows an example like:
```
(4,5) < (3,5) # Equals false
```
So I'm wondering, how/why does it equal false? How does python compare these two tuples?
Btw, it's not explained in the book. | The [Python documentation](https://docs.python.org/2/reference/expressions.html#not-in) does explain it.
> Tuples and lists are compared
> lexicographically using comparison of
> corresponding elements. This means
> that to compare equal, each element
> must compare equal and the two
> sequences must be of the same ty... |
python tuple comparison | 5,292,303 | 66 | 2011-03-13T20:52:29Z | 5,292,332 | 86 | 2011-03-13T20:58:27Z | [
"python",
"comparison",
"tuples"
] | I have been reading the Core Python programming book and the author shows an example like:
```
(4,5) < (3,5) # Equals false
```
So I'm wondering, how/why does it equal false? How does python compare these two tuples?
Btw, it's not explained in the book. | Tuples are compared position by position:
the first item of first tuple is compared to the first item of the second tuple; if they are not equal, this is the result of the comparison, else the second item is considered, then the third and so on.
See [doc](http://docs.python.org/library/stdtypes.html#sequence-types-str... |
Fast or Bulk Upsert in pymongo | 5,292,370 | 18 | 2011-03-13T21:04:24Z | 22,623,104 | 20 | 2014-03-25T00:11:09Z | [
"python",
"mongodb",
"nosql",
"pymongo",
"upsert"
] | How can I do a bulk upsert in pymongo? I want to Update a bunch of entries and doing them one at a time is very slow.
The answer to an almost identical question is here: [Bulk update/upsert in MongoDB?](http://stackoverflow.com/questions/4444023/bulk-update-upsert-in-mongodb)
The accepted answer doesn't actually answ... | MongoDB 2.6+ has support for bulk operations. This includes bulk inserts, upserts, updates, etc. The point of this is to reduce/eliminate delays from the round-trip latency of doing record-by-record operations ('document by document' to be correct).
So, how does this work? Example in Python, because that's what I'm wo... |
Algorithm to determine the winner of a Texas Hold'em Hand | 5,293,405 | 7 | 2011-03-14T00:03:11Z | 5,293,476 | 7 | 2011-03-14T00:17:56Z | [
"python",
"artificial-intelligence",
"poker"
] | Ok, so I am making a Texas Hold'em AI for my senior project. I've created the gui and betting/dealing procedures, but I have reached the part where I need to determine who won the hand, and I do not know the best way to approach this. I am using python btw. ATM i have 2 lists, one for the 7 player cards, one for the 7 ... | <http://www.codingthewheel.com/archives/poker-hand-evaluator-roundup>
Best algorithm you will get is 7 looks in lookup table of size 100 MB (if I remember correctly) |
Ways to manage DB migrations with SQLAlchemy? | 5,293,669 | 13 | 2011-03-14T00:54:22Z | 8,094,243 | 13 | 2011-11-11T12:52:02Z | [
"python",
"sqlalchemy",
"database-migration"
] | I've looked at sqlalchemy-migrate, but it just seems like a lot of work and I haven't been able to find any useful examples.
Anyone care to share how they handle this? | Check out new project Alembic: <http://readthedocs.org/docs/alembic/en/latest/index.html> |
Creating a salt in python | 5,293,959 | 21 | 2011-03-14T01:52:08Z | 5,293,983 | 26 | 2011-03-14T01:57:17Z | [
"python",
"salt",
"base62"
] | How would I create a random, 16-character base-62 salt in python? I need it for a protocol and I'm not sure where to start. Thanks. | ```
>>> import random
>>> ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
>>> chars=[]
>>> for i in range(16):
chars.append(random.choice(ALPHABET))
>>> "".join(chars)
'wE9mg9pu2KSmp5lh'
```
This should work. |
Creating a salt in python | 5,293,959 | 21 | 2011-03-14T01:52:08Z | 10,445,962 | 21 | 2012-05-04T09:11:51Z | [
"python",
"salt",
"base62"
] | How would I create a random, 16-character base-62 salt in python? I need it for a protocol and I'm not sure where to start. Thanks. | You shouldn't use UUIDs, they are unique, not random: [Is using a CreateUUID() function as salt a good idea?](http://stackoverflow.com/q/3596598/1224926)
Your salts should use a cryptographically secure random numbers, in python 2.4+, os.urandom is the source of these (if you have a good timing source).
```
# for som... |
Restart logging to a new file (Python) | 5,296,130 | 16 | 2011-03-14T08:07:58Z | 5,296,208 | 23 | 2011-03-14T08:19:53Z | [
"python",
"logging",
"rotation"
] | I'm using the following code to initialize logging in my application:
```
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# log to a file
directory = '/reserved/DYPE/logfiles'
now = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = os.path.join(directory, 'dype_%s.log' % now)
file_handler = logging.File... | You can manually re-assign the handler if you want using the `removeHandler` and `addHandler` OR, you can access `logger.handlers[index_of_handler_here].stream` and replace the stream manually, but I'd recommend the former over the latter.
```
logger.handlers[0].stream.close()
logger.removeHandler(logger.handlers[0])
... |
What will happen if I modify a Python script while it's running? | 5,296,977 | 69 | 2011-03-14T09:47:05Z | 5,296,992 | 78 | 2011-03-14T09:48:19Z | [
"python"
] | Imagine a python script that will take long time to run, and what will happen if I modify it while it's running? Will the result be different? | Nothing, because python precompiles you script into PYC file and launches from it.
Only if some kind of exception occurs- you may get wrong explanation, because in line **X** may be different code that it was before starting script |
How to get MD5 sum of a string? | 5,297,448 | 106 | 2011-03-14T10:38:56Z | 5,297,483 | 239 | 2011-03-14T10:42:23Z | [
"python",
"md5",
"flickr-api"
] | In the [Flickr API docs](http://www.flickr.com/services/api/auth.howto.web.html), you need to find the MD5 sum of a string to generate the `[api_sig]` value.
How does one go about generating an MD5 sum from a string?
Flickr's example:
string: `000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite`
MD5 s... | You can do the following:
**Python 2.x**
```
import hashlib
print hashlib.md5("whatever your string is").hexdigest()
```
---
**Python 3.x**
```
import hashlib
print(hashlib.md5("whatever your string is".encode('utf-8')).hexdigest())
```
---
However in this case you're probably better off using this helpful Pytho... |
How to get MD5 sum of a string? | 5,297,448 | 106 | 2011-03-14T10:38:56Z | 5,297,495 | 123 | 2011-03-14T10:43:21Z | [
"python",
"md5",
"flickr-api"
] | In the [Flickr API docs](http://www.flickr.com/services/api/auth.howto.web.html), you need to find the MD5 sum of a string to generate the `[api_sig]` value.
How does one go about generating an MD5 sum from a string?
Flickr's example:
string: `000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite`
MD5 s... | Use pythons [hashlib](http://docs.python.org/library/hashlib.html#module-hashlib)
```
import hashlib
m = hashlib.md5()
m.update("000005fab4534d05api_key9a0554259914a86fb9e7eb014e4e5d52permswrite")
print m.hexdigest()
```
Output: `a02506b31c1cd46c2e0b6380fb94eb3d` |
python: how to interrupt a regex match | 5,298,033 | 7 | 2011-03-14T11:37:59Z | 5,299,719 | 7 | 2011-03-14T14:10:15Z | [
"python",
"regex",
"multithreading",
"timeout",
"signals"
] | I iterate over the lines in a large number of downloaded text files and do a regex match on each line. Usually, the match takes less than a second. However, at times a match takes several minutes, sometimes the match does not finish at all and the code just hangs (waited an hour a couple of times, then gave up). Theref... | You are running into catastrophic backtracking; not because of nested quantifiers but because your quantified characters also can match the separators, and since there are a lot of them, you'll get exponential time in certain cases.
Aside from the fact that it looks more like a job for a CSV parser, try the following:... |
Python zipfile module: difference between zipfile.ZIP_DEFLATED and zipfile.ZIP_STORED | 5,298,169 | 6 | 2011-03-14T11:51:47Z | 5,298,221 | 10 | 2011-03-14T11:57:07Z | [
"python",
"zipfile"
] | I have difficult to understand the difference between zipfile.ZIP\_DEFLATED and zipfile.ZIP\_STORED compression modes of the zipfile module.
Someone could help me?
thanks,
Max | `ZIP_DEFLATED` correspond to an archive member (a file inside the archive) which is compressed (or deflated). `ZIP_STORED` correspond to an archive member which is simply stored, without being compressed, quite the same as an archive member inside a `tar` file. |
Detecting if an email is a "Delivery Status Notification" and extract information - Python | 5,298,285 | 11 | 2011-03-14T12:03:19Z | 5,300,759 | 12 | 2011-03-14T15:32:38Z | [
"python",
"email"
] | I'm using the Python `email` module to parse emails.
I need to be able to tell if an email is a "Delivery Status Notification", find out what the status is, and extract information on the email that failed, eg. the Subject.
The object I get after parsing with .parsestr(email) is like this:
```
{'Content-Transfer-Enc... | [The docs you cited says](http://docs.python.org/library/email#differences-from-mimelib) that the message is multi-part if it is [DSN](http://tools.ietf.org/html/rfc1894.html):
```
import email
msg = email.message_from_string(emailstr)
if (msg.is_multipart() and len(msg.get_payload()) > 1 and
msg.get_payload(1)... |
Finding number of colored shapes from picture using Python | 5,298,884 | 11 | 2011-03-14T13:00:09Z | 5,304,140 | 11 | 2011-03-14T20:33:05Z | [
"python",
"image-processing"
] | My problem has to do with recognising colours from pictures. Doing microbiology I need to count the number of cell nuclei present on a picture taken with a microscope camera. I've used GIMP to tag the nuclei with dots of red colour. Now I'd need to make a script in python, which, given an image, would tell me how many ... | ### Count nuclei
The code adapted from [Python Image Tutorial](http://pythonvision.org/basic-tutorial). Input image with nuclei from the tutorial:

```
#!/usr/bin/env python
import scipy
from scipy import ndimage
# read image into numpy array
# $ wget http://pythonvision... |
Can't open file 'django-admin.py': [Errno 2] No such file or directory | 5,299,241 | 14 | 2011-03-14T13:32:42Z | 5,299,378 | 8 | 2011-03-14T13:44:09Z | [
"python",
"django",
"django-admin"
] | I'm using Python 2.7, Django 1.2.5 and on Windows 7.
I am not sure what I've done. I used to be able to create Django projects like
```
python django-admin.py startproject test
```
Now however I get this error.
> Can't open file 'django-admin.py':
> [Errno 2] No such file or directory
I can type the following w... | If `C:\Python27\Scripts` is in your Path, just type in:
```
django-admin.py startproject proj
```
There should be a file association with .py and try to execute. If you prefix with `python` the next command is a file path.
I've never been able to do `python django-admin.py` -- I get the same error you describe.
Mak... |
Can't open file 'django-admin.py': [Errno 2] No such file or directory | 5,299,241 | 14 | 2011-03-14T13:32:42Z | 8,601,853 | 13 | 2011-12-22T09:31:56Z | [
"python",
"django",
"django-admin"
] | I'm using Python 2.7, Django 1.2.5 and on Windows 7.
I am not sure what I've done. I used to be able to create Django projects like
```
python django-admin.py startproject test
```
Now however I get this error.
> Can't open file 'django-admin.py':
> [Errno 2] No such file or directory
I can type the following w... | I had this same problem with slightly newer versions of Python 2.7.x and Django - and it is not the PATH. This is all I had to do to fix it in Windows XP:
1. Find a .py file (any, even a blank).
2. Right click on it and choose: "Open with>" and then select "Choose program...".
3. This pops up a list of all programs - ... |
How to use list (or tuple) as String Formating value | 5,299,796 | 2 | 2011-03-14T14:16:05Z | 5,299,855 | 17 | 2011-03-14T14:20:19Z | [
"python",
"string"
] | Assume this variable:
```
s=['Python', 'rocks']
x = '%s %s' % (s[0], s[1])
```
Now I would like to substitute much longer list, and adding all list values separately, like s[0], s[1], ... s[n], does not seem right
Quote from documentation:
> Given format % values... If format
> requires a single argument, values ma... | You don't have to spell out all the indices:
```
s = ['language', 'Python', 'rocks']
some_text = "There is a %s called %s which %s."
x = some_text % tuple(s)
```
The number of items in s has to be the same as the number of insert points in the format string of course.
Since 2.6 you can also use the new `format` meth... |
Download several parts of one file concurrently with Python? | 5,299,968 | 7 | 2011-03-14T14:30:02Z | 5,301,147 | 12 | 2011-03-14T16:00:26Z | [
"python",
"download"
] | I know how to use `urllib` to download a file. However, it's much faster, if the server allows it, to download several part of the same file simultaneously and then merge them.
How do you do that in Python? If you can't do it easily with the standard lib, any lib that would let you do it? | Although I agree with Gregory's suggestion of using an existing library, it's worth noting that you can do this by using the `Range` HTTP header. If the server accepts byte-range requests, you can start several threads to download multiple parts of the file in parallel. This snippet, for example, will only download byt... |
Set a kind name independently of the model name (App Engine datastore) | 5,300,387 | 3 | 2011-03-14T15:02:09Z | 5,302,119 | 10 | 2011-03-14T17:29:22Z | [
"python",
"google-app-engine",
"gae-datastore"
] | As a Python programmer, I like my code to be reusable, I'm trying to avoid kind name conflicts in my code (where two different models share the same kind name).
Currently I just prepend some meaningful text to the model's class name, but this is awfully unpythonic.
Being able to explicitly set the model's kind will s... | Just override the `kind()` method of your class:
```
class MyModel(db.Model):
@classmethod
def kind(cls):
return 'prefix_%s' % super(MyModel, cls).kind()
```
You can define a custom baseclass that does this for you:
```
class ModuleModel(db.Model):
@classmethod
def kind(cls):
return '%s_%s' % (cls.__... |
learn python the hard way exercise 35 help | 5,300,506 | 2 | 2011-03-14T15:12:42Z | 5,300,615 | 8 | 2011-03-14T15:20:50Z | [
"python"
] | for some reason when the game reaches gold room it doesn't work right. when i enter any number i get the death message 'man, learn to type a number'
thanks
```
from sys import exit
def gold_room():
print 'this room is full of gold, how much do you take?'
next = raw_input('> ')
if '0' in next or '1' in n... | You do this in `gold_room`:
```
next = raw_input('> ')
if '0' in next or '1' in next:
how_much = int(next)
else:
dead('man, learn how to type a number')
```
it checks only if `'0' in next or '1' in next`, so it's not really surprising that '2' does not work, right?
What you want goes along these lines
```
n... |
Python __iter__ and for loops | 5,300,988 | 3 | 2011-03-14T15:49:14Z | 5,301,235 | 12 | 2011-03-14T16:08:33Z | [
"python",
"for-loop",
"iterable"
] | As I understand it, I can use the `for` loop construction on an object with a `__iter__` method that returns an iterator. I have an object for which I implement the following `__getattribute__` method:
```
def __getattribute__(self,name):
if name in ["read","readlines","readline","seek","__iter__","closed","fileno... | There's a subtle implementation detail getting in your way: `__iter__` isn't actually an instance method, but a class method. That is, `obj.__class__.__iter__(obj)` is called, rather than `obj.__iter__()`.
This is due to slots optimizations under the hood, allowing the Python runtime to set up iterators faster. This i... |
Problem while trying to create python generator | 5,301,614 | 2 | 2011-03-14T16:44:47Z | 5,301,660 | 8 | 2011-03-14T16:48:43Z | [
"python",
"generator"
] | I am trying to learn how to use generators, so I wrote this one, but it just prints the same value all the time. Why?
I want it to generate values from 999 down to 100.
```
>>> def gen_a():
a=999
while a>99:
yield a
a-=1
>>> gen_a().next()
999
>>> gen_a().next()
999
>>> gen_a... | Because you are generating the generator over and over.
Try:
```
f = gen_a()
f.next()
f.next()
``` |
How to do many-to-many Django query to find book with 2 given authors? | 5,301,996 | 11 | 2011-03-14T17:16:16Z | 5,302,110 | 30 | 2011-03-14T17:28:04Z | [
"python",
"django",
"many-to-many",
"django-queryset"
] | I have a query that requires to filter exactly 2 authors with the ID
Theoretically,
```
Book.objects.filter(author__id=1, author__id=2).
```
which is not possible.
How can I solve this problem?
Cheers,
Mickey | Not intuitive at first but the answer is right in front of us.
```
Book.objects.filter(author__id=1).filter(author__id=2)
```
If you want an exact match, you could potentially further filter this result by those items that only have exactly 2 authors.
```
Book.objects.annotate(count=Count('author')).filter(author__i... |
Packing 4 Integers as ONE BYTE? | 5,302,374 | 15 | 2011-03-14T17:53:49Z | 5,302,410 | 29 | 2011-03-14T17:56:20Z | [
"python",
"binary",
"struct"
] | I have four integers {`a`, `b`, `c`, `d`} that can have the following range of values:
`a` - {0 or 1} (1 bit)
`b` - {0 or 1} (1 bit)
`c` - {0, 1, 2, ..., 7} (3 bits)
`d` - {0, 1, 2, ..., 7} (3 bits)
at first, I would like to pack them into a one byte that can be then written to a binary file.
later, I would like t... | Use shift and bitwise OR, then convert to a character to get a "byte":
```
x = chr(a | (b << 1) | (c << 2) | (d << 5))
```
To unpack this byte again, first convert to an integer, then shift and use bitwise AND:
```
i = ord(x)
a = i & 1
b = (i >> 1) & 1
c = (i >> 2) & 7
d = (i >> 5) & 7
```
Explanation: Initially, y... |
Packing 4 Integers as ONE BYTE? | 5,302,374 | 15 | 2011-03-14T17:53:49Z | 5,302,474 | 8 | 2011-03-14T18:02:03Z | [
"python",
"binary",
"struct"
] | I have four integers {`a`, `b`, `c`, `d`} that can have the following range of values:
`a` - {0 or 1} (1 bit)
`b` - {0 or 1} (1 bit)
`c` - {0, 1, 2, ..., 7} (3 bits)
`d` - {0, 1, 2, ..., 7} (3 bits)
at first, I would like to pack them into a one byte that can be then written to a binary file.
later, I would like t... | ```
def encode(a, b, c, d):
return a | b << 1 | c << 2 | d << 5
def decode(x):
return x & 1, (x >> 1) & 1, (x >> 2) & 7, (x >> 5) & 7
``` |
How to use Twisted to get an IRC channel's user list | 5,305,050 | 5 | 2011-03-14T21:55:29Z | 5,306,497 | 7 | 2011-03-15T01:21:14Z | [
"python",
"twisted"
] | I'm trying to get channel's user list using `{{self.say(channel, "WHO",100)}}`. How can I get the response? Which method I should override? | Here are some additional methods which should help you get further along. You handle a given reply `RPL_NAME` by defining a method `irc_RPL_NAME`. So for `RPL_WHOREPLY` you define `irc_WHOREPLY`:
```
def who(self, channel):
"List the users in 'channel', usage: client.who('#testroom')"
self.sendLine... |
Get difference from two lists in Python | 5,305,164 | 3 | 2011-03-14T22:06:17Z | 5,305,214 | 7 | 2011-03-14T22:11:53Z | [
"python"
] | I have two lists, `l1` and `l2`. I need items from `l1` which are not in `l2`.
```
l1 = [2, 3, 4, 5]
l2 = [0, 1, 2, 3]
```
I want to get only [4,5] - only new values in l1.
```
[i for i in l1 if not i in l2 ]
```
Can I do that without iteration? | You can't do it without iteration. Even if you call a single method, internally that will iterate.
Your approach is fine for a small list, but you could use this approach instead for larger lists:
```
s2 = set(l2)
result = [i for i in l1 if not i in s2 ]
```
This will be fast and will also preserve the original orde... |
how to show Percentage in python | 5,306,756 | 52 | 2011-03-15T02:10:44Z | 5,306,787 | 84 | 2011-03-15T02:16:03Z | [
"python"
] | this is my code:
```
print str(float(1/3))+'%'
```
and it show :
```
0.0%
```
but i want get `33%`
what can i do. | [`format`](http://docs.python.org/library/functions.html#format) is a built-in since Python 2.6:
```
>>> print "{0:.0f}%".format(1./3 * 100)
33%
```
If you don't want integer division, you can import Python3's division from [`__future__`](http://docs.python.org/2/library/__future__.html):
```
>>> from __future__ imp... |
how to show Percentage in python | 5,306,756 | 52 | 2011-03-15T02:10:44Z | 5,306,788 | 27 | 2011-03-15T02:16:10Z | [
"python"
] | this is my code:
```
print str(float(1/3))+'%'
```
and it show :
```
0.0%
```
but i want get `33%`
what can i do. | You are dividing integers then converting to float. Divide by floats instead.
As a bonus, use the awesome string formatting methods described here: <http://docs.python.org/library/string.html#format-specification-mini-language>
To specify a percent conversion and precision.
```
>>> float(1) / float(3)
[Out] 0.333333... |
how to show Percentage in python | 5,306,756 | 52 | 2011-03-15T02:10:44Z | 18,251,214 | 18 | 2013-08-15T10:52:32Z | [
"python"
] | this is my code:
```
print str(float(1/3))+'%'
```
and it show :
```
0.0%
```
but i want get `33%`
what can i do. | Just for the sake of completeness, since I noticed no one suggested this simple approach:
```
>>> print "%.0f%%" % (100 * 1.0/3)
33%
```
Details:
* `%.0f` stands for "*print a float with 0 decimal places*", so `%.2f` would print `33.33`
* `%%` prints a literal `%`. A bit cleaner than your original `+'%'`
* `1.0` ins... |
how to show Percentage in python | 5,306,756 | 52 | 2011-03-15T02:10:44Z | 23,764,798 | 27 | 2014-05-20T16:00:46Z | [
"python"
] | this is my code:
```
print str(float(1/3))+'%'
```
and it show :
```
0.0%
```
but i want get `33%`
what can i do. | There is a way more convenient 'percent'-formatting option for the `.format()` format method:
```
>>> '{:.1%}'.format(1/3.0)
'33.3%'
``` |
How to send a POST request using django? | 5,308,060 | 15 | 2011-03-15T06:02:42Z | 5,308,914 | 23 | 2011-03-15T08:00:25Z | [
"python",
"django",
"urllib2"
] | I dont want to use `html` file, but only with django I have to make POST request.
Just like `urllib2` sends a `get` request. | A combination of methods from urllib2 and urllib will do the trick. Here is how I post data using the two:
```
post_data = [('name','Gladys'),] # a sequence of two element tuples
result = urllib2.urlopen('http://example.com', urllib.urlencode(post_data))
content = result.read()
```
[urlopen()](http://docs.python.... |
How to send a POST request using django? | 5,308,060 | 15 | 2011-03-15T06:02:42Z | 25,272,529 | 12 | 2014-08-12T19:28:22Z | [
"python",
"django",
"urllib2"
] | I dont want to use `html` file, but only with django I have to make POST request.
Just like `urllib2` sends a `get` request. | Here's how you'd write the accepted answer's example using `python-requests`:
```
post_data = {'name': 'Gladys'}
response = requests.post('http://example.com', data=post_data)
content = response.content
```
Much more intuitive. See the [Quickstart](http://docs.python-requests.org/en/latest/user/quickstart/) for more ... |
Python socket.accept nonblocking? | 5,308,080 | 12 | 2011-03-15T06:06:04Z | 5,308,168 | 22 | 2011-03-15T06:18:23Z | [
"python",
"sockets",
"tcp",
"nonblocking"
] | Is there a way I can use python's socket.accept() in a non-blocking way that simply runs it and lets me just check if it got any new connections? I *really* don't want to use threading.
Thanks. | You probably want something like `select.select()` (see [documentation](http://docs.python.org/library/select.html#select.select)). You supply `select()` with three lists of sockets: sockets you want to monitor for readability, writability, and error states. The server socket will be readable when a new client is waiti... |
writing double quotes in python | 5,308,097 | 7 | 2011-03-15T06:08:51Z | 5,308,117 | 10 | 2011-03-15T06:12:39Z | [
"python"
] | I would like to write the following in a text file in the following format:
The Name is from a list of names
Item "Name" RollNo
e.g
Item "Aaron" RollNo
Item "Barry" RollNo
I am writing
```
file.write("Item" + \" + Name[i] +\")
```
but getting error | With double-quote strings:
```
file.write("Item \"" + Name[i] + "\" ")
```
Or with simple quotes:
```
file.write('Item "' + Name[i] + '" ')
```
Or with triple double quotes and string interpolation:
```
file.write("""Item "%s" """ % Name[i])
```
Or with simple quotes and format:
```
file.write('Item "{0}"'.forma... |
Py2exe lxml woes | 5,308,760 | 19 | 2011-03-15T07:38:50Z | 5,309,733 | 34 | 2011-03-15T09:25:46Z | [
"python",
"wxpython",
"lxml",
"py2exe"
] | I have a wxpython application that depends on lxml and works well when running it through the python interpreter. However, when creating an exe with py2exe, I got this error
```
ImportError: No module named _elementpath
```
I then used `python setup.py py2exe -p lxml` and I did not get the above error but
another one... | Py2exe allows you to specify additional packages/modules to include with the `options` argument to `setup()`, in case they are not automatically detected. The following should work:
```
from distutils.core import setup
import py2exe
setup(
windows=[{'script': 'gui.py'}],
options={
'py2exe':
{... |
Forward class declaration in Python | 5,308,895 | 5 | 2011-03-15T07:58:38Z | 5,309,027 | 9 | 2011-03-15T08:14:20Z | [
"python",
"django",
"django-models",
"django-south"
] | I have two classes in order:
```
class A(models):
...
class B(models):
a = models.ManyToManyField(A)
```
Now I have to change my model to one below:
```
class A(models):
b = models.ManyToManyField(B)
class B(models):
...
```
I have to use south migrations. I wanted to create new many to many field... | At least SQLAlchemy allows you to use a string instead of a class. Try if django-orm allows that, too.
```
a = models.ManyToManyField('A')
# ...
b = models.ManyToManyField('B')
```
Update: According to [Django/Python Circular model reference.](http://stackoverflow.com/questions/4813293/django-python-circular-model-re... |
find multiple string occurrences in Python | 5,309,204 | 4 | 2011-03-15T08:34:42Z | 5,309,270 | 11 | 2011-03-15T08:42:26Z | [
"python",
"string"
] | is there a way to do something like this?
```
if ['hel','ell','orl'] in 'hello world' :
```
I want to see if all of these strings occur in the word. If possible in a shorter way than completely writing a multiline foor loop. | You could do:
```
if all( x in 'hello world' for x in ['hel','ell','orl'] ):
print "Found all of them"
```
The built-in functions [`all`](http://docs.python.org/library/functions.html#all) and [`any`](http://docs.python.org/library/functions.html#any) are useful for this kind of thing. |
How to get PyCharm to auto-complete code in methods? | 5,309,279 | 14 | 2011-03-15T08:42:59Z | 17,806,951 | 8 | 2013-07-23T09:56:13Z | [
"python",
"autocomplete",
"pycharm"
] | When I'm using a 3rd party l
ibrary such as [boto](http://code.google.com/p/boto/), PyCharm seems to be able to auto-complete quite nicely

However, as soon as I define a function of my own, auto-complete breaks down inside that function. I understand... | You can use type hints: <http://www.jetbrains.com/pycharm/webhelp/type-hinting-in-pycharm.html>
```
def some_method(self, conn):
"""
@type conn: EC2Connection
"""
conn.<autocomplete>
``` |
sprintf like functionality in Python | 5,309,978 | 65 | 2011-03-15T09:49:27Z | 5,310,030 | 30 | 2011-03-15T09:53:48Z | [
"python",
"string"
] | I would like to create a string buffer to do lots of processing, format and finally write the buffer in a text file using a C-style `sprintf` functionality in Python. Because of conditional statements, I canât write them directly to the file.
e.g pseudo code:
```
sprintf(buf,"A = %d\n , B= %s\n",A,B)
/* some proces... | If I understand your question correctly, [format()](http://docs.python.org/library/functions.html#format) is what you are looking for, along with [its mini-language](http://docs.python.org/library/string.html#format-specification-mini-language).
Silly example for python 2.7 and up:
```
>>> print "{} ...\r\n {}!".form... |
sprintf like functionality in Python | 5,309,978 | 65 | 2011-03-15T09:49:27Z | 5,310,040 | 7 | 2011-03-15T09:54:34Z | [
"python",
"string"
] | I would like to create a string buffer to do lots of processing, format and finally write the buffer in a text file using a C-style `sprintf` functionality in Python. Because of conditional statements, I canât write them directly to the file.
e.g pseudo code:
```
sprintf(buf,"A = %d\n , B= %s\n",A,B)
/* some proces... | You can use string formatting:
```
>>> a=42
>>> b="bar"
>>> "The number is %d and the word is %s" % (a,b)
'The number is 42 and the word is bar'
```
But this is removed in Python 3, you should use "str.format()":
```
>>> a=42
>>> b="bar"
>>> "The number is {0} and the word is {1}".format(a,b)
'The number is 42 and t... |
sprintf like functionality in Python | 5,309,978 | 65 | 2011-03-15T09:49:27Z | 5,310,077 | 92 | 2011-03-15T09:57:10Z | [
"python",
"string"
] | I would like to create a string buffer to do lots of processing, format and finally write the buffer in a text file using a C-style `sprintf` functionality in Python. Because of conditional statements, I canât write them directly to the file.
e.g pseudo code:
```
sprintf(buf,"A = %d\n , B= %s\n",A,B)
/* some proces... | Python has a `%` operator for this.
```
>>> a = 5
>>> b = "hello"
>>> buf = "A = %d\n , B = %s\n" % (a, b)
>>> print buf
A = 5
, B = hello
>>> c = 10
>>> buf = "C = %d\n" % c
>>> print buf
C = 10
```
See this [reference](http://docs.python.org/2/library/stdtypes.html#string-formatting-operations) for all supported ... |
sprintf like functionality in Python | 5,309,978 | 65 | 2011-03-15T09:49:27Z | 18,514,789 | 8 | 2013-08-29T15:14:57Z | [
"python",
"string"
] | I would like to create a string buffer to do lots of processing, format and finally write the buffer in a text file using a C-style `sprintf` functionality in Python. Because of conditional statements, I canât write them directly to the file.
e.g pseudo code:
```
sprintf(buf,"A = %d\n , B= %s\n",A,B)
/* some proces... | I'm not completely certain that I understand your goal, but you can use a `StringIO` instance as a buffer:
```
>>> import StringIO
>>> buf = StringIO.StringIO()
>>> buf.write("A = %d, B = %s\n" % (3, "bar"))
>>> buf.write("C=%d\n" % 5)
>>> print(buf.getvalue())
A = 3, B = bar
C=5
```
Unlike `sprintf`, you just pass ... |
Access to the values of set() | 5,310,646 | 7 | 2011-03-15T10:54:04Z | 5,310,674 | 19 | 2011-03-15T10:56:08Z | [
"python"
] | Any way to access the values of BIF "set()" without using an iterator.
For instance, I got this output from my code:
```
>>> set([1,2,3])
```
How can I access it as a list?
Like:
```
>>> [1,2,3]
``` | Use a simple type conversion:
```
>>> a
set([1, 2, 3])
>>> list(a)
[1, 2, 3]
``` |
How do I get rid of the "u" from a decoded JSON object? | 5,312,948 | 15 | 2011-03-15T14:07:18Z | 5,313,273 | 16 | 2011-03-15T14:33:08Z | [
"python"
] | I have a dictionary of dictionaries in Python:
```
d = {"a11y_firesafety.html":{"lang:hi": {"div1": "http://a11y.in/a11y/idea/a11y_firesafety.html:hi"}, "lang:kn": {"div1": "http://a11y.in/a11ypi/idea/a11y_firesafety.html:kn}}}
```
I have this in a JSON file and I encoded it using `json.dumps()`. Now when I decode it... | Why do you care about the 'u' characters? They're just a visual indicator; unless you're actually using the result of `str(temp)` in your code, they have no effect on your code. For example:
```
>>> test = u"abcd"
>>> test == "abcd"
True
```
If they do matter for some reason, and you don't care about consequences lik... |
Execute function without sending 'self' to it | 5,313,364 | 3 | 2011-03-15T14:38:41Z | 5,313,485 | 9 | 2011-03-15T14:49:04Z | [
"python",
"google-app-engine"
] | Is that possible to define a function without referencing to `self` this way?
```
def myfunc(var_a,var_b)
```
But so that it could also get sender data, like if I defined it like this:
```
def myfunc(self, var_a,var_b)
```
That `self` is always the same so it looks a little redundant here always to run a function t... | If you don't *need* self, you can use the `staticmethod` decorator to create a method which does not receive the object as its first argument:
```
class Foo(object):
@staticmethod
def foo(bar, baz, qux):
pass
```
If you're writing code which deals only with class-global data, by contrast, you can use ... |
How to delete an AMI using boto? | 5,313,726 | 3 | 2011-03-15T15:08:25Z | 11,861,452 | 7 | 2012-08-08T09:23:47Z | [
"python",
"amazon-ec2",
"boto"
] | (cross posted to [boto-users](https://groups.google.com/d/topic/boto-users/TSVqfgbAhRM/discussion))
Given an image ID, how can I delete it using boto? | With newer boto (Tested with 2.38.0), you can run:
```
ec2_conn = boto.ec2.connect_to_region('xx-xxxx-x')
ec2_conn.deregister_image('ami-xxxxxxx')
```
or
```
ec2_conn.deregister_image('ami-xxxxxxx', delete_snapshot=True)
```
The first will delete the AMI, the second will also delete the attached EBS snapshot |
Generating cyclic permutations / reduced Latin Squares in Python | 5,313,900 | 5 | 2011-03-15T15:21:47Z | 5,313,961 | 11 | 2011-03-15T15:26:25Z | [
"python",
"algorithm",
"list",
"permutation",
"cyclic"
] | Was just wondering what's the most efficient way of generating all the cyclic permutations of a list in Python. In either direction. For example, given a list `[1, 2, 3, 4]`, I want to generate either:
```
[[1, 2, 3, 4],
[4, 1, 2, 3],
[3, 4, 1, 2],
[2, 3, 4, 1]]
```
where the next permutation is generated by movin... | You can use collections.deque:
```
from collections import deque
g = deque([1, 2, 3, 4])
for i in range(len(g)):
print list(g) #or do anything with permutation
g.rotate(1) #for right rotation
#or g.rotate(-1) for left rotation
```
It prints:
```
[1, 2, 3, 4]
[4, 1, 2, 3]
[3, 4, 1, 2]
[2, 3, 4, 1]
`... |
Naming variable, best convention | 5,314,421 | 9 | 2011-03-15T15:58:36Z | 5,314,442 | 8 | 2011-03-15T15:59:58Z | [
"python",
"django",
"naming-conventions"
] | What is the most used convention for naming variables in Python / Django?
ex: pub\_date or pubdate
What about for classes and methods? | [PEP 8](http://www.python.org/dev/peps/pep-0008/), nothing more to say.
Of course you can use your own style (I use camelCase, for example), but most people use recommendations from that PEP. |
Naming variable, best convention | 5,314,421 | 9 | 2011-03-15T15:58:36Z | 5,314,651 | 13 | 2011-03-15T16:16:59Z | [
"python",
"django",
"naming-conventions"
] | What is the most used convention for naming variables in Python / Django?
ex: pub\_date or pubdate
What about for classes and methods? | [Django's coding style](https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/coding-style/) |
matplot - store image in variable | 5,314,707 | 9 | 2011-03-15T16:22:38Z | 5,314,808 | 18 | 2011-03-15T16:31:05Z | [
"python",
"html",
"image",
"matplotlib"
] | I would like to store the image generated by matplot in a variable raw\_data to use it as inline image.
```
import os
import sys
os.environ['MPLCONFIGDIR'] = '/tmp/'
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
print "Content-type: image/png\n"
plt.plot(range(10, 20))
raw_data = plt.show()... | Have you tried `cStringIO` or an equivalent?
```
import os
import sys
import matplotlib
import matplotlib.pyplot as plt
import StringIO
import urllib, base64
plt.plot(range(10, 20))
fig = plt.gcf()
imgdata = StringIO.StringIO()
fig.savefig(imgdata, format='png')
imgdata.seek(0) # rewind the data
print "Content-typ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.