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 |
|---|---|---|---|---|---|---|---|---|---|
Get key by value in dictionary | 8,023,306 | 189 | 2011-11-05T21:09:18Z | 14,624,923 | 38 | 2013-01-31T11:42:59Z | [
"python",
"dictionary"
] | I made a function which will look up ages in dictionary and show the matching name:
```
list = {'george':16,'amber':19}
search_age = raw_input("Provide age")
for age in list.values():
if age == search_age:
name = list[age]
print name
```
I know how to compare and find the age I just don't know how... | I thought it would be interesting to point out which methods are the quickest, and in what scenario:
Here's some tests I ran (on a 2012 MacBook Pro)
```
>>> def method1(list,search_age):
... for name,age in list.iteritems():
... if age == search_age:
... return name
...
>>> def me... |
Get key by value in dictionary | 8,023,306 | 189 | 2011-11-05T21:09:18Z | 19,165,996 | 15 | 2013-10-03T18:01:04Z | [
"python",
"dictionary"
] | I made a function which will look up ages in dictionary and show the matching name:
```
list = {'george':16,'amber':19}
search_age = raw_input("Provide age")
for age in list.values():
if age == search_age:
name = list[age]
print name
```
I know how to compare and find the age I just don't know how... | one line version: (i is an old dictionary, p is a reversed dictionary)
```
p = dict(zip(i.values(),i.keys()))
``` |
Programatically opening URLs in web browser in Python | 8,024,091 | 7 | 2011-11-05T23:27:27Z | 8,024,106 | 14 | 2011-11-05T23:30:18Z | [
"python",
"url",
"tkinter",
"hyperlink"
] | I have a tkinter script. I was wondering is there anyway to have is so when you hit a button it takes you to a Web Site
```
from tkinter import *
app = Tk()
app.geometry("250x400")
app.title("Links")
def Link():
?
button1 = Button(app, text = "To a web site.", command = Link)
button1.pack()
app.mainloop()
``` | There's a [module for that](http://docs.python.org/library/webbrowser.html).
```
import webbrowser
webbrowser.open("http://xkcd.com/353/")
``` |
Telling Python to save a .txt file to a certain directory on Windows and Mac | 8,024,248 | 8 | 2011-11-06T00:01:33Z | 8,024,254 | 18 | 2011-11-06T00:02:58Z | [
"python"
] | How do you tell Python where to save a text file?
For example, my computer is running the Python file off my desktop. I want it to save all the text file in my documents folder, not on my desktop. How do I do that in a script like this?
```
name_of_file = raw_input("What is the name of the file: ")
completeName = nam... | Just use an absolute path when opening the filehandle for writing.
```
import os.path
save_path = 'C:/example/'
name_of_file = raw_input("What is the name of the file: ")
completeName = os.path.join(save_path, name_of_file+".txt")
file1 = open(completeName, "w")
toFile = raw_input("Write what you want in... |
Telling Python to save a .txt file to a certain directory on Windows and Mac | 8,024,248 | 8 | 2011-11-06T00:01:33Z | 8,024,259 | 9 | 2011-11-06T00:04:23Z | [
"python"
] | How do you tell Python where to save a text file?
For example, my computer is running the Python file off my desktop. I want it to save all the text file in my documents folder, not on my desktop. How do I do that in a script like this?
```
name_of_file = raw_input("What is the name of the file: ")
completeName = nam... | Use [os.path.join](http://docs.python.org/library/os.path.html#os.path.join) to combine the path to the `Documents` directory with the `completeName` (filename?) supplied by the user.
```
import os
with open(os.path.join('/path/to/Documents',completeName), "w") as file1:
toFile = raw_input("Write what you want int... |
Insert an item into sorted list in Python | 8,024,571 | 13 | 2011-11-06T01:14:13Z | 8,024,678 | 39 | 2011-11-06T01:45:10Z | [
"python",
"list",
"sorted"
] | I'm creating a class where one of the methods inserts a new item into the sorted list. The item is inserted in the corrected (sorted) position in the sorted list. I'm not allowed to use any built-in list functions or methods other than `[]`, `[:]`, `+`, and `len` though. This is the part that's really confusing to me.
... | Hint 1: You might want to study the Python code in the [bisect module](http://docs.python.org/py3k/library/bisect.html#module-bisect).
Hint 2: [Slicing](http://docs.python.org/tutorial/introduction.html#lists) can be used for list insertion:
```
>>> s = ['a', 'b', 'd', 'e']
>>> s[2:2] = ['c']
>>> s
['a', 'b', 'c', 'd... |
Insert an item into sorted list in Python | 8,024,571 | 13 | 2011-11-06T01:14:13Z | 24,714,344 | 10 | 2014-07-12T15:19:30Z | [
"python",
"list",
"sorted"
] | I'm creating a class where one of the methods inserts a new item into the sorted list. The item is inserted in the corrected (sorted) position in the sorted list. I'm not allowed to use any built-in list functions or methods other than `[]`, `[:]`, `+`, and `len` though. This is the part that's really confusing to me.
... | You should use the bisect module. Also, the list needs to be sorted before using bisect.insort\_left
It's a pretty big difference.
```
>>> l = [0, 2, 4, 5, 9]
>>> bisect.insort_left(l,8)
>>> l
[0, 2, 4, 5, 8, 9]
timeit.timeit("l.append(8); l = sorted(l)",setup="l = [4,2,0,9,5]; import bisect; l = sorted(l)",number=1... |
Cython compiled C extension: ImportError: dynamic module does not define init function | 8,024,805 | 29 | 2011-11-06T02:21:02Z | 13,976,504 | 13 | 2012-12-20T16:30:30Z | [
"python",
"cython",
"python-extensions"
] | I have just compiled part of my C library as an extension using Cython, as a "proof of concept". I managed to hack the code (const correctnes problems etc aside), to finally get an extension built.
However, when I attempted to import the newly created extension, I got the following error:
```
ImportError: dynamic mod... | It appears that it's a bug/feature in Cython. I had the same thing, but simply added:
```
STUFF = "Hi"
```
to the top of my .pyx file and the issue went away. It appears if there is no global initialization (a **cinit** or setting a global variable), that the required initialization code isn't generated. |
Cython compiled C extension: ImportError: dynamic module does not define init function | 8,024,805 | 29 | 2011-11-06T02:21:02Z | 21,430,697 | 40 | 2014-01-29T12:08:46Z | [
"python",
"cython",
"python-extensions"
] | I have just compiled part of my C library as an extension using Cython, as a "proof of concept". I managed to hack the code (const correctnes problems etc aside), to finally get an extension built.
However, when I attempted to import the newly created extension, I got the following error:
```
ImportError: dynamic mod... | I've found that a frequent cause of this problem is, when using a distutils setup file to compile the code, that the .pyx base name does not match the extension name, e.g:
```
ext = Extension(name='different', sources=['cython_ext.pyx']) # Won't work
```
To avoid the problem the extension name should be exactly the s... |
Project Euler 5 in Python - How can I optimize my solution? | 8,024,911 | 6 | 2011-11-06T02:48:58Z | 8,025,847 | 9 | 2011-11-06T07:57:49Z | [
"python"
] | I've recently been working on Project Euler problems in Python. I am fairly new to Python, and still somewhat new as a programmer.
In any case, I've ran into a speed-related issue coding a solution for problem #5. The problem is,
"2520 is the smallest number that can be divided by each of the numbers from 1 to 10 wit... | Taking the advice of Michael Mior and poke, I wrote a solution. I tried to use a few tricks to make it fast.
Since we need a relatively short list of numbers tested, then we can pre-build the list of numbers rather than repeatedly calling `xrange()` or `range()`.
Also, while it would work to just put the numbers `[1,... |
ImportError: no module named Tkinter (Running python with NotePad++'s NppExec) | 8,025,188 | 2 | 2011-11-06T04:15:15Z | 8,027,934 | 8 | 2011-11-06T15:08:15Z | [
"python",
"tkinter",
"notepad++",
"importerror",
"nppexec"
] | I'm trying to run a python file using Notepad++'s NppExec plugin. My file attempts to import Tkinter using the line "from Tkinter import \* ". With NppExec, I run the following script:
```
python "$(FULL_CURRENT_PATH)"
```
or sometimes
```
python -i "$(FULL_CURRENT_PATH)"
```
In either case, I get the error "Import... | The problem is simple -- the python command you are running does not have a module named Tkinter. The *cause* of the problem is more difficult to understand without more information. My first guess would be that NppExec is running a different version of python than you think it is running, and this version of python ei... |
Does Python GC deal with reference-cycles like this? | 8,025,888 | 9 | 2011-11-06T08:11:21Z | 8,025,922 | 18 | 2011-11-06T08:19:07Z | [
"python",
"memory-leaks",
"garbage-collection",
"objgraph"
] | Using [objgraph](http://mg.pov.lt/objgraph/), I found a bunch of objects like this:

Will Python's garbage collector deal with cycles like this, or will it leak?
A slightly wider view of the loop:
, however, is enabled by default and should be able to free that structure, if none of its components are reachable from ... |
Does Python GC deal with reference-cycles like this? | 8,025,888 | 9 | 2011-11-06T08:11:21Z | 8,027,665 | 14 | 2011-11-06T14:27:54Z | [
"python",
"memory-leaks",
"garbage-collection",
"objgraph"
] | Using [objgraph](http://mg.pov.lt/objgraph/), I found a bunch of objects like this:

Will Python's garbage collector deal with cycles like this, or will it leak?
A slightly wider view of the loop:
 of the docs explains the supplementary cycle detection nicely.
Since I find explaining things a good way to confirm I understand it, here are some examples... With these two classe... |
Parse X-Forwarded-For to get ip with werkzeug on Heroku | 8,026,281 | 6 | 2011-11-06T09:53:43Z | 8,040,145 | 14 | 2011-11-07T17:26:13Z | [
"python",
"heroku",
"ip",
"flask",
"werkzeug"
] | Heroku proxies requests from a client to server, so you have to parse the X-Forwarded-For to find the originating IP address.
The general format of the X-Forwarded-For is:
```
X-Forwarded-For: client1, proxy1, proxy2
```
Using werkzeug on flask, I'm trying to come up with a solution in order to access the originatin... | Werkzeug (and Flask) store headers in an instance of [`werkzeug.datastructures.Headers`](http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.Headers). You should be able to do something like this:
```
provided_ips = request.headers.getlist("X-Forwarded-For")
# The first entry in the list should be t... |
Python list.append as an argument | 8,026,660 | 3 | 2011-11-06T11:24:37Z | 8,026,667 | 7 | 2011-11-06T11:26:34Z | [
"python",
"list",
"python-3.x"
] | Why does the following code give 'None'? How can I resolve this?
```
def f1(list1):
f2(list1.append(2))
def f2(list1):
print(list1)
f1([1])
```
What also doesn't work:
```
def f1(list1):
arg1 = list1.append(2)
f2(arg1)
``` | In general, Python methods that mutate an object (such as `list.append`, `list.extend`, or `list.sort`) return `None`.
If you wish to print out the new list:
```
def f1(list1):
list1.append(2)
f2(list1)
``` |
What does this message mean? from: can't read /var/mail/ex48 (Learn Python the Hard Way ex49) | 8,028,036 | 8 | 2011-11-06T15:22:14Z | 8,028,060 | 10 | 2011-11-06T15:25:49Z | [
"python"
] | In ex49, we are told to call the the lexicon.py file created in ex48 with the following command.
When I try to import the lexicon file with the following command
```
>>> from ex48 import lexicon
```
it returns the following:
```
from: can't read /var/mail/ex48
```
I've tried looking this up. What does this... | You didn't type "from ex48 import lexicon" in the Python shell, you typed it in at the command line. "from" is the command to list who mail is from, hence the /var/mail location.
You can tell this from the different error messages the commands produce:
```
localhost-2:~ $ from ex48 import lexicon
from: can't read /va... |
What does this message mean? from: can't read /var/mail/ex48 (Learn Python the Hard Way ex49) | 8,028,036 | 8 | 2011-11-06T15:22:14Z | 11,729,172 | 23 | 2012-07-30T20:35:06Z | [
"python"
] | In ex49, we are told to call the the lexicon.py file created in ex48 with the following command.
When I try to import the lexicon file with the following command
```
>>> from ex48 import lexicon
```
it returns the following:
```
from: can't read /var/mail/ex48
```
I've tried looking this up. What does this... | You need to add the shebang to the first line of your program. Put in `#!/usr/bin/python` or where ever your python bin is located and your program will run. |
How to sort OrderedDict in OrderedDict - Python | 8,031,418 | 22 | 2011-11-07T00:07:11Z | 8,031,431 | 46 | 2011-11-07T00:09:16Z | [
"python"
] | I'm trying to sort OrderedDict in OrderedDict by **'depth'** key.
Is there any solution to sort that Dictionary ?
```
OrderedDict([
(2, OrderedDict([
('depth', 0),
('height', 51),
('width', 51),
('id', 100)
])),
(1, OrderedDict([
('depth', 2),
('height', 51),
('width', 51), ... | You'll have to create a new one since `OrderedDict` is sorted by insertion order.
In your case the code would look like this:
```
foo = OrderedDict(sorted(foo.iteritems(), key=lambda x: x[1]['depth']))
```
See <http://docs.python.org/dev/library/collections.html#ordereddict-examples-and-recipes> for more examples. |
How to sort OrderedDict in OrderedDict - Python | 8,031,418 | 22 | 2011-11-07T00:07:11Z | 8,031,448 | 9 | 2011-11-07T00:12:23Z | [
"python"
] | I'm trying to sort OrderedDict in OrderedDict by **'depth'** key.
Is there any solution to sort that Dictionary ?
```
OrderedDict([
(2, OrderedDict([
('depth', 0),
('height', 51),
('width', 51),
('id', 100)
])),
(1, OrderedDict([
('depth', 2),
('height', 51),
('width', 51), ... | ```
>>> OrderedDict(sorted(od.items(), key=lambda item: item[1]['depth']))
``` |
python: count word tokens in sentence | 8,031,658 | 2 | 2011-11-07T00:49:28Z | 8,031,704 | 10 | 2011-11-07T00:58:07Z | [
"python",
"string",
"replace"
] | I'm trying to count the number of words in a string. however, i first have to strip some punctuations e.g.
```
line = "i want you , to know , my name . "
```
running
```
en = line.translate(string.maketrans('', ''), '!,.?')
```
produces
```
en = "i want you to know my name "
```
after this, i want to count the... | The problem with `en.split(' ')` is that you have extra whitespace in your string, which gives empty matches. You could fix this quite easily by calling `en.split()` instead.
But perhaps you could use this different approach using a regular expression (and now there is no need to remove the punctuation first):
```
im... |
Same equation, different answers from Pylab and Octave | 8,031,937 | 8 | 2011-11-07T01:41:27Z | 8,032,055 | 12 | 2011-11-07T02:07:24Z | [
"python",
"matlab",
"octave",
"equation",
"matplotlib"
] | I am porting code created in octave into pylab. One of the ported equations gives dramatically different results in python than it does in octave.
The best way to explain is to show plots generated by octave and pylab from the same equation.
Here is a simplified snippet of the original equation in octave. In this sma... | Try `from __future__ import division` to eliminate errors arising from floor division. |
how to define functions in ipython configuration file? | 8,032,224 | 4 | 2011-11-07T02:41:10Z | 8,032,599 | 9 | 2011-11-07T04:02:00Z | [
"python",
"ipython"
] | Using ipython 0.11 if I type a function definition, like
```
def f(s): print s
```
then I can use that function in that ipython session, but I don't know how to define that
in the ipython\_config.py file.
If I just type the function definition in the file and try to use the function it it undefined.
Any idea? | Two answers here:
First, for *super* simple functions like the one above, you can define them in `exec_lines`, e.g.:
```
c.InteractiveShellApp.exec_lines = [ "def f(s): print s" ]
```
(you can define arbitrarily complex functions this way, but it gets annoying beyond a couple of lines)
For more complicated code, yo... |
How to obtain image size using standard Python class (without using external library)? | 8,032,642 | 38 | 2011-11-07T04:11:00Z | 8,033,053 | 11 | 2011-11-07T05:32:56Z | [
"python",
"image",
"python-2.5"
] | I am using Python 2.5. And using the standard classes from Python, I want to determine the image size of a file.
I've heard PIL (Python Image Library), but it requires installation to work.
How might I obtain an image's size without using any external library, just using Python 2.5's own modules?
Note I want to supp... | While it's possible to call `open(filename, 'rb')` and check through the binary image headers for the dimensions, it seems much more useful to install PIL and spend your time writing great new software! You gain greater file format support and the reliability that comes from widespread usage. [From the PIL documentatio... |
How to obtain image size using standard Python class (without using external library)? | 8,032,642 | 38 | 2011-11-07T04:11:00Z | 9,499,976 | 37 | 2012-02-29T13:25:24Z | [
"python",
"image",
"python-2.5"
] | I am using Python 2.5. And using the standard classes from Python, I want to determine the image size of a file.
I've heard PIL (Python Image Library), but it requires installation to work.
How might I obtain an image's size without using any external library, just using Python 2.5's own modules?
Note I want to supp... | Kurts answer needed to be slightly modified to work for me.
First, on ubuntu: `sudo apt-get install python-imaging`
Then:
```
from PIL import Image
im=Image.open(filepath)
im.size # (width,height) tuple
```
Check out the [handbook](http://effbot.org/imagingbook/image.htm) for more info. |
How to obtain image size using standard Python class (without using external library)? | 8,032,642 | 38 | 2011-11-07T04:11:00Z | 20,380,514 | 53 | 2013-12-04T16:21:22Z | [
"python",
"image",
"python-2.5"
] | I am using Python 2.5. And using the standard classes from Python, I want to determine the image size of a file.
I've heard PIL (Python Image Library), but it requires installation to work.
How might I obtain an image's size without using any external library, just using Python 2.5's own modules?
Note I want to supp... | Here's a python 3 script that returns a tuple containing an image height and width for .png, .gif and .jpeg without using any external libraries (ie what Kurt McKee referenced above). Should be relatively easy to transfer it to Python 2.
```
import struct
import imghdr
def get_image_size(fname):
'''Determine the ... |
How to obtain image size using standard Python class (without using external library)? | 8,032,642 | 38 | 2011-11-07T04:11:00Z | 21,555,489 | 14 | 2014-02-04T14:43:17Z | [
"python",
"image",
"python-2.5"
] | I am using Python 2.5. And using the standard classes from Python, I want to determine the image size of a file.
I've heard PIL (Python Image Library), but it requires installation to work.
How might I obtain an image's size without using any external library, just using Python 2.5's own modules?
Note I want to supp... | Here's a way to get dimensions of a png file without needing a third-party module. From <http://coreygoldberg.blogspot.com/2013/01/python-verify-png-file-and-get-image.html>
```
import struct
def get_image_info(data):
if is_png(data):
w, h = struct.unpack('>LL', data[16:24])
width = int(w)
... |
How to obtain image size using standard Python class (without using external library)? | 8,032,642 | 38 | 2011-11-07T04:11:00Z | 27,783,749 | 19 | 2015-01-05T16:30:28Z | [
"python",
"image",
"python-2.5"
] | I am using Python 2.5. And using the standard classes from Python, I want to determine the image size of a file.
I've heard PIL (Python Image Library), but it requires installation to work.
How might I obtain an image's size without using any external library, just using Python 2.5's own modules?
Note I want to supp... | You can use Pillow ([Documentation](http://pillow.readthedocs.org/), [GitHub](https://github.com/python-pillow/Pillow), [PyPI](https://pypi.python.org/pypi/Pillow/)).
## Installation
```
$ pip install Pillow
```
If you don't have administrator rights (sudo on Debian), you can use
```
$ pip install --user Pillow
```... |
Re.sub not working for me | 8,033,375 | 6 | 2011-11-07T06:30:26Z | 8,033,393 | 9 | 2011-11-07T06:32:56Z | [
"python",
"regex"
] | I'm trying to get `re.sub` to replace a pattern specified with a value for example
```
for lines in f:
pattern='\${2}'+key[0]+'\${2}'
re.search(pattern,lines)
```
this return the line where the pattern was found. For example this is one of the test returns if got
this is a $$test$$
The problem i'm having is... | You *are* assigning the result of `re.sub` back to a variable, right? e.g.
```
lines = re.sub(pattern, key[1], lines)
```
It's a string, so it can't be changed (strings are immutable in Python), therefore a new string is created and returned to you. If you don't assign it back to a name, you will lose it. |
Python socket bind to any IP? | 8,033,552 | 12 | 2011-11-07T06:58:00Z | 8,033,598 | 21 | 2011-11-07T07:03:12Z | [
"python",
"sockets"
] | I have a small one sided message sender that works while i specify the ip to connect to in code, however, i am having trouble allowing the socket to accept connections from any IP. Here is the line that is the problem.
```
mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
mySocket.bind ( ( '', 2727 ) )
`... | If you want to bind to all available IPv4 addresses, specify `0.0.0.0` as your IP address. If you're behind a router and wish to have your socket internet-accessible, rather than just available on your LAN, you'll need to set up a port forwarding rule so that users outside your LAN can access the service.
See the foll... |
Ternary operator return `True` instead the given value | 8,034,257 | 4 | 2011-11-07T08:36:24Z | 8,034,278 | 7 | 2011-11-07T08:39:03Z | [
"python",
"conditional"
] | I'm using ternary operator for short conditional variable definition. I was wondering when the expression returned True instead given in the expression value.
```
>>> digits = '123456'
>>> conv_d = digits != None if int(digits) else None
>>> conv_d
>>> True
>>> int(digits)
>>> 123456
```
Explain to me please, how ... | `int(digits) == 123456` which is a true-ish value. So `conv_d = digits != None`. Since `digits` is not `None`, `conv_d` is set to true.
You probably wanted this:
```
conv_d = int(digits) if digits is not None else None
```
Remember that a string containing something not a number will raise an exception though! If yo... |
How to get filename from Content-Disposition in headers | 8,035,900 | 17 | 2011-11-07T11:34:25Z | 27,840,405 | 17 | 2015-01-08T12:42:37Z | [
"python",
"mechanize-python"
] | I am downloading a file with Mechanize and in response headers there is a string:
```
Content-Disposition: attachment; filename=myfilename.txt
```
Is there a quick standard way to get that filename value?
What I have in mind now is this:
```
filename = f[1]['Content-Disposition'].split('; ')[1].replace('filename=', ... | First get the value of the header by using mechanize, then parse the header using the builtin [cgi](https://docs.python.org/2/library/cgi.html) module.
To demonstrate:
```
>>> import mechanize
>>> browser = mechanize.Browser()
>>> response = browser.open('http://example.com/your/url')
>>> info = response.info()
>>> h... |
Function of Numpy Array with if-statement | 8,036,878 | 11 | 2011-11-07T13:04:12Z | 8,037,010 | 10 | 2011-11-07T13:18:10Z | [
"python",
"numpy",
"matplotlib"
] | I am using [Matplotlib](http://matplotlib.sourceforge.net/) and [Numpy](http://numpy.scipy.org/) to produce some plots. I wish to define a function which given an array returns another array with values calculated *elementwise*, for example:
```
def func(x):
return x*10
x = numpy.arrange(-1,1,0.01)
y = func(x)
`... | This should do what you want:
```
def func(x):
small_indices = x < 10
x[small_indices] = 0
x[invert(small_indices)] *= 10
return x
```
[`invert`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.invert.html) is a Numpy-function. Note that this modifies the argument. To prevent this, you'd hav... |
Function of Numpy Array with if-statement | 8,036,878 | 11 | 2011-11-07T13:04:12Z | 8,037,078 | 8 | 2011-11-07T13:25:43Z | [
"python",
"numpy",
"matplotlib"
] | I am using [Matplotlib](http://matplotlib.sourceforge.net/) and [Numpy](http://numpy.scipy.org/) to produce some plots. I wish to define a function which given an array returns another array with values calculated *elementwise*, for example:
```
def func(x):
return x*10
x = numpy.arrange(-1,1,0.01)
y = func(x)
`... | Use numpy.vectorize to wrap func before applying it to array x:
```
from numpy import vectorize
vfunc = vectorize(func)
y = vfunc(x)
``` |
Quick and easy way to check if all items in a dictionary are empty strings? | 8,037,060 | 4 | 2011-11-07T13:23:29Z | 8,037,079 | 12 | 2011-11-07T13:25:46Z | [
"python"
] | I have a dictionary of N items. Their values are strings, but I'm looking for an easy way to detect if they are all empty strings.
```
{'a': u'', 'b': u'', 'c': u''}
``` | ```
not any(dict.itervalues())
```
Or:
```
all(not X for X in dict.itervalues())
```
Whichever you find clearer. |
How to modify python collections by filtering in-place? | 8,037,455 | 6 | 2011-11-07T13:59:37Z | 8,037,476 | 13 | 2011-11-07T14:01:33Z | [
"python",
"collections"
] | I was wondering, if there is way in Python to modify collections without creating new ones. E.g.:
```
lst = [1, 2, 3, 4, 5, 6]
new_lst = [i for i in lst if i > 3]
```
Works just fine, but a new collection is created. Is there a reason, that Python collections lack a `filter()` method (or similar) that would modify th... | If you want to do this in place, just use
```
lst[:] = [i for i in lst if i > 3]
```
This [won't be faster or save any memory](http://stackoverflow.com/questions/4948293/python-slice-assignment-memory-usage/4948508#4948508), but it changes the object in place, if this is the semantics you need. |
Resource usage of google Go vs Python and Java on Appengine | 8,037,783 | 43 | 2011-11-07T14:26:48Z | 8,038,951 | 17 | 2011-11-07T15:56:39Z | [
"java",
"python",
"google-app-engine",
"go"
] | Will google Go use less resources than Python and Java on Appengine? Are the instance startup times for go faster than Java's and Python's startup times?
Is the go program uploaded as binaries or source code and if it is uploaded as source code is it then compiled once or at each instance startup?
In other words: Wil... | The cost of instances is only part of the cost of your app. I only use the Java runtime right now, so I don't know how much more or less efficient things would be with Python or Go, but I don't imagine it will be orders of magnitude different. I do know that instances are not the only cost you need to consider. Dependi... |
Resource usage of google Go vs Python and Java on Appengine | 8,037,783 | 43 | 2011-11-07T14:26:48Z | 10,283,180 | 40 | 2012-04-23T15:09:26Z | [
"java",
"python",
"google-app-engine",
"go"
] | Will google Go use less resources than Python and Java on Appengine? Are the instance startup times for go faster than Java's and Python's startup times?
Is the go program uploaded as binaries or source code and if it is uploaded as source code is it then compiled once or at each instance startup?
In other words: Wil... | > Will google Go use less resources than Python and Java on Appengine?
> Are the instance startup times for go faster than Java's and Python's
> startup times?
Yes, Go instances have a lower memory than Python and Java (< 10 MB).
Yes, Go instances start faster than Java and Python equivalent because the runtime only ... |
Resource usage of google Go vs Python and Java on Appengine | 8,037,783 | 43 | 2011-11-07T14:26:48Z | 10,370,469 | 14 | 2012-04-29T07:33:53Z | [
"java",
"python",
"google-app-engine",
"go"
] | Will google Go use less resources than Python and Java on Appengine? Are the instance startup times for go faster than Java's and Python's startup times?
Is the go program uploaded as binaries or source code and if it is uploaded as source code is it then compiled once or at each instance startup?
In other words: Wil... | The question is mostly irrelevant.
The minimum memory footprint for a Go app is less than a Python app which is less than a Java app. They all cost the same per-instance, so unless your application performs better with extra heap space, this issue is irrelevant.
Go startup time is less than Python startup time which ... |
matplotlib hist while ignoring a particular no data value | 8,039,276 | 5 | 2011-11-07T16:17:40Z | 8,039,368 | 8 | 2011-11-07T16:23:49Z | [
"python",
"numpy",
"matplotlib"
] | I've got a 2D numpy array with 1.0e6 as the no data value. I'd like to generate a histogram of the data and while I've succeeded this can't be the best way to do it.
```
from matplotlib import pyplot
import sys
eps = sys.float_info.epsilon
no_data = 1.0e6
e_data = elevation.reshape(elevation.size)
e_data_clean = [ ]... | You can use a boolean array to select the required indices:
```
selected_values = (e_data > (no_data + eps)) & (e_data < (no_data - eps))
pyplot.hist(e_data[selected_values])
```
`(e_data > (no_data + eps))` will create an array of `np.bool` with the same shape as `e_data`, set to `True` at a given index if and only ... |
Python - shortening an if / for loop | 8,041,276 | 3 | 2011-11-07T19:07:42Z | 8,041,301 | 7 | 2011-11-07T19:09:51Z | [
"python",
"coding-style",
"if-statement",
"for-loop",
"iterator"
] | I've got a few lines of code for iterating over a dict within a list and I'm looking to shorten it. It works perfectly as is, but seems like too much code and I'm trying to get a feel for how to keep code efficient in Python (or in general really).
```
for d in dev['devices']:
if d['name'] == devName:
devF... | Basically the same, only rewritten with some built-in function and a generator:
```
devFound = any(d['name'] == devName for d in dev['devices'])
``` |
if 'x' and 'y' in 'z': | 8,041,944 | 2 | 2011-11-07T20:08:36Z | 8,041,968 | 11 | 2011-11-07T20:09:53Z | [
"python",
"if-statement"
] | I'm making sort of a Q&A script in python. It gets raw\_input, and sets it as theQuestion. I tried `if 'var1' and 'var2' in theQuestion:`, but it looks for either string, not both. Is there a way I can make this work in one 'if' statement? (not 'if x: if y: then z). | `and` is a logical AND, not a natural-language one. Therefore, your code gets interpreted as:
```
'var1' and 'var2' in theQuestion
True and 'var2' in theQuestion # Since bool('var1') == True
'var2' in theQuestion
```
You want to connect the two tests with a logical AND:
```
if 'var1' in theQuestion and ... |
What is a Python equivalent of Perlbrew? | 8,045,629 | 6 | 2011-11-08T03:31:47Z | 8,045,650 | 8 | 2011-11-08T03:36:14Z | [
"python"
] | Is there a Python equivalent of [Perlbrew](http://www.perlbrew.pl/)?
Ideally, this `equivalent' would have at least the following two features:
1. Allow for multiple Python isolated installs, ie perlbrew install, list, use...
2. Allow for the installation of `non-core' Python modules to specific Python installs, as i... | I d say virtualenv
<https://pypi.python.org/pypi/virtualenv/>
It seems like the same thing and you use pip to install your packages in your virtual python environments. |
Sometimes PyDev doesn't recognise .py files as python source files | 8,045,991 | 4 | 2011-11-08T04:32:45Z | 8,049,228 | 7 | 2011-11-08T10:49:44Z | [
"python",
"eclipse",
"pydev"
] | Sometimes when I open a python file (.py extension) in the PyDev Package Explorer, that file is opened as a plain text file - without syntax highlighting, breakpoint setting and all the other great PyDev features. I cannot see any differences to other files in the same folder. When I create another .py file (this time ... | If this happens (and the association for file marks "Python editor" as the default in the preferences), you can right-click the file and do "open with > other" and choose "Python editor" from the list.
That setting should be persisted for that file later on (what could've happened is that you opened the file as text a... |
Python optparse, default values, and explicit options | 8,046,064 | 6 | 2011-11-08T04:48:19Z | 8,046,254 | 7 | 2011-11-08T05:18:09Z | [
"python",
"optparse"
] | Take the following rather standard code:
```
from optparse import OptionParser
opts = OptionParser()
opts.add_option('-f', action="store_true")
opts.add_option("-x", dest="x", type="int", default=1)
options, args = opts.parse_args()
```
Assume that `-x` and `-f` are mutually exclusive: when `... | Use [argparse](http://docs.python.org/library/argparse.html). There's a section for [mutually exclusive groups](http://docs.python.org/library/argparse.html#mutual-exclusion):
> **argparse.add\_mutually\_exclusive\_group(required=False)**
>
> Create a mutually exclusive group. argparse will make sure that only one of ... |
Python optparse, default values, and explicit options | 8,046,064 | 6 | 2011-11-08T04:48:19Z | 8,046,338 | 8 | 2011-11-08T05:29:08Z | [
"python",
"optparse"
] | Take the following rather standard code:
```
from optparse import OptionParser
opts = OptionParser()
opts.add_option('-f', action="store_true")
opts.add_option("-x", dest="x", type="int", default=1)
options, args = opts.parse_args()
```
Assume that `-x` and `-f` are mutually exclusive: when `... | You can accomplish this with `optparse` using a callback. Building from your code:
```
from optparse import OptionParser
def set_x(option, opt, value, parser):
parser.values.x = value
parser.values.x_set_explicitly = True
opts = OptionParser()
opts.add_option('-f', action="store_true")
opts.add_option("-x", ... |
Can I define a scope anywhere in Python? | 8,046,142 | 8 | 2011-11-08T05:01:42Z | 8,046,160 | 14 | 2011-11-08T05:05:19Z | [
"python",
"scope"
] | Sometimes I find that I have to use functions with long names such as `os.path.abspath` and `os.path.dirname` a **lot** in just a few lines of code. I don't think it's worth littering the global namespace with such functions, but it would be incredibly helpful to be able to define a scope around the lines where I need ... | Python doesn't have a temporary namespace tool like *[let](http://www.gnu.org/software/emacs/emacs-lisp-intro/html_node/let.html)* in Lisp or Scheme.
The usual technique in Python is to put names in the current namespace and then take them out when you're done with them. This technique is used heavily in the standard ... |
Django script to access model objects without using manage.py shell | 8,047,204 | 26 | 2011-11-08T07:30:21Z | 8,047,253 | 18 | 2011-11-08T07:37:40Z | [
"python",
"django",
"django-models"
] | I'm writing a script to import some model objects into the database my django application uses. In the past I've solved this by running `./manage.py shell` and then `import myscript`. I'm sure there's a better way. I'd like to be able to call a script from anywhere on my HD using `python scriptname.py`, and in the firs... | You need to setup django environment first:
```
from your_project import settings
from django.core.management import setup_environ
setup_environ(settings)
```
At last import your models, everything goes just like django. |
Django script to access model objects without using manage.py shell | 8,047,204 | 26 | 2011-11-08T07:30:21Z | 8,047,520 | 21 | 2011-11-08T08:08:13Z | [
"python",
"django",
"django-models"
] | I'm writing a script to import some model objects into the database my django application uses. In the past I've solved this by running `./manage.py shell` and then `import myscript`. I'm sure there's a better way. I'd like to be able to call a script from anywhere on my HD using `python scriptname.py`, and in the firs... | I think the best way is to create your [custom management command(s)](https://docs.djangoproject.com/en/dev/howto/custom-management-commands/). Then you can call `manage.py <yourcommand>` from anywhere. |
Django script to access model objects without using manage.py shell | 8,047,204 | 26 | 2011-11-08T07:30:21Z | 18,760,222 | 67 | 2013-09-12T09:17:41Z | [
"python",
"django",
"django-models"
] | I'm writing a script to import some model objects into the database my django application uses. In the past I've solved this by running `./manage.py shell` and then `import myscript`. I'm sure there's a better way. I'd like to be able to call a script from anywhere on my HD using `python scriptname.py`, and in the firs... | **Since Django 1.4** you should avoid using `setup_environ(settings)` (post by Melug) because it is deprecated. Use the following instead and you will be able to access your model
```
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")
# your imports, e.g. Django models
from your_... |
Django script to access model objects without using manage.py shell | 8,047,204 | 26 | 2011-11-08T07:30:21Z | 26,875,729 | 22 | 2014-11-11T22:22:43Z | [
"python",
"django",
"django-models"
] | I'm writing a script to import some model objects into the database my django application uses. In the past I've solved this by running `./manage.py shell` and then `import myscript`. I'm sure there's a better way. I'd like to be able to call a script from anywhere on my HD using `python scriptname.py`, and in the firs... | To get models loaded too, I had to combine this with [this answer](http://stackoverflow.com/a/26215548/1591957), otherwise I get `django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet`
```
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings")
import django
django.setup()
```
... |
How to load data from a file, for a unit test, in python? | 8,047,736 | 12 | 2011-11-08T08:34:27Z | 8,049,772 | 22 | 2011-11-08T11:36:29Z | [
"python",
"unit-testing",
"file-io"
] | I've written a specialized HTML parser, that I want to unit test with a couple of sample webpages I've downloaded.
In Java, I've used class resources, to load data into unit tests, without having to rely on them being at a particular path on the file system. Is there a way to do this in Python?
I found the [doctest.t... | To load data from a file in a unittest, if the testdata is on the same dir as unittests, one solution :
```
TESTDATA_FILENAME = os.path.join(os.path.dirname(__file__), 'testdata.html')
class MyTest(unittest.TestCase)
def setUp(self):
self.testdata = open(TESTDATA_FILENAME).read()
def test_something(se... |
Web-scraping JavaScript page with Python | 8,049,520 | 31 | 2011-11-08T11:13:51Z | 26,440,563 | 44 | 2014-10-18T14:03:42Z | [
"python",
"web-scraping",
"urlopen"
] | I'm trying to develop a simple web scraper. I want to extract text without the HTML code. In fact, I achieve this goal, but I have seen that in some pages where JavaScript is loaded I didn't obtain good results.
For example, if some JavaScript code adds some text, I can't see it, because when I call
```
response = ur... | You can also use Python library [dryscrape](https://github.com/niklasb/dryscrape) to scrape javascript driven websites.
# Example
To give an example, I created a sample page with following HTML code. ([link](http://avi.im/stuff/js-or-no-js.html)):
```
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>J... |
Web-scraping JavaScript page with Python | 8,049,520 | 31 | 2011-11-08T11:13:51Z | 36,619,019 | 9 | 2016-04-14T09:31:25Z | [
"python",
"web-scraping",
"urlopen"
] | I'm trying to develop a simple web scraper. I want to extract text without the HTML code. In fact, I achieve this goal, but I have seen that in some pages where JavaScript is loaded I didn't obtain good results.
For example, if some JavaScript code adds some text, I can't see it, because when I call
```
response = ur... | Maybe [selenium](http://www.seleniumhq.org/) can do it.
```
from selenium import webdriver
import time
driver = webdriver.Firefox()
driver.get(url)
time.sleep(5)
htmlSource = driver.page_source
``` |
How can I draw text with different stroke and fill colors on images with python? | 8,049,764 | 10 | 2011-11-08T11:35:35Z | 8,050,658 | 7 | 2011-11-08T12:52:48Z | [
"python",
"image",
"python-imaging-library"
] | How can I draw text with different stroke and fill colors on images with python?
Here is some text with red stroke and gray fill.

I tried to do this with PIL but there was no option for setting the stroke color. | Using [cairo](http://cairographics.org/pycairo/) (with much code taken from [here](http://cairographics.org/samples/text/)):
```
import cairo
def text_extent(font, font_size, text, *args, **kwargs):
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 0, 0)
ctx = cairo.Context(surface)
ctx.select_font_face(f... |
Understanding nested list comprehension | 8,049,798 | 42 | 2011-11-08T11:38:53Z | 8,050,243 | 40 | 2011-11-08T12:19:20Z | [
"python",
"nested",
"list-comprehension"
] | I want to understand nested list comprehension.
Below, I listed a list comprehension expression and their for loop equivalent.
I wonder if my understanding is correct on those.
For example,
```
[(min([row[i] for row in rows]),max([row[i] for row in rows]))
for i in range(len(rows[0]))]
```
is equivalent to
```
r... | The short answer is: **yes, you are correct in your understanding**.
There's only a catch: the way you normally use nested list comprehension in python code is to operate on multidimensional arrays.
A typical example is when you operate on matrices:
```
>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> [[el - 1 for... |
Understanding nested list comprehension | 8,049,798 | 42 | 2011-11-08T11:38:53Z | 8,050,398 | 46 | 2011-11-08T12:32:02Z | [
"python",
"nested",
"list-comprehension"
] | I want to understand nested list comprehension.
Below, I listed a list comprehension expression and their for loop equivalent.
I wonder if my understanding is correct on those.
For example,
```
[(min([row[i] for row in rows]),max([row[i] for row in rows]))
for i in range(len(rows[0]))]
```
is equivalent to
```
r... | Indeed, you are correct. This is described in detail in the [Expressions section in the Python Language Reference](http://docs.python.org/reference/expressions.html#list-displays).
Note especially the order of nesting of several `for`s in a single list comprehension, which is always left-to-right:
```
>>> matrix = [[... |
Using python's logging module to log all exceptions and errors | 8,050,775 | 14 | 2011-11-08T13:01:36Z | 8,054,179 | 23 | 2011-11-08T16:58:10Z | [
"python",
"debugging"
] | I want to check for errors in a particular background file, but the standard error stream is being controlled by the program in the foreground and the errors in the file in the question are not being displayed. I can use the `logging` module and write output to a file, though. I was wondering how I can use this to log ... | It's probably a bad idea to log *any* exception thrown within the program, since Python uses exceptions also for normal control flow.
Therefore you should only log *uncaught* exceptions. You can easily do this using a logger's [`exception()` method](http://docs.python.org/library/logging.html#logging.Logger.exception)... |
Numpy: equivalent of numpy.roll but only for data visualisation | 8,050,789 | 7 | 2011-11-08T13:02:37Z | 8,050,909 | 9 | 2011-11-08T13:11:27Z | [
"python",
"numpy",
"python-2.7"
] | **Is there a way to perform a roll on an array, but instead of having a copy of the data having just a different visualisation of it?**
An example might clarify: given `b` a rolled version of `a`...
```
>>> a = np.random.randint(0, 10, (3, 3))
>>> a
array([[6, 7, 4],
[5, 4, 8],
[1, 3, 4]])
>>> b = np.ro... | This is not possible, sorry. The rolled array cannot be described by a different set of [strides](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.strides.html), which would be necessary for a NumPy view to work. |
Select divs between html comments in lxml | 8,050,929 | 3 | 2011-11-08T13:13:20Z | 8,051,031 | 7 | 2011-11-08T13:20:25Z | [
"python",
"html",
"xml",
"parsing",
"xpath"
] | This is my html file
```
<div>
<div></div>
<div></div>
<!--Comment1-->
<div>1</div>
<div>2</div>
<div>3</div>
<!--Comment2-->
<div></div>
<div></div>
<div></div>
</div>
```
and I want to select divs between Comment 1 and Comment 2
With this xPath = "/div/comment()" I can select `<!--Com... | ```
//*[preceding-sibling::comment() and following-sibling::comment()]
```
Or stricter version:
```
//*[preceding-sibling::comment()[. = 'Comment1']
and following-sibling::comment()[. = 'Comment2']]
``` |
In Python, how do I write unit tests that can access private attributes without exposing them? | 8,052,814 | 11 | 2011-11-08T15:27:13Z | 8,052,880 | 11 | 2011-11-08T15:31:17Z | [
"python",
"unit-testing",
"testing",
"tdd",
"access-modifiers"
] | I am trying to improve how I write my unit test cases for my Python programs. I am noticing in some cases, it would be really helpful to have access to private members to ensure that a method is functioning properly. An example case would be when trying to test a method for proper behavior that has no expected return v... | Nothing is private in Python. If you are using the double underscore prefix on member variables, the name is simply mangled. You can access it by qualifying the name in the form `_Class__member`. This will access the `__member` variable in the class `Class`.
See also this question: [Why are Python's 'private' methods ... |
Paramiko: Piping blocks forever on read | 8,052,840 | 8 | 2011-11-08T15:28:58Z | 8,057,995 | 11 | 2011-11-08T22:30:01Z | [
"python",
"ssh",
"paramiko"
] | I have a problem with getting piping to work with paramiko.
This works:
```
ssh = paramiko.SSHClient()
[...]
stdin, stdout, stderr = ssh.exec_command("find /tmp")
stdout.read()
```
This does **not** work (blocks forever on stdout.read()):
```
[...]
stdin, stdout, stderr = ssh.exec_command("bash -")
stdin.write("fin... | With some investigation, it appears that `stdin.close()` does not actually end the bash session. To do that, you could use the bash command `exit` (`stdin.write('exit\n')`) or dig into the paramiko `Channel` object underneath the `stdin` object:
```
stdin.channel.shutdown_write()
```
If you'd like the bash session to... |
Running subprocess within different virtualenv with python | 8,052,926 | 7 | 2011-11-08T15:33:40Z | 27,123,973 | 7 | 2014-11-25T10:16:55Z | [
"python",
"virtualenv"
] | Let's say I have 2 different versions of my app installed in 2 different virtualenvironments. myapp v1.0 and myapp v2.0.
Now I would like to compare those. The comparison is written in python itself. What would be the best way to do that? Let's assume I can run them separately and both write an output file, which I ca... | The accepted answer does not address the problem of 'activating' a virtualenv in a subprocess.
If you start your application with a call to the python executable, like in your example it is actually very simple: you only have to explicitly point to the executable in the virtualenv.
```
import subprocess
subprocess.P... |
Getting the final destination of a javascript redirect on a website | 8,053,295 | 2 | 2011-11-08T15:58:30Z | 8,066,106 | 8 | 2011-11-09T14:01:07Z | [
"python",
"urllib2"
] | I parse a website with python. They use a lot of redirects and they do them by calling javascript functions.
So when I just use urllib to parse the site, it doesn't help me, because I can't find the destination url in the returned html code.
Is there a way to access the DOM and call the correct javascript function fr... | I looked into Selenium. And if you are not running a pure script (meaning you don't have a display and can't start a "normal" browser) the solution is actually quite simple:
```
from selenium import webdriver
driver = webdriver.Firefox()
link = "http://yourlink.com"
driver.get(link)
#this waits for the new page to l... |
how do I use empty namespaces in an lxml xpath query? | 8,053,568 | 12 | 2011-11-08T16:15:43Z | 8,056,239 | 22 | 2011-11-08T19:49:55Z | [
"python",
"xml",
"xpath",
"lxml"
] | I have an xml document in the following format:
```
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:gsa="http://schemas.google.com/gsa/2007">
...
<entry>
<id>https://ip.ad.dr.ess:8000/feeds/diagnostics/smb://ip.ad.dr.ess/path/to/file</id>
<updated>... | Something like this should work:
```
import lxml.etree as et
ns = {"atom": "http://www.w3.org/2005/Atom"}
tree = et.fromstring(xml)
for node in tree.xpath('//atom:entry', namespaces=ns):
print node
```
See also <http://lxml.de/xpathxslt.html#namespaces-and-prefixes>.
Alternative:
```
for node in tree.xpath("//... |
Why is putting the module level code into a function and then calling the function is faster in Python? | 8,053,608 | 5 | 2011-11-08T16:18:52Z | 8,053,661 | 7 | 2011-11-08T16:21:19Z | [
"python",
"function",
"optimization",
"module"
] | In Alex Martelli's response to [Making a Python script Object-Oriented](http://stackoverflow.com/questions/1813117/making-a-python-script-object-oriented), he mentions that putting module level code into a function and then calling the function is faster in Python. Can someone explain why and whether it's true for all ... | This is mostly due to variable look-up. Looking up a variable in the global scope requires a dictionary look-up. In contrast, the compiler determines local names statically and references them by index, so no dictionary look up is required.
Note that in Python 2.x the presence of an `exec` statement inside a function ... |
Django multi-database routing | 8,054,195 | 25 | 2011-11-08T16:59:18Z | 8,068,326 | 14 | 2011-11-09T16:39:41Z | [
"python",
"django"
] | I have been using manual db selection to cope with a project which has two seperate dbs. I have defined my databases in the settings. After some further reading it seems that database routing is actually the way to go with this. However, after reading the docs and some relevant posts here I am more confused than ever.
... | OK, so I just solved my own problem. The router class goes into a separate file called routers.py under **/myapp2**. No **meta.app\_label** is required as I guess it is automatically assigned. Hope this helps someone. I have also documented the process [here](http://djangosteps.wordpress.com/2011/11/08/multiple-databas... |
change (eg) 8 to 08...python | 8,055,185 | 2 | 2011-11-08T18:16:56Z | 8,055,290 | 7 | 2011-11-08T18:24:45Z | [
"python",
"algorithm",
"file",
"date"
] | I am reading data from a csv file, and there are date elements in it, but there is an inconsistency in the dates.
For example: sometimes the date element is like `1/1/2011` and sometimes it is like `01/01/2011`
Since I am plotting this data later.. this causes a great deal of noise in my plots. The following is my da... | You definitely want to be using `datetime`. Here's some code that will get a datetime from either string type:
```
from datetime import datetime
def strToDatetime(dateStr):
return datetime.strptime(dateStr, "%d/%m/%Y")
```
Then, you can print a `datetime` out in the format you want with:
```
strToDatetime("1/3/... |
Smoothing Data in Contour Plot with Matplotlib | 8,055,489 | 2 | 2011-11-08T18:40:43Z | 8,055,823 | 9 | 2011-11-08T19:13:46Z | [
"python",
"matplotlib",
"scipy",
"contour",
"smoothing"
] | I am working on creating a contour plot using Matplotlib. I have all of the data
in an array that is multidimensional. It is 12 long about 2000 wide. So it is
basically a list of 12 lists that are 2000 in length. I have the contour plot
working fine, but I need to smooth the data. I have read a lot of
examples. Unfortu... | You could smooth your data with a [gaussian\_filter](http://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.filters.gaussian_filter.html#scipy.ndimage.filters.gaussian_filter):
```
import numpy as np
import matplotlib.pyplot as plt
import scipy.ndimage as ndimage
X, Y = np.mgrid[-70:70, -70:70]
Z = np.cos(... |
Immutable vs Mutable types | 8,056,130 | 84 | 2011-11-08T19:41:53Z | 8,056,219 | 20 | 2011-11-08T19:48:20Z | [
"python",
"immutability",
"mutable"
] | I'm confused on what an immutable type is. I know the `float` object is considered to be immutable, with this type of example from my book:
```
class RoundFloat(float):
def __new__(cls, val):
return float.__new__(cls, round(val, 2))
```
Is this considered to be immutable because of the class structure / h... | First of all, whether a class has methods or what it's class structure is has nothing to do with mutability.
`int`s and `float`s are *immutable*. If I do
```
a = 1
a += 5
```
It points the name `a` at a `1` somewhere in memory on the first line. On the second line, it looks up that `1`, adds `5`, gets `6`, then poin... |
Immutable vs Mutable types | 8,056,130 | 84 | 2011-11-08T19:41:53Z | 8,056,288 | 13 | 2011-11-08T19:52:44Z | [
"python",
"immutability",
"mutable"
] | I'm confused on what an immutable type is. I know the `float` object is considered to be immutable, with this type of example from my book:
```
class RoundFloat(float):
def __new__(cls, val):
return float.__new__(cls, round(val, 2))
```
Is this considered to be immutable because of the class structure / h... | Whether an object is mutable or not depends on its type. This doesn't depend on whether or not it has certain methods, nor on the structure of the class hierarchy.
User-defined types (i.e. classes) are generally mutable. There are some exceptions, such as simple sub-classes of an immutable type. Other immutable types ... |
Immutable vs Mutable types | 8,056,130 | 84 | 2011-11-08T19:41:53Z | 8,056,598 | 99 | 2011-11-08T20:19:56Z | [
"python",
"immutability",
"mutable"
] | I'm confused on what an immutable type is. I know the `float` object is considered to be immutable, with this type of example from my book:
```
class RoundFloat(float):
def __new__(cls, val):
return float.__new__(cls, round(val, 2))
```
Is this considered to be immutable because of the class structure / h... | You have to understand that Python represents all its data as objects. Some of these objects like lists and dictionaries are mutable, meaning you can change their content without changing their identity. Other objects like integers, floats, strings and tuples ... are objects that can not be changed.
An easy way to unde... |
Immutable vs Mutable types | 8,056,130 | 84 | 2011-11-08T19:41:53Z | 8,059,504 | 134 | 2011-11-09T01:50:58Z | [
"python",
"immutability",
"mutable"
] | I'm confused on what an immutable type is. I know the `float` object is considered to be immutable, with this type of example from my book:
```
class RoundFloat(float):
def __new__(cls, val):
return float.__new__(cls, round(val, 2))
```
Is this considered to be immutable because of the class structure / h... | What? Floats are immutable? But can't I do
```
x = 5.0
x += 7.0
print x # 12.0
```
Doesn't that "mut" x?
Well you agree strings are immutable right? But you can do the same thing.
```
s = 'foo'
s += 'bar'
print s # foobar
```
The value of the variable changes, but it changes by changing what the variable refers to... |
Immutable vs Mutable types | 8,056,130 | 84 | 2011-11-08T19:41:53Z | 14,451,391 | 7 | 2013-01-22T04:02:04Z | [
"python",
"immutability",
"mutable"
] | I'm confused on what an immutable type is. I know the `float` object is considered to be immutable, with this type of example from my book:
```
class RoundFloat(float):
def __new__(cls, val):
return float.__new__(cls, round(val, 2))
```
Is this considered to be immutable because of the class structure / h... | A mutable object has to have at least a method able to mutate the object. For example, the `list` object has the `append` method, which will actually mutate the object:
```
>>> a = [1,2,3]
>>> a.append('hello') # `a` has mutated but is still the same object
>>> a
[1, 2, 3, 'hello']
```
but the class `float` has no me... |
Immutable vs Mutable types | 8,056,130 | 84 | 2011-11-08T19:41:53Z | 23,715,872 | 57 | 2014-05-17T20:38:40Z | [
"python",
"immutability",
"mutable"
] | I'm confused on what an immutable type is. I know the `float` object is considered to be immutable, with this type of example from my book:
```
class RoundFloat(float):
def __new__(cls, val):
return float.__new__(cls, round(val, 2))
```
Is this considered to be immutable because of the class structure / h... | Common immutable type:
1. numbers: `int()`, `float()`, `complex()`
2. immutable sequences: `str()`, `tuple()`, `frozenset()`, `bytes()`
Common mutable type (almost everything else):
1. mutable sequences: `list()`, `bytearray()`
2. set type: `set()`
3. mapping type: `dict()`
4. classes, class instances
5. etc.
One t... |
Immutable vs Mutable types | 8,056,130 | 84 | 2011-11-08T19:41:53Z | 29,604,031 | 11 | 2015-04-13T11:19:10Z | [
"python",
"immutability",
"mutable"
] | I'm confused on what an immutable type is. I know the `float` object is considered to be immutable, with this type of example from my book:
```
class RoundFloat(float):
def __new__(cls, val):
return float.__new__(cls, round(val, 2))
```
Is this considered to be immutable because of the class structure / h... | If you're coming to Python from another language (except one that's a lot like Python, like Ruby), and insist on understanding it in terms of that other language, here's where people usually get confused:
```
>>> a = 1
>>> a = 2 # I thought int was immutable, but I just changed it?!
```
In Python, assignment is not m... |
Display image with a zoom = 1 with Matplotlib imshow() (how to?) | 8,056,458 | 12 | 2011-11-08T20:08:21Z | 8,057,182 | 14 | 2011-11-08T21:18:34Z | [
"python",
"matplotlib"
] | I want to display an image (say 800x800) with Matplotlib.pyplot imshow() function but I want to display it so that one pixel of the image occupies one pixel on the screen (zoom factor = 1, no shrink, no stretch).
I'm a beginner, so do you know how to proceed? | Matplotlib isn't optimized for this. You'd be a bit better off with simpler options if you just want to display an image at one-pixel-to-one-pixel. (Have a look at Tkinter, for example.)
That having been said:
```
import matplotlib.pyplot as plt
import numpy as np
# DPI, here, has _nothing_ to do with your screen's ... |
python get unicode string size | 8,056,496 | 9 | 2011-11-08T20:11:20Z | 8,056,573 | 23 | 2011-11-08T20:18:04Z | [
"python",
"utf-8",
"binaryfiles"
] | I have a binary file. This file contains an UTF-8 string. Moreover, it is guaranteed that this string is just a single word.
In python, how can I get number of letters in this string?
Let's say, I opened this file and read bytes:
```
bytes = open("1.dat", "rb").read()
```
What next have I to do to find out length (i... | ```
unicode_string = bytes.decode("utf-8")
print len(unicode_string)
``` |
How do numbers work in Python? | 8,057,605 | 2 | 2011-11-08T21:56:04Z | 8,057,688 | 10 | 2011-11-08T22:02:43Z | [
"python"
] | So, I open terminal.
```
> python
> 1 / 3
0
> 1.0 / 3
0.33333333333333331
```
Could someone tell me what the rules are when it comes to decimals. Does it matter which number when being divided carries the decimal? Is there a best practice?
If I want more decimal points, or less for that matter, do I need to use a fu... | The division in Python < 3.0 works like in many different programming languages and the output is an integer:
```
>>> 3 / 2
1
```
If you use **float** for **any** of the parts, the output will be a float also:
```
>>> 3.0 / 2
1.5
>>> 3 / 2.0
1.5
```
But there is a solution, if you want to do division more precisely... |
Error when running tests of scipy and numpy on OS X Snow Leopard | 8,057,777 | 5 | 2011-11-08T22:09:49Z | 8,059,075 | 7 | 2011-11-09T00:44:36Z | [
"python",
"numpy",
"osx-snow-leopard",
"scipy",
"nose"
] | I am new to stackoverflow as well as Python, and I hope to use stackoverflow to learn and improve my Python programming.
However, as soon as I set up Python, SciPy, NumPy on my Mac, I encountered a problem when I tried running a full test of SciPy and NumPy to verify the install:
```
>>> import scipy
>>> scipy.test()... | I tried replicating the error that you were encountering. I did not have nose, so I was getting the same error.
I installed nose using pip
> > sudo pip install nose
After that the scipy.test() worked. I did nothing else. Did you install nose using pip? If not, try using pip.
My machine has :
SciPy version 0.10.0... |
Installing matplotlib under Windows | 8,057,801 | 2 | 2011-11-08T22:11:33Z | 8,057,935 | 9 | 2011-11-08T22:24:21Z | [
"python",
"matplotlib"
] | I'm trying to install matplotlib under Windows Vista. Both python itself and numpy are working for me.
I installed matplotlib via the executable `basemap-1.0.2.win32-py2.7` and followed the [official instructions](http://matplotlib.sourceforge.net/users/installing.html#installing-on-windows). But running `from matplot... | basemap is not the installer for matplotlib.
basemap is a library of the matplotlib toolkit for plotting 2D data on maps, you need to indepently install matplotlib to use it.
You can get matplotlib from [here](http://sourceforge.net/projects/matplotlib/files/matplotlib/matplotlib-1.1.0/) |
Applying machine learning to a guessing game? | 8,057,936 | 21 | 2011-11-08T22:24:22Z | 8,062,594 | 16 | 2011-11-09T09:09:34Z | [
"python",
"artificial-intelligence",
"machine-learning"
] | I have a problem with a game I am making. I think I know the solution(or what solution to apply) but not sure how all the âpiecesâ fit together.
**How the game works:**
(from [How to approach number guessing game(with a twist) algorithm?](http://stackoverflow.com/questions/7694978/how-to-approach-number-guessing-... | Like you've said, this problem can be described with a HMM. You are essentially interested in maintaining a distribution over latent, or hidden, states which would be the true quantities at each time point. However, it seems you are confusing the problem of learning the parameters for a HMM opposed to simply doing infe... |
Single Line Python Webserver | 8,058,793 | 20 | 2011-11-09T00:04:44Z | 8,058,846 | 41 | 2011-11-09T00:11:18Z | [
"python"
] | I seem to remember seeing a single line implementation of a webserver a couple of years ago. **I'm aware of SimpleHTTPServer and it's like, and that's not it** - I think this was using Socket and select().
I thought it was on the Python Tutor mailing list, but an archive search hasn't revealed anything, nor has a goog... | I'm pretty sure you can't have a webserver using sockets and select() on one line of code. Not even using semicolons, you'd have to have some loops and control structures.
Are you sure this isn't what you are looking for?
```
$ python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
```
Python 3 version: `p... |
Python Interpreter in Emacs repeats lines | 8,060,609 | 10 | 2011-11-09T05:10:48Z | 8,198,737 | 9 | 2011-11-20T01:24:14Z | [
"python",
"emacs"
] | What is happening:
```
>>> 2 * 10
2 * 10
20
>>>
```
What I want to happen:
```
>>> 2 * 10
20
>>>
```
Does anyone know why the command is printed out before being executed and how to stop it from doing that? I can't find any documentation about this. I'm using Emacs 23 on Mac OS X with Python 2.7. | I don't use python, but I would guess that the python feature you are using has set the variable `comint-process-echoes` incorrectly. Whatever the value in your buffer is, just reverse the boolean value.
Comint is a support library in Emacs for running inferior processes in Emacs. It interacts with the prompts, and th... |
What in the world is the attribute "__class__" in python | 8,060,751 | 23 | 2011-11-09T05:30:58Z | 8,060,848 | 9 | 2011-11-09T05:42:49Z | [
"python",
"class"
] | I have a question about `__class__` in python.
The documentation says that `__class__` is the class to which a class instance belongs. So I conducted a series of experiments:
```
class counter:
count = 0
def __init__(self):
self.__class__.count += 1
NewCounter1 = counter()
print NewCounter1.count... | This line:
```
NewCounter2.__class__.count = 3
```
changes the static `count` of `counter`, but here:
```
NewCounter2.count = 5
```
`NewCounter2` now has its own `count` attribute that hides the static `count`;
so that line has no effect on `NewCounter1`.
This is also why `NewCounter2.__class__.count != NewCoun... |
What in the world is the attribute "__class__" in python | 8,060,751 | 23 | 2011-11-09T05:30:58Z | 8,066,942 | 16 | 2011-11-09T15:05:27Z | [
"python",
"class"
] | I have a question about `__class__` in python.
The documentation says that `__class__` is the class to which a class instance belongs. So I conducted a series of experiments:
```
class counter:
count = 0
def __init__(self):
self.__class__.count += 1
NewCounter1 = counter()
print NewCounter1.count... | > "From codes above, I thought that maybe NewCounter1.count equals NewCounter1. \_class\_.count"
The problem is that at the moment of this sentence in your question, after the only instructions:
```
NewCounter1 = counter()
NewCounter2 = counter()
NewCounter2.__class__.count = 3
```
having created **NewCounter1** and... |
Return value from Python subprocess | 8,060,878 | 8 | 2011-11-09T05:46:41Z | 8,061,918 | 7 | 2011-11-09T08:02:40Z | [
"python",
"subprocess"
] | I would like to get the output (print statements) and return status from a python subprocess along with displaying logging info. I am using Python 2.5 on Windows XP. How do I get the return code as well? Here in this extract, I am reading output so that I can redirect it to display in a wxPython `TextCtrl` in a separat... | The returncode gets returned by the `poll` call, and is also (once `poll` did not return `None`) accessible via the `returncode` attribute. You are already using this in your code, so I'm not sure what your problem with that is.
When you want to update your control while your process is running, use `readline` instead... |
Syntax error when passing unpacked argument to print in Python | 8,061,867 | 4 | 2011-11-09T07:56:14Z | 8,061,915 | 7 | 2011-11-09T08:02:10Z | [
"python",
"python-2.7",
"argument-unpacking"
] | Instead of a simple debug/log print as this:
```
print "error ", error_number
```
I would like to use a log function that I can expand when required looking something like this:
```
def log(condition, *message):
if(<do something here...>):
print(*message)
<perhaps do something more...>
```
and c... | `print` is not a function in Python 2.x. In the first snippet you are printing a tuple and the last one has invalid syntax. If you want to use the print function, you need to enable it via `from __future__ import print_function`. |
Syntax error when passing unpacked argument to print in Python | 8,061,867 | 4 | 2011-11-09T07:56:14Z | 19,610,438 | 7 | 2013-10-26T18:39:08Z | [
"python",
"python-2.7",
"argument-unpacking"
] | Instead of a simple debug/log print as this:
```
print "error ", error_number
```
I would like to use a log function that I can expand when required looking something like this:
```
def log(condition, *message):
if(<do something here...>):
print(*message)
<perhaps do something more...>
```
and c... | If you don't want to use `__future__`, you can define the logging function like this:
```
def log(condition, *message):
if(<do something here...>):
print ' '.join(str(a) for a in message)
<perhaps do something more...>
``` |
Python one class per module and packages | 8,061,930 | 5 | 2011-11-09T08:03:58Z | 8,062,064 | 13 | 2011-11-09T08:20:39Z | [
"python",
"packages"
] | I'm trying to structure my app in Python. Coming back from C#/Java background, I like the approach of one class per file. I'd like my project tree to look like this:
```
[Service]
[Database]
DbClass1.py
DbClass2.py
[Model]
DbModel1.py
DbModel2.py
TheService.py
[ServiceTests]... | Q1. You can use the 1 class per file style in Python, but this is unusual.
Q2. you'd have to use `from Service.Model import *` and do some stuff in `Service/Model/__init__.py` which is generally frowned upon. Avoid `import *` in Python
My personal advice on this: Python is *not* C#/Java. Trying to bend it to make it ... |
Can I dynamically convert an instance of one class to another? | 8,062,161 | 11 | 2011-11-09T08:31:35Z | 8,062,313 | 14 | 2011-11-09T08:44:43Z | [
"python"
] | I have a class that describe chess pieces. I make for all type piece in the Board a class for example Pawn, Queen, keen, etc...
I have a trouble in Pawn class I want to convert to Queen or other object that has a class (when pawn goto 8th row then convert to something another) how can I do this ?
```
class Pawn:
d... | It is actually possible to assign to `self.__class__` in Python, but you really have to know what you're doing. The two classes have to be compatible in some ways (both are user-defined classes, both are either old-style or new-style, and I'm not sure about the use of `__slots__`). Also, if you do `pawn.__class__ = Que... |
Python threading module import failure | 8,062,450 | 6 | 2011-11-09T08:57:23Z | 8,062,514 | 30 | 2011-11-09T09:03:03Z | [
"python",
"multithreading",
"import"
] | I'm trying to import the threading module, however, i just seem to get errors for no good reason. Here is my code:
```
import threading
class TheThread ( threading.Thread ):
def run ( self ):
print 'Insert some thread stuff here.'
print 'I\'ll be executed...yeah....'
print 'There\'s not mu... | i think that all you need is just to rename the name of your working file, because your file name is the same as module name:
> threading.py
or you have wrong threading.py file in your working directory |
Can't apply image filters on 16-bit TIFs in PIL | 8,062,564 | 2 | 2011-11-09T09:07:04Z | 8,134,764 | 10 | 2011-11-15T10:21:15Z | [
"python",
"image",
"image-processing",
"python-imaging-library"
] | I try to apply image filters using python's [PIL](http://www.pythonware.com/products/pil/). The code is straight forward:
```
im = Image.open(fnImage)
im = im.filter(ImageFilter.BLUR)
```
This code works as expected on PNGs, JPGs and on 8-bit TIFs. However, when I try to apply this code on 16-bit TIFs, I get the foll... | Your TIFF image's mode is most likely a "I;16".
In the current version of ImageFilter, kernels can only be applied to
"L" and "RGB" images (see source of ImageFilter.py)
Try converting first to another mode:
```
im.convert('L')
```
If it fails, try:
```
im.mode = 'I'
im = im.point(lambda i:i*(1./256)).convert('L').... |
ajax widgets in pyramid and chameleon | 8,063,012 | 3 | 2011-11-09T09:42:05Z | 8,064,586 | 8 | 2011-11-09T11:50:51Z | [
"python",
"ajax",
"pyramid",
"chameleon",
"template-tal"
] | I would like to be able to easily create ajax 'widgets' backed by chameleon and pyramid on the server side.
Does Pyramid provide any plumbing code that would make writing widgets easy?
My current approach is I have a home view which uses home.pt as the renderer. home.pt uses a macro base.pt which defines the page str... | A good way of dealing with this is to associate your account\_login\_widget with its own view, like:
```
@view_config(name='login_widget',
renderer='templates/account_login_widget.pt')
def login_widget(request):
return {'username': ...}
```
You should then be able to visit <http://yourapp/login_widge... |
os.mkdir's rights assigning doesn't work as expected | 8,063,836 | 7 | 2011-11-09T10:45:48Z | 8,063,890 | 7 | 2011-11-09T10:49:34Z | [
"python",
"unix"
] | I'm trying to create directory with 777 rights.
```
os.mkdir(Xmldocument.directory, 0777)
```
However what I get is 775
```
drwxrwxr-x. 2 mwysoki mwysoki 4096 Nov 9 11:38 VeloDBBrowser
```
I'm sure that I have appropriate rights because chmod 777 works just fine. | The current umask is applied here as well.
Normally, files are created with `0777` (if executable or directory) or `0666` (other files.)
Then the OS applies the current umask to this value, resulting into `0755` resp. `0644` seen on most files, as the most usual umask is `0022`.
Your solution would be to set the uma... |
Why is Clojure 10 times slower than Python for the equivalent solution of Euler 50? | 8,064,336 | 15 | 2011-11-09T11:26:51Z | 8,064,594 | 15 | 2011-11-09T11:51:11Z | [
"python",
"performance",
"clojure",
"comparison"
] | I recently started to learn Clojure and decided to practice on Euler problems to get a hang of the available data structures and practice recursion and looping.
I tried various approaches to [Problem 50](http://projecteuler.net/problem=50), but no matter what I did, finding the solution for 1000000 never finished. Aft... | I think the slowdown comes from the number of times you iterate through the sequences in `longest-seq-under`; each of those iterations takes its toll. Here's a smoking fast version, based on a combination of your code and the answer posted [here](http://clojure.roboloco.net/?p=437). Note that `primes` is lazy, so we ca... |
Create different distribution types with setup.py | 8,064,823 | 12 | 2011-11-09T12:10:10Z | 8,180,253 | 10 | 2011-11-18T09:26:52Z | [
"python",
"setuptools",
"setup.py"
] | Given the following (demonstration) project layout:
```
MyProject/
README
LICENSE
setup.py
myproject/
... # packages
extrastuff/
... # some extra data
```
How (and where) do I declare different distribution types? Especially I need these two options:
1. A distribution containing o... | I've implemented something like this before ... the `sdist` command can be extended to handle additional command line arguments and to manipulate the data files based on these. If you run `python setup.py sdist --help`, it'll include your custom command line arguments in the help, which is nice. Use the following recip... |
Kill a python process | 8,066,221 | 7 | 2011-11-09T14:08:46Z | 8,066,240 | 12 | 2011-11-09T14:10:06Z | [
"python",
"osx"
] | I wrote a python script but accidentally put an infinite while loop in my script.
How do I kill the process? I've tried `ctrl+c` but with no success.
Are there any other option to try?
I'm on Mac Os X 10.7.2 with python 2.7 | Try `Ctrl+\` to send a SIGQUIT. |
Kill a python process | 8,066,221 | 7 | 2011-11-09T14:08:46Z | 8,066,307 | 8 | 2011-11-09T14:15:50Z | [
"python",
"osx"
] | I wrote a python script but accidentally put an infinite while loop in my script.
How do I kill the process? I've tried `ctrl+c` but with no success.
Are there any other option to try?
I'm on Mac Os X 10.7.2 with python 2.7 | `ps a` to get the PID of your process. `kill -9 <pid>` to send it the unblockable SIGKILL signal.
Note that I only have a Linux box in front of me to test, so the OS X commands may be slightly different. |
ctypes vs C extension | 8,067,171 | 12 | 2011-11-09T15:21:21Z | 8,069,179 | 8 | 2011-11-09T17:42:08Z | [
"python",
"c",
"ctypes",
"overhead"
] | I have a few functions written in C for a game project. These functions get called quite a lot (about 2000-4000 times per second). The functions are written in C for raw speed.
Now, the easiest way for me to include these functions into Python is to use `ctypes`. The alternative is to write a C extension to Python aro... | I've compared the performance of a C extension vs. a ctypes wrapper. In my particular test, the difference was about 250x. There were multiple calls into the C library so the ctypes wrapper was also executing Python code. The running time for the C library was very short which made the extra overhead for Python code ev... |
Insert gives me an empty list? What is going on here? | 8,067,344 | 3 | 2011-11-09T15:33:31Z | 8,067,376 | 9 | 2011-11-09T15:35:35Z | [
"python",
"list"
] | ```
>>> numlist = ['0', '1', '2', '3', '4', '5', '6']
>>> numlist = numlist.insert(0, '-1')
>>> numlist
>>> print numlist
None
>>>
```
I don't get it - I am trying to append to the first position of the list, and it is giving me a NoneType? | `list.insert` modifies the list in-place and returns `None`. Use it like this instead:
```
>>> numlist = ['0', '1', '2', '3', '4', '5', '6']
>>> numlist.insert(0, '-1')
>>> numlist
['-1', '1', '2', '3', '4', '5', '6']
```
Also, is there any particular reason you are using quoted numbers? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.