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 |
|---|---|---|---|---|---|---|---|---|---|
Filtering on Foreign Keys in Django | 7,367,368 | 10 | 2011-09-09T20:59:06Z | 7,367,388 | 14 | 2011-09-09T21:00:56Z | [
"python",
"django",
"orm"
] | I have a few models in Django where I attach a location to each blog published:
```
class Country(models.Model):
country_name = models.TextField()
class Town(models.Model):
country = models.ForeignKey(Country)
town_name = models.CharField(max_length=192)
class Blog(models.Model):
town = models.Foreig... | ```
blog_list = Blog.objects.filter( town__country__country_name = 'Canada' ).order_by( '-id' )
``` |
login() in Django testing framework | 7,367,509 | 14 | 2011-09-09T21:15:05Z | 7,367,945 | 15 | 2011-09-09T22:06:45Z | [
"python",
"django",
"testing",
"authentication",
"login"
] | I have started using Django's testing framework, and everything was working fine until I started testing authenticated pages.
For the sake of simplicity, let's say that this is a test:
```
class SimpleTest(TestCase):
def setUp(self):
user = User.objects.create_user('temporary', 'temporary@gmail.com', 'tem... | The problem is that you're not passing `RequestContext` to your template.
Also, you probably should use the `login_required` decorator and the client built in the `TestCase` class.
I'd rewrite it like this:
```
#views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
@... |
login() in Django testing framework | 7,367,509 | 14 | 2011-09-09T21:15:05Z | 24,641,196 | 7 | 2014-07-08T20:32:14Z | [
"python",
"django",
"testing",
"authentication",
"login"
] | I have started using Django's testing framework, and everything was working fine until I started testing authenticated pages.
For the sake of simplicity, let's say that this is a test:
```
class SimpleTest(TestCase):
def setUp(self):
user = User.objects.create_user('temporary', 'temporary@gmail.com', 'tem... | It can often be useful to use a custom auth backend that bypassess any sort of authentication during testing:
```
from django.contrib.auth.models import User
class TestcaseUserBackend(object):
def authenticate(self, testcase_user=None):
return testcase_user
def get_user(self, user_id):
return... |
Django Shell No module named settings | 7,367,577 | 13 | 2011-09-09T21:21:56Z | 7,887,521 | 19 | 2011-10-25T09:54:21Z | [
"python",
"django"
] | I've deployed Django to Apache via `mod_wsgi`. Django is running fine when hosted from Apache. However, I'm trying to do some maintenance via `manage.py`, but when I try and run it, I get the error:
> Error: Could not import settings 'myproject.settings' (Is it on sys.path?): No module named settings
```
user@localho... | This can happen if your root directory name is the same as the name of one of your apps. For example here I have a directory called `bar` containing a Django project with an app also called `bar`:
```
Simons-MacBook-Pro ~/temp
$ cd bar
Simons-MacBook-Pro ~/temp/bar
$ ./manage.py shell
Error: Could not import settings... |
Calling a C# library from python | 7,367,976 | 21 | 2011-09-09T22:10:40Z | 7,368,156 | 8 | 2011-09-09T22:36:09Z | [
"c#",
"python",
"interop",
"ironpython",
"python.net"
] | Anyone can share a working example on how to call a simple C# library (actually its WPF) from python code? (I have tried using IronPython and had too much trouble with unsupported CPython library my python code is using so I thought of trying the other way around and calling my C# code from Python).
Here is the exampl... | Python for .Net (pythonnet) may be a reasonable alternative to IronPython in your situation.
<https://github.com/pythonnet/pythonnet/blob/master/README.md>
From the site:
> Note that this package does not implement Python as a first-class CLR
> language - it does not produce managed code (IL) from Python code.
> Rath... |
Calling a C# library from python | 7,367,976 | 21 | 2011-09-09T22:10:40Z | 7,375,485 | 12 | 2011-09-11T00:10:05Z | [
"c#",
"python",
"interop",
"ironpython",
"python.net"
] | Anyone can share a working example on how to call a simple C# library (actually its WPF) from python code? (I have tried using IronPython and had too much trouble with unsupported CPython library my python code is using so I thought of trying the other way around and calling my C# code from Python).
Here is the exampl... | Since your post is tagged IronPython, if you want to use the sample C# the following should work.
```
import clr
clr.AddReference('assembly name here')
from DataViewerLibrary import PlotData
p = PlotData()
p.Start()
``` |
Calling a C# library from python | 7,367,976 | 21 | 2011-09-09T22:10:40Z | 29,854,281 | 14 | 2015-04-24T17:52:45Z | [
"c#",
"python",
"interop",
"ironpython",
"python.net"
] | Anyone can share a working example on how to call a simple C# library (actually its WPF) from python code? (I have tried using IronPython and had too much trouble with unsupported CPython library my python code is using so I thought of trying the other way around and calling my C# code from Python).
Here is the exampl... | It is actually pretty easy. Just use NuGet to add the "UnmanagedExports" package to your .Net project. See <https://sites.google.com/site/robertgiesecke/Home/uploads/unmanagedexports> for details.
You can then export directly, without having to do a COM layer. Here is the sample C# code:
```
using System;
using Syste... |
Insert tabs with .join in python | 7,368,503 | 5 | 2011-09-09T23:30:55Z | 7,368,512 | 8 | 2011-09-09T23:32:33Z | [
"python"
] | This is probably basic, but I can't find a solution. I have a string, e.g.,
```
s = 'a,b,c,d'
```
I'd like to convert the commas to tabs. But using .replace, e.g.,
```
s.replace(',', '\t')
```
gives me
```
>>> s.replace(',', '\t')
'a\tb\tc\td'
```
I also tried converting to a list and then adding the tabs with a ... | ```
>>> print s.replace(',', '\t')
a b c d
```
Right now you are see'ing `repr(s.replace(',', '\t'))` in the interpreter without the print statement. `repr()` will show each actual character in a string and the interpreter uses that as the default method to print out the result of operations.
Unless you want... |
Weird behavior: Lambda inside list comprehension | 7,368,522 | 16 | 2011-09-09T23:34:24Z | 7,368,639 | 13 | 2011-09-09T23:57:27Z | [
"python",
"lambda",
"list-comprehension"
] | In python 2.6:
```
[x() for x in [lambda: m for m in [1,2,3]]]
```
results in:
```
[3, 3, 3]
```
I would expect the output to be [1, 2, 3]. I get the exact same problem even with a non list comprehension approach. And even after I copy m into a different variable.
What am I missing? | To make the lambdas remember the value of `m`, you could use an argument with a default value:
```
[x() for x in [lambda m=m: m for m in [1,2,3]]]
# [1, 2, 3]
```
This works because default values are set once, at definition time. Each lambda now uses its own default value of `m` instead of looking for `m`'s value in... |
Getting a JSON request in a view (using Django) | 7,368,669 | 3 | 2011-09-10T00:04:20Z | 7,368,826 | 7 | 2011-09-10T00:33:58Z | [
"python",
"django",
"json",
"api"
] | I am trying to set up a view to received a JSON notification from an API. I'm trying to figure out how to get the JSON data, and I currently have this as a starting point to see that the request is being properly received:
```
def api_response(request):
print request
return HttpResponse('')
```
I know the JSO... | This is how I did it:
```
def api_response(request):
try:
data=json.loads(request.raw_post_data)
label=data['label']
url=data['url']
print label, url
except:
print 'nope'
return HttpResponse('')
``` |
Numpy and 16-bit PGM | 7,368,739 | 8 | 2011-09-10T00:18:02Z | 7,369,986 | 13 | 2011-09-10T06:10:48Z | [
"python",
"numpy",
"16-bit",
"pgm"
] | What is an efficient and clear way to read 16-bit PGM images in Python with numpy?
I cannot use PIL to load 16-bit PGM images [due to a PIL bug](http://stackoverflow.com/questions/7363735/python-and-16-bit-pgm). I can read in the header with the following code:
```
dt = np.dtype([('type', 'a2'),
('spac... | ```
import re
import numpy
def read_pgm(filename, byteorder='>'):
"""Return image data from a raw PGM file as numpy array.
Format specification: http://netpbm.sourceforge.net/doc/pgm.html
"""
with open(filename, 'rb') as f:
buffer = f.read()
try:
header, width, height, maxval = re... |
Using boto library on S3 | 7,368,999 | 3 | 2011-09-10T01:14:00Z | 7,369,491 | 11 | 2011-09-10T03:49:51Z | [
"python",
"amazon-s3",
"boto"
] | Is there a way to change the key of an S3 file? For example, I want to be able to do the equivalent of:
```
>>> from boto.s3.key import Key
>>> k=Key(bucket)
>>> k.key='cli-images/image-thumb.jpg' # this is the original key
>>> k.key='cli-images/moved/image-thumb.jpg' # this is the key I want to change it to
>>> k.sav... | just copy the object to the same bucket and delete the original one:
```
from boto.s3.key import Key
k=Key(bucket)
k.key='cli-images/image-thumb.jpg'
k.copy('bucketname', 'cli-images/moved/image-thumb.jpg')
k.delete()
``` |
Copy keys to a new dictionary (Python) | 7,369,247 | 6 | 2011-09-10T02:33:22Z | 7,369,284 | 8 | 2011-09-10T02:44:47Z | [
"python",
"dictionary"
] | I'm reading a csv file, using DictReader(). The function returns a dictionary, where the header items are the keys and the cells are the values. Pretty cool.
But I'm trying to account for rows where the data may not be what I expect it to be. In that case (I'm catching a ValueError exception), I would like the rows th... | You are close. Try:
`dict.fromkeys(my_csv_dict.keys(),[])`
This will initialize a dictionary with the same keys that you parsed from your CSV file, and each one will map to an empty list (to which, I assume, you will append your suspect row values).
---
Try this. (There are several subtler changes here that are all... |
Measure time elapsed in Python? | 7,370,801 | 260 | 2011-09-10T09:21:02Z | 7,370,824 | 364 | 2011-09-10T09:26:56Z | [
"python",
"performance",
"measure",
"timeit"
] | What I want is to start counting time somewhere in my code and then get the passed time, to measure the time it took to execute few function. I think I'm using the timeit module wrong, but the docs are just confusing for me.
```
import timeit
start = timeit.timeit()
print "hello"
end = timeit.timeit()
print end - sta... | If you just want to measure the elapsed wall-clock time between two points, you could use [`time.time()`](http://docs.python.org/library/time.html#time.time):
```
import time
start = time.time()
print("hello")
end = time.time()
print(end - start)
```
This gives the execution time in seconds.
**edit** A better optio... |
Measure time elapsed in Python? | 7,370,801 | 260 | 2011-09-10T09:21:02Z | 7,370,883 | 18 | 2011-09-10T09:38:51Z | [
"python",
"performance",
"measure",
"timeit"
] | What I want is to start counting time somewhere in my code and then get the passed time, to measure the time it took to execute few function. I think I'm using the timeit module wrong, but the docs are just confusing for me.
```
import timeit
start = timeit.timeit()
print "hello"
end = timeit.timeit()
print end - sta... | Using `time.time` to measure execution gives you the overall execution time of your commands including running time spent by other processes on your computer. It is the time the user notices, but is not good if you want to compare different code snippets / algorithms / functions / ...
More information on `timeit`:
* ... |
Measure time elapsed in Python? | 7,370,801 | 260 | 2011-09-10T09:21:02Z | 7,370,980 | 48 | 2011-09-10T10:04:03Z | [
"python",
"performance",
"measure",
"timeit"
] | What I want is to start counting time somewhere in my code and then get the passed time, to measure the time it took to execute few function. I think I'm using the timeit module wrong, but the docs are just confusing for me.
```
import timeit
start = timeit.timeit()
print "hello"
end = timeit.timeit()
print end - sta... | Given a function you'd like to time,
test.py:
```
def foo():
# print "hello"
return "hello"
```
the easiest way to use `timeit` is to call it from the command line:
```
% python -mtimeit -s'import test' 'test.foo()'
1000000 loops, best of 3: 0.254 usec per loop
```
Do not try to use `time.time` or `tim... |
Measure time elapsed in Python? | 7,370,801 | 260 | 2011-09-10T09:21:02Z | 20,791,871 | 9 | 2013-12-26T22:03:36Z | [
"python",
"performance",
"measure",
"timeit"
] | What I want is to start counting time somewhere in my code and then get the passed time, to measure the time it took to execute few function. I think I'm using the timeit module wrong, but the docs are just confusing for me.
```
import timeit
start = timeit.timeit()
print "hello"
end = timeit.timeit()
print end - sta... | The python cProfile and pstats modules offer great support for measuring time elapsed in certain functions without having to add any code around the existing functions.
For example if you have a python script timeFunctions.py:
```
import time
def hello():
print "Hello :)"
time.sleep(0.1)
def thankyou():
... |
Measure time elapsed in Python? | 7,370,801 | 260 | 2011-09-10T09:21:02Z | 21,455,138 | 39 | 2014-01-30T11:25:57Z | [
"python",
"performance",
"measure",
"timeit"
] | What I want is to start counting time somewhere in my code and then get the passed time, to measure the time it took to execute few function. I think I'm using the timeit module wrong, but the docs are just confusing for me.
```
import timeit
start = timeit.timeit()
print "hello"
end = timeit.timeit()
print end - sta... | # Python 3 only:
Since time.clock() [is deprecated as of Python 3.3](https://docs.python.org/3.3/library/time.html#time.clock), you will want to use [`time.perf_counter()`](https://docs.python.org/3/library/time.html#time.perf_counter) for system-wide timing, or [`time.process_time()`](https://docs.python.org/3/librar... |
Measure time elapsed in Python? | 7,370,801 | 260 | 2011-09-10T09:21:02Z | 25,823,885 | 74 | 2014-09-13T13:54:38Z | [
"python",
"performance",
"measure",
"timeit"
] | What I want is to start counting time somewhere in my code and then get the passed time, to measure the time it took to execute few function. I think I'm using the timeit module wrong, but the docs are just confusing for me.
```
import timeit
start = timeit.timeit()
print "hello"
end = timeit.timeit()
print end - sta... | Use `timeit.default_timer` instead of `timeit.timeit`. The former provides the best clock available on your platform and version of Python automatically:
```
from timeit import default_timer as timer
start = timer()
# ...
end = timer()
print(end - start)
```
[timeit.default\_timer](http://docs.python.org/2/library/t... |
Measure time elapsed in Python? | 7,370,801 | 260 | 2011-09-10T09:21:02Z | 30,024,601 | 12 | 2015-05-04T07:18:41Z | [
"python",
"performance",
"measure",
"timeit"
] | What I want is to start counting time somewhere in my code and then get the passed time, to measure the time it took to execute few function. I think I'm using the timeit module wrong, but the docs are just confusing for me.
```
import timeit
start = timeit.timeit()
print "hello"
end = timeit.timeit()
print end - sta... | It's fun to do this with a context-manager that automatically remembers the start time upon entry to a `with` block, then freezes the end time on block exit. With a little trickery, you can even get a running elapsed-time tally inside the block from the same context-manager function.
The core library doesn't have this... |
Retrieving binary file content using Javascript, base64 encode it and reverse-decode it using Python | 7,370,943 | 32 | 2011-09-10T09:55:11Z | 7,372,816 | 65 | 2011-09-10T15:45:40Z | [
"javascript",
"python",
"encoding",
"xmlhttprequest",
"base64"
] | I'm trying to download a binary file using `XMLHttpRequest` (using a recent Webkit) and base64-encode its contents using this simple function:
```
function getBinary(file){
var xhr = new XMLHttpRequest();
xhr.open("GET", file, false);
xhr.overrideMimeType("text/plain; charset=x-user-defined");
xh... | So I'm answering to myself â and sorry for that â but I think it might be useful for someone as lost as I was ;)
So you have to use [ArrayBuffer](https://developer.mozilla.org/en/JavaScript_typed_arrays/ArrayBuffer) and set the `responseType` property of your `XMLHttpRequest` object instance to `arraybuffer` for... |
Using self.* as default value for a method | 7,371,244 | 14 | 2011-09-10T10:59:53Z | 7,371,254 | 16 | 2011-09-10T11:01:18Z | [
"python"
] | ```
def save_file(self, outputfilename = self.image_filename):
self.file.read(outputfilename)
....
```
gives `NameError: name 'self' is not defined`in the first line. It seems that Python doesn't accept it. How can I rewrite the code, so that I does not violate the rules?
...
Please feel free to add tags or ... | Use a default of `None` and detect that.
```
def save_file(self, outputfilename=None):
if outputfilename is None:
outputfilename = self.image_filename
self.file.read(outputfilename)
....
``` |
Using self.* as default value for a method | 7,371,244 | 14 | 2011-09-10T10:59:53Z | 7,371,358 | 8 | 2011-09-10T11:21:24Z | [
"python"
] | ```
def save_file(self, outputfilename = self.image_filename):
self.file.read(outputfilename)
....
```
gives `NameError: name 'self' is not defined`in the first line. It seems that Python doesn't accept it. How can I rewrite the code, so that I does not violate the rules?
...
Please feel free to add tags or ... | The [documentation](http://docs.python.org/reference/compound_stmts.html) states:
> Default parameter values are evaluated when the function definition is executed.
This explains why the instance cannot be referenced. As others have said, use None as your default and fix up the value at function execution time when t... |
Sort a string in lexicographic order python | 7,371,935 | 7 | 2011-09-10T13:17:22Z | 7,372,478 | 15 | 2011-09-10T14:45:53Z | [
"python",
"sorting",
"lambda"
] | I want to sort a string to a list in lexicographic order as
```
str='aAaBbcCdE'
```
to
```
['A','a','a','B','b','C','c','d','E']
```
but `sorted()` gives me this output:
```
['A','B','C','E','a','a','b','c','d']
```
How can I sort lexicographically? | Do not use lambda functions when there's builtin ones for the job. Also never use the `cmp` argument of sorted because it's deprecated:
```
sorted(s, key=str.lower)
```
or
```
sorted(s, key=str.upper)
```
But that may not keep 'A' and 'a' in order, so:
```
sorted(sorted(s), key=str.upper)
```
that will and, by th... |
How to make a 2d numpy array a 3d array? | 7,372,316 | 4 | 2011-09-10T14:17:43Z | 7,372,678 | 12 | 2011-09-10T15:24:22Z | [
"python",
"multidimensional-array",
"numpy"
] | I have a 2d array with shape (x, y) which I want to convert to a 3d array with shape (x, y, 1). Is there a nice Pythonic way to do this? | In addition to the other answers, you can also use slicing with [`numpy.newaxis`](http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#numpy.newaxis):
```
>>> from numpy import zeros, newaxis
>>> a = zeros((6, 8))
>>> a.shape
(6, 8)
>>> b = a[:, :, newaxis]
>>> b.shape
(6, 8, 1)
```
Or even this (which will... |
Python: How can I execute a jar file through a python script | 7,372,592 | 14 | 2011-09-10T15:08:22Z | 7,372,651 | 23 | 2011-09-10T15:19:17Z | [
"java",
"python",
"jar"
] | I have been looking for an answer for how to execute a java jar file through python and after looking at:
[Execute .jar from Python](http://stackoverflow.com/questions/5532481/execute-jar-from-python)
[How can I get my python (version 2.5) script to run a jar file inside a folder instead of from command line?](http:/... | I would use subprocess this way:
```
import subprocess
subprocess.call(['java', '-jar', 'Blender.jar'])
```
But, if you have a properly configured `/proc/sys/fs/binfmt_misc/jar` you should be able to run the jar directly, as you wrote.
So, which is exactly the error you are getting?
Please post somewhere all the out... |
parsing excel documents with python | 7,372,716 | 23 | 2011-09-10T15:30:43Z | 7,372,812 | 32 | 2011-09-10T15:44:58Z | [
"python",
"excel",
"parsing"
] | I want to parse excel document to lists in Python.
Is there a python library which is helpful for this action?
And what functions are relevant in that library? | You're best bet for parsing Excel files would be the [xlrd](http://pypi.python.org/pypi/xlrd) library. The [python-excel.org](http://www.python-excel.org/) site has links and examples for [xlrd](http://pypi.python.org/pypi/xlrd) and related python excel libraries, including a [pdf document](http://www.simplistix.co.uk/... |
Attribute getters in python | 7,373,219 | 5 | 2011-09-10T17:05:03Z | 7,373,249 | 10 | 2011-09-10T17:09:13Z | [
"python"
] | I vaguely remember learning about some sort of built-in function that would do the equivalent of
```
f = lambda x: x.attr
```
Am I just imagining this or does such a thing exist? | [`operator.attrgetter()`](http://docs.python.org/library/operator.html#operator.attrgetter) |
get the DST boundaries of a given timezone in python | 7,373,389 | 6 | 2011-09-10T17:30:39Z | 7,373,550 | 11 | 2011-09-10T17:56:14Z | [
"python",
"pytz"
] | Is it possible to get the DST boundaries of a given timezone with pytz? | It doesn't seem to be officially supported. However, you can poke at the internals of a `DstTzInfo` object and get it from there:
```
>>> from pytz import timezone
>>> tz = timezone('Europe/London')
>>> tz._utc_transition_times
[datetime.datetime(1, 1, 1, 0, 0), datetime.datetime(1916, 5, 21, 2, 0),
...
datetime.datet... |
Using same function as instance and classmethod in python | 7,373,648 | 2 | 2011-09-10T18:12:16Z | 14,642,782 | 7 | 2013-02-01T09:04:25Z | [
"python",
"decorator",
"instance",
"class-method"
] | One can do something like this:
```
class master:
@combomethod
def foo(param):
param.bar() # Param could be type as well as object
class slaveClass( master ):
@classmethod
def bar(cls):
print("This is class method")
slaveType = slaveClass
slaveType.foo()
class slaveInstance( master... | use this:
```
class A(object):
@classmethod
def print(cls):
print 'A'
def __print(self):
print 'B'
def __init__(self):
self.print = self.__print
a = A()
a.print()
A.print()
``` |
Making python imports more structured? | 7,374,100 | 2 | 2011-09-10T19:32:31Z | 7,374,418 | 7 | 2011-09-10T20:18:39Z | [
"python",
"import"
] | The code works but looks messy so this might be a code review question where I didn't study enough of pythons conventions to know how to structure and organize the beginning of my file more pythonic. I basically just pasted in imports so they could be duplicates, not needed anymore or wrongly ordered. Can you advice an... | [PEP 8 - Style Guide for Python code](http://www.python.org/dev/peps/pep-0008/) recomends to order your imports in fallowing order:
```
1. Standart library imports
2. - blank line -
3. google sdk imports
4. - blank line -
5. django imports
6. - blank line -
7. your own code imports
```
Import only things you use in c... |
Sublime Text 2 & PYTHONPATH | 7,374,597 | 8 | 2011-09-10T20:46:40Z | 11,120,411 | 13 | 2012-06-20T13:14:39Z | [
"python",
"sublimetext2"
] | When running a python script on Sublime Text 2 (OSX), the python interpreter works (using Enthought Python Distribution) but not my own PYTHONPATH. Here's what the Python.sublime-build file looks like at the moment:
```
{
"path": "/Library/Frameworks/EPD64.framework/Versions/Current/bin/",
"cmd": ["python2.7", "-u", "... | I'm working with SublimeText2 build 2202 (I have a license and I can download all the "nightly" releases) and I add an "env" attribute to the builder.
For example:
```
{
"path": "/Library/Frameworks/EPD64.framework/Versions/Current/bin/",
"cmd": ["python2.7", "-u", "$file"],
"env":
{
"PYTHONPA... |
What's the difference between a Python "property" and "attribute"? | 7,374,748 | 57 | 2011-09-10T21:15:34Z | 7,374,811 | 15 | 2011-09-10T21:28:19Z | [
"python"
] | I am generally confused about the difference between a "property" and an "attribute", and can't find a great resource to concisely detail the differences. | In general speaking terms a property and an attribute are the same thing. However, there is a property decorator in Python which provides getter/setter access to an attribute (or other data).
```
class MyObject(object):
# This is a normal attribute
foo = 1
@property
def bar(self):
return self.... |
What's the difference between a Python "property" and "attribute"? | 7,374,748 | 57 | 2011-09-10T21:15:34Z | 7,374,831 | 12 | 2011-09-10T21:30:24Z | [
"python"
] | I am generally confused about the difference between a "property" and an "attribute", and can't find a great resource to concisely detail the differences. | With a property you have complete control on his getter, setter and deleter methods, thing you don't have (if not using caveats) with an attribute.
```
class A(object):
_x = 0
'''A._x is an attribute'''
@property
def x(self):
'''
A.x is a property
This is the getter method
... |
What's the difference between a Python "property" and "attribute"? | 7,374,748 | 57 | 2011-09-10T21:15:34Z | 7,374,892 | 8 | 2011-09-10T21:43:38Z | [
"python"
] | I am generally confused about the difference between a "property" and an "attribute", and can't find a great resource to concisely detail the differences. | The property allows you to get and set values like you would normal attributes, but underneath there is a method being called translating it into a getter and setter for you. It's really just a convenience to cut down on the boilerplate of calling getters and setters.
Lets say for example, you had a class that held so... |
What's the difference between a Python "property" and "attribute"? | 7,374,748 | 57 | 2011-09-10T21:15:34Z | 7,377,013 | 82 | 2011-09-11T07:56:36Z | [
"python"
] | I am generally confused about the difference between a "property" and an "attribute", and can't find a great resource to concisely detail the differences. | Properties are a special kind of attribute. Basically, when Python encounters the following code:
```
spam = SomeObject()
print(spam.eggs)
```
it looks up `eggs` in `spam`, and then examines `eggs` to see if it has a `__get__`, `__set__`, or `__delete__` method — if it does, it's a property. If it *is* a property, in... |
Python, Brew, and MySQLdb | 7,375,199 | 7 | 2011-09-10T22:51:35Z | 7,376,436 | 14 | 2011-09-11T05:18:33Z | [
"python",
"mysql",
"mysql-python",
"homebrew"
] | I have been running python from a brew install. I went to install the mysql\_python egg with setup tools (standard install according to mysql\_python instructions) and it installed to /usr/local/lib/python2.7/site-packages/. The dependencies processed, etc.
Then I went to run python console. I can import other things ... | In trying to duplicate your error I did the following (I assume, being a homebrewer, you have done the same).
1) `brew install python` To install Python 2.7
2) `brew install mysql` To install mysql to the system (needed for various drivers)
3) Configured mysql per homebrew's recommendations
4) Downloaded [mysql\... |
ipython complaining about readline | 7,375,545 | 24 | 2011-09-11T00:26:58Z | 7,376,930 | 37 | 2011-09-11T07:37:10Z | [
"python"
] | When I install ipython on my osx and run it, I get the following warning:
```
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/
site-packages/IPython/utils/rlineimpl.py:96:
RuntimeWarning: Leopard libedit detected - readline will not be wel
behaved including some crashes on tab completion, and incor... | When pip installs readline, it will never be imported, because readline.so goes in site-packages, which ends up behind the libedit System one, located in `lib-dynload` (OSX Python path order is very odd). `easy_install -a readline` will actually install usable readline.
So you can either use easy\_install, or use pip ... |
Class with Object as a parameter | 7,375,595 | 36 | 2011-09-11T00:39:45Z | 7,375,605 | 9 | 2011-09-11T00:42:34Z | [
"python"
] | I'm trying to translate some python code to scala code. So I'm a total noob in Python.
But why do some classes have object as a parameter but never explicitly use it? What's the reasoning for having it as a parameter in the first place?
Example:
```
class Table(object)
```
Thank you for your time. | The `Table` class is extending a class called `object`. It's not an argument. The reason you may want to extend `object` explicitly is it turns the class into a new-style class. If you don't explicitly specify it extends `object`, until Python 3, it will default to being an old-style class. (Since Python 3, all classes... |
Class with Object as a parameter | 7,375,595 | 36 | 2011-09-11T00:39:45Z | 7,375,621 | 39 | 2011-09-11T00:46:21Z | [
"python"
] | I'm trying to translate some python code to scala code. So I'm a total noob in Python.
But why do some classes have object as a parameter but never explicitly use it? What's the reasoning for having it as a parameter in the first place?
Example:
```
class Table(object)
```
Thank you for your time. | In Python2 this declares `Table` to be a [new-style class](http://www.python.org/doc/newstyle/) (as opposed to "classic" class).
In Python3 all classes are new-style classes, so this is no longer necessary.
New style classes have a few special attributes that classic classes lack.
```
class Classic: pass
class NewSty... |
list extend() to index, inserting list elements not only to the end | 7,376,019 | 12 | 2011-09-11T02:48:01Z | 7,376,026 | 34 | 2011-09-11T02:51:13Z | [
"python",
"list",
"insert"
] | I'm looking for the most pythonic way to implement a version of the list `extend` function, where it extends to a given index instead of the end of the list.
```
a_list = [ "I", "rad", "list" ]
b_list = [ "am", "a" ]
a_list.my_extend( b_list, 1 ) # insert the item... | Sure, you can use slice indexing:
```
a_list[1:1] = b_list
```
Just to demonstrate the general algorithm, if you were to implement the `my_extend` function in a hypothetical custom `list` class, it would look like this:
```
def my_extend(self, other_list, index):
self[index:index] = other_list
```
But don't act... |
axis range in scatter graphs | 7,376,330 | 4 | 2011-09-11T04:39:57Z | 7,379,830 | 15 | 2011-09-11T17:02:54Z | [
"python",
"matplotlib",
"limit",
"scatter"
] | I have been using the code below to plot the time spent to run 4 functions. The x axis represents the number of executions whereas the y axis represents the time spent
running a function.
I was wondering if you could help me accomplish the following:
1) set the limits of the x axis so that only positive values are sh... | You need to call [`legend`](http://matplotlib.sourceforge.net/users/legend_guide.html) for the legend to appear. The `label` kwarg only sets the `_label` attribute on the artist object in question. It's there for convenience, so that the label in the legend can be clearly associated with the plotting command. It won't ... |
Is there a Python module where I could easily convert mixed fractions into a float? | 7,376,342 | 4 | 2011-09-11T04:45:02Z | 7,376,362 | 8 | 2011-09-11T04:51:53Z | [
"python",
"python-3.x"
] | I'm just wondering if I could easily convert a mixed number (entered as a number or a string) into a floating point number or an integer. I've looked at the fractions module but it seems like it couldn't do what I want, or I didn't read well.
Just wanted to know if something already exists before I write my own functi... | The built-in [`Fraction`](http://docs.python.org/py3k/library/fractions.html) class does not appear to support mixed fractions like you have, but it wouldn't be too hard to split them up on the space. For example, `1 + fractions.Fraction('1/2')` or a very simplistic
```
def convert(f):
whole, frac = f.split()
... |
Mark block based on indentation level in Vim | 7,377,771 | 8 | 2011-09-11T11:02:34Z | 7,378,444 | 7 | 2011-09-11T13:20:41Z | [
"python",
"vim",
"haskell",
"whitespace",
"macvim"
] | Is it possible to mark a block in Vim based on the indentation already in place? Similarly to v{ .
It would be extremely useful for programming languages with whitespace-sensitive syntax (like Haskell and Python).
For example mark everything between the first let and return in this function:
```
checkArg (com:arg) s... | I use the [indent object plugin](http://www.vim.org/scripts/script.php?script_id=3037):
> This plugin defines a new text object, based on indentation levels.
> This is very useful in languages such as Python, in which the syntax
> defines scope in terms of indentation. Using the objects defined in
> this plugin, an en... |
Taking multiple inputs from user in python | 7,378,091 | 4 | 2011-09-11T12:12:47Z | 7,388,131 | 8 | 2011-09-12T12:49:17Z | [
"python"
] | i know how to take a single input from user in python 2.5:
```
raw_input("enter 1st number")
```
this opens up one input screen and takes in the first number. if i want to take a second input i need to repeat the same command and that opens up in another dialogue box.
How can i take two or more inputs together in the... | How about something like this?
```
input = raw_input("Enter three numbers separated by commas: ")
input_list = input.split(',')
numbers = [float(x.strip()) for x in input_list]
```
(You would probably want some error handling too) |
Taking multiple inputs from user in python | 7,378,091 | 4 | 2011-09-11T12:12:47Z | 16,200,835 | 7 | 2013-04-24T19:44:48Z | [
"python"
] | i know how to take a single input from user in python 2.5:
```
raw_input("enter 1st number")
```
this opens up one input screen and takes in the first number. if i want to take a second input i need to repeat the same command and that opens up in another dialogue box.
How can i take two or more inputs together in the... | This might prove useful:
```
a,b=map(int,raw_input().split())
```
You can then use 'a' and 'b' separately. |
Generate all subsets of size k (containing k elements) in Python | 7,378,180 | 8 | 2011-09-11T12:30:59Z | 7,378,313 | 17 | 2011-09-11T12:54:15Z | [
"python",
"set",
"tuples",
"subset"
] | I have a set of values and would like to create list of all subsets containing 2 elements.
For example, a source set `([1,2,3])` has the following 2-element subsets:
```
set([1,2]), set([1,3]), set([2,3])
```
Is there a way to do this in python? | Seems like you want `itertools.combinations`:
```
>>> list(itertools.combinations((1, 2, 3), 2))
[(1, 2), (1, 3), (2, 3)]
```
If you want sets you'll have to convert them explicitly.
```
>>> s = set((1, 2, 3))
>>> map(set, itertools.combinations(s, 2))
[set([1, 2]), set([1, 3]), set([2, 3])]
``` |
android python scripting: GUI? | 7,378,662 | 10 | 2011-09-11T13:52:12Z | 7,749,792 | 11 | 2011-10-13T05:21:50Z | [
"android",
"python",
"ase",
"sl4a"
] | Are there basic GUI functions in SL4A? I'd like to run a python program on Android and would need a listbox and simple dialogs (display info and get input).
There seem to be simple dialogs, but I haven't found a listbox. If there isn't a listbox, I should be able to create one if there's the ability to write text and ... | Essentially there are three things you can do:
1. If you just want simple Android lists and inputs, such as getting a user's input (e.g., a username and password) or showing a list of option to choose from, then there are some tutorials here: <http://code.google.com/p/android-scripting/wiki/UiExamples>
2. If you want ... |
android python scripting: GUI? | 7,378,662 | 10 | 2011-09-11T13:52:12Z | 11,358,798 | 10 | 2012-07-06T08:42:14Z | [
"android",
"python",
"ase",
"sl4a"
] | Are there basic GUI functions in SL4A? I'd like to run a python program on Android and would need a listbox and simple dialogs (display info and get input).
There seem to be simple dialogs, but I haven't found a listbox. If there isn't a listbox, I should be able to create one if there's the ability to write text and ... | If you want a python GUI solution on Android/iOS/Linux/Windows/Mac you can use kivy... its nice!
[kivy.org](http://kivy.org) |
How to parse this huge XML file with nested elements using lxml the efficient way? | 7,380,215 | 7 | 2011-09-11T18:00:22Z | 7,380,696 | 7 | 2011-09-11T19:32:09Z | [
"python",
"xml",
"lxml",
"iterparse"
] | I tried parsing this huge XML document using [XML minidom](http://stackoverflow.com/questions/7327924/how-to-efficiently-store-this-parsed-xml-document-in-mysql-database-using-python). While it worked fine on a sample file, it choked the system when trying to process the real file (about 400 MB).
I tried adapting code... | You might try something like this:
```
import MySQLdb
from lxml import etree
import config
def fast_iter(context, func, args=[], kwargs={}):
# http://www.ibm.com/developerworks/xml/library/x-hiperfparse/
# Author: Liza Daly
for event, elem in context:
func(elem, *args, **kwargs)
elem.c... |
Byte Array in Python | 7,380,460 | 27 | 2011-09-11T18:45:07Z | 7,380,493 | 26 | 2011-09-11T18:50:03Z | [
"python",
"byte",
"gevent"
] | How can I represent a byte array (like in Java with byte[]) in Python? I'll need to send it over the wire with gevent.
```
byte key[] = {0x13, 0x00, 0x00, 0x00, 0x08, 0x00};
``` | In Python 3, we use the `bytes` object, also known as `str` in Python 2.
```
# Python 3
key = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
# Python 2
key = ''.join(chr(x) for x in [0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
```
I find it more convenient to use the `base64` module...
```
# Python 3
key = base64.b16decode(b... |
Byte Array in Python | 7,380,460 | 27 | 2011-09-11T18:45:07Z | 7,380,573 | 13 | 2011-09-11T19:06:55Z | [
"python",
"byte",
"gevent"
] | How can I represent a byte array (like in Java with byte[]) in Python? I'll need to send it over the wire with gevent.
```
byte key[] = {0x13, 0x00, 0x00, 0x00, 0x08, 0x00};
``` | Just use a `bytearray` (Python 2.6 and later) which represents a mutable sequence of bytes
```
>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> key
bytearray(b'\x13\x00\x00\x00\x08\x00')
```
Indexing get and sets the individual bytes
```
>>> key[0]
19
>>> key[1]=0xff
>>> key
bytearray(b'\x13\xff\x00\x00... |
Django SECRET_KEY | 7,382,149 | 69 | 2011-09-11T23:59:01Z | 7,382,198 | 56 | 2011-09-12T00:09:44Z | [
"python",
"django",
"security",
"encryption"
] | What exactly is the point of the `SECRET_KEY` in django? I did a few google searches and checked out the docs ( <https://docs.djangoproject.com/en/dev/ref/settings/#secret-key> ), but I was looking for a more in-depth explanation of this, and why it is required.
For example, what could happen if the key was compromise... | It is used for making hashes. Look:
```
>grep -Inr SECRET_KEY *
conf/global_settings.py:255:SECRET_KEY = ''
conf/project_template/settings.py:61:SECRET_KEY = ''
contrib/auth/tokens.py:54: hash = sha_constructor(settings.SECRET_KEY + unicode(user.id) +
contrib/comments/forms.py:86: info = (content_type, o... |
Python variable scope in if-statements | 7,382,638 | 15 | 2011-09-12T01:53:50Z | 7,382,643 | 30 | 2011-09-12T01:55:23Z | [
"python"
] | In Python, are variable scopes inside if-statements visible outside of the if-statement? (coming from a Java background, so find this a bit odd)
In the following case, name is first defined inside the if-block but the variable is visible outside of the if-block as well. I was expecting an error to occur but 'joe' gets... | `if` statements don't define a scope in Python.
Neither do loops, `with` statements, `try` / `except`, etc.
Only modules, functions and classes define scopes.
See [Python Scopes and Namespaces](http://docs.python.org/tutorial/classes.html#python-scopes-and-namespaces) in the Python Tutorial. |
Serving css file from CherryPy | 7,383,069 | 3 | 2011-09-12T03:39:47Z | 7,390,842 | 11 | 2011-09-12T16:12:50Z | [
"python",
"css",
"cherrypy"
] | I'm having a devil of a time getting CherryPy to serve the necessary css file for the page returned.
My directory structure:
```
Application
ab.py (CherryPy application)
ab.config (CherryPy config file)
html\ (html template folder)
ab.html (html templa... | **Change it quickly!** The static handlers take paths that are **absolute to your filesystem**. By setting `tools.staticdir.root = "/"` you are saying "serve any file from my hard drive".
Whew. Now that the panic is over, let's analyze in more detail. First of all, staticdir and staticfile are different tools, and don... |
How to use the "native" GUI look with Tkinter? | 7,385,343 | 13 | 2011-09-12T08:50:52Z | 7,385,518 | 14 | 2011-09-12T09:04:22Z | [
"python",
"windows",
"tkinter"
] | By default Tkinter still uses the old Windows 2000-style widgets (random example):

but I want it to use the Windows XP/Vista/7-style widgets instead:

How can I do this? I would prefer to use t... | On Windows, use [tkinter.ttk](http://docs.python.org/py3k/library/tkinter.ttk.html) to get the the themed version of Tk. |
Make matplotlib autoscaling ignore some of the plots | 7,386,872 | 5 | 2011-09-12T11:03:33Z | 7,396,313 | 8 | 2011-09-13T02:52:10Z | [
"python",
"matplotlib"
] | I use matplotib's Axes API to plot some figures. One of the lines I plot represents the theoretical expected line. It has no meaning outside of the original y and x limits. What I want, is for matlplotlib to ignore it when autoscaling the limits. What I used to do, is to check what are the current limits, then plot, an... | The obvious way is to just manually set the limits to what you want. (e.g. `ax.axis([xmin, xmax, ymin, ymax])`)
If you don't want to bother with finding out the limits manually, you have a couple of options...
As several people (tillsten, Yann, and Vorticity) have mentioned, if you can plot the function you want to i... |
Avoid if __name__ == '__main__' in Python subclasses to be run using function from parent | 7,386,969 | 4 | 2011-09-12T11:13:19Z | 7,387,471 | 8 | 2011-09-12T11:59:15Z | [
"python",
"subclass"
] | I have a generic class (A) which is to be subclassed a lot like this:
```
class A:
def run(self):
...
self.do_something()
...
#abstract function
def do_something(self):
pass
class B(A):
def do_something(self):
...
```
The subclasses are in separate files that... | If your python version is recent enough, you can create a class decorator.
In this case, an indirect one.
```
def runifmain(mainname):
def deco(clas):
if mainname == '__main__':
clas().run()
return clas
return deco
@runifmain(__name__)
class B(A):
[...]
```
should do the job... |
Set Windows command-line terminal title in Python | 7,387,276 | 11 | 2011-09-12T11:40:07Z | 10,229,529 | 14 | 2012-04-19T13:50:14Z | [
"python",
"windows",
"low-latency"
] | I'm running several instances of a certain Python script on a Windows machine, each from a different directory and using a separate shell windows. Unfortunately Windows gives each of these shell windows the same name:
```
<User>: C:\Windows\system32\cmd.exe - <script.py>
```
Is it possible to set this name to somethi... | On Windows, a simple console command will suffice:
```
from os import system
system("title "+myCoolTitle)
```
Nice & easy. |
Set Windows command-line terminal title in Python | 7,387,276 | 11 | 2011-09-12T11:40:07Z | 12,626,424 | 16 | 2012-09-27T16:56:04Z | [
"python",
"windows",
"low-latency"
] | I'm running several instances of a certain Python script on a Windows machine, each from a different directory and using a separate shell windows. Unfortunately Windows gives each of these shell windows the same name:
```
<User>: C:\Windows\system32\cmd.exe - <script.py>
```
Is it possible to set this name to somethi... | This works for Python2.7 under Windows.
```
>>> import ctypes
>>> ctypes.windll.kernel32.SetConsoleTitleA("My New Title")
``` |
Set Windows command-line terminal title in Python | 7,387,276 | 11 | 2011-09-12T11:40:07Z | 20,864,842 | 7 | 2014-01-01T01:33:25Z | [
"python",
"windows",
"low-latency"
] | I'm running several instances of a certain Python script on a Windows machine, each from a different directory and using a separate shell windows. Unfortunately Windows gives each of these shell windows the same name:
```
<User>: C:\Windows\system32\cmd.exe - <script.py>
```
Is it possible to set this name to somethi... | Due to not enough rep I cannot add a comment to the above post - so as a new post.
In **Python 3** you can use:
```
import ctypes
ctypes.windll.kernel32.SetConsoleTitleA(b"My New Title")
```
It's nearly the same as above but in Python 3 you have to add the 'b' in front of the string.
If you want to use a variable y... |
How do you find out what the "system default encoding" is? | 7,387,744 | 14 | 2011-09-12T12:20:56Z | 7,387,773 | 35 | 2011-09-12T12:22:40Z | [
"python",
"unicode",
"character-encoding",
"python-2.x"
] | [The documentation for fileobject.encoding](http://docs.python.org/library/stdtypes.html#file.encoding) mentions that it can be `None`, and in that case, the "system default encoding" is used.
How can I find out what this encoding is? | [`sys.getdefaultencoding()`](http://docs.python.org/library/sys.html#sys.getdefaultencoding)
(Not to grumble too much, but this is probably something you should have googled - it's the first result for `python os default encoding`, and the second for `python system default encoding`.) |
Replace property for perfomance gain | 7,388,258 | 4 | 2011-09-12T12:59:22Z | 7,388,323 | 14 | 2011-09-12T13:05:31Z | [
"python",
"properties"
] | ### Situation
Similar to [this question](http://stackoverflow.com/questions/4963036/python-how-to-replace-a-property-with-a-regular-attribute), I want to replace a property. Unlike that question, I do not want to override it in a sub-class. I want to replace it in the init and in the property itself for efficiency, so... | What you are looking for is [Denis Otkidach](http://stackoverflow.com/users/168352/denis-otkidach)'s excellent CachedAttribute:
```
class CachedAttribute(object):
'''Computes attribute value and caches it in the instance.
From the Python Cookbook (Denis Otkidach)
This decorator allows you to create a p... |
append subprocess.Popen output to file? | 7,389,158 | 11 | 2011-09-12T14:04:47Z | 7,389,473 | 10 | 2011-09-12T14:29:26Z | [
"python",
"subprocess",
"popen"
] | I can successfully redirect my output to a file, however this appears to overwrite the file's existing data:
```
import subprocess
outfile = open('test','w') #same with "w" or "a" as opening mode
outfile.write('Hello')
subprocess.Popen('ls',stdout=outfile)
```
will remove the `'Hello'` line from the file.
I guess a ... | You sure can append the output of `subprocess.Popen` to a file, and I make a daily use of it. Here's how I do it:
```
log = open('some file.txt', 'a') # so that data written to it will be appended
c = subprocess.Popen(['dir', '/p'], stdout=log, stderr=log, shell=True)
```
(of course, this is a dummy example, I'm not... |
Output images to html using python | 7,389,567 | 7 | 2011-09-12T14:37:09Z | 7,389,616 | 18 | 2011-09-12T14:40:37Z | [
"python",
"html",
"http-headers",
"cgi"
] | I have a webpage generated from python that works as it should, using:
```
print 'Content-type: text/html\n\n'
print "" # blank line, end of headers
print '<link href="default.css" rel="stylesheet" type="text/css" />'
print "<html><head>"
```
I want to add images to this webpage, but ... | You can use this code to directly embed the image in your HTML:
```
data_uri = open('11.png', 'rb').read().encode('base64').replace('\n', '')
img_tag = '<img src="data:image/png;base64,{0}">'.format(data_uri)
print(img_tag)
```
Alternatively for Python <2.6:
```
data_uri = open('11.png', 'rb').read().encode('base64... |
link several Popen commands with pipes | 7,389,662 | 16 | 2011-09-12T14:43:56Z | 7,389,857 | 24 | 2011-09-12T14:58:21Z | [
"python",
"command",
"subprocess",
"pipe",
"popen"
] | I know how to run a command using cmd = subprocess.Popen and then subprocess.communicate.
Most of the time I use a string tokenized with shlex.split as 'argv' argument for Popen.
Example with "ls -l":
```
import subprocess
import shlex
print subprocess.Popen(shlex.split(r'ls -l'), stdin = subprocess.PIPE, stdout = sub... | I think you want to instantiate two separate Popen objects here, one for 'ls' and the other for 'sed'. You'll want to pass the first Popen object's `stdout` attribute as the `stdin` argument to the 2nd Popen object.
Example:
```
p1 = subprocess.Popen('ls ...', stdout=subprocess.PIPE)
p2 = subprocess.Popen('sed ...', ... |
memory-efficient built-in SqlAlchemy iterator/generator? | 7,389,759 | 43 | 2011-09-12T14:50:36Z | 7,390,660 | 71 | 2011-09-12T15:58:03Z | [
"python",
"mysql",
"sqlalchemy"
] | I have a ~10M record MySQL table that I interface with using SqlAlchemy. I have found that queries on large subsets of this table will consume too much memory even though I thought I was using a built-in generator that intelligently fetched bite-sized chunks of the dataset:
```
for thing in session.query(Things):
... | Most DBAPI implementations fully buffer rows as they are fetched - so usually, before the SQLAlchemy ORM even gets a hold of one result, the whole result set is in memory.
But then, the way Query works is that it fully loads the given result set by default before returning to you your objects. The rationale here regar... |
Parsing crontab-style lines | 7,390,170 | 15 | 2011-09-12T15:20:23Z | 7,399,453 | 26 | 2011-09-13T09:15:44Z | [
"python",
"crontab"
] | I need to parse a crontab-like schedule definition in Python (e.g. 00 3 \* \* \*) and get where this should have last run.
Is there a good (preferably small) library that parses these strings and translates them to dates? | Perhaps the python package [croniter](http://pypi.python.org/pypi/croniter/) suits your needs.
Usage example:
```
>>> import croniter
>>> import datetime
>>> now = datetime.datetime.now()
>>> cron = croniter.croniter('45 17 */2 * *', now)
>>> cron.get_next(datetime.datetime)
datetime.datetime(2011, 9, 14, 17, 45)
>>... |
PyCurl installed but not found | 7,391,638 | 11 | 2011-09-12T17:31:26Z | 7,400,218 | 22 | 2011-09-13T10:18:01Z | [
"python",
"curl",
"libcurl",
"pycurl"
] | I've been trying to install pycurl in a virtualenv with easy\_install, and it appears to install correctly:
```
(xxx) $ easy_install pycurl
Searching for pycurl
Reading http://pypi.python.org/simple/pycurl/
Reading http://pycurl.sourceforge.net/
Reading http://pycurl.sourceforge.net/download/
Best match: pycurl 7.19.0... | I have managed (with some help) so solve the problem. The problem is that after installation, the pycurl.so is not copied to the site-packages for this virtualenv.
When installing via `pip -v install pycurl`, the following output is given:
```
Downloading/unpacking pycurl
Using version 7.19.0 (newest of versions: 7... |
closing stdout of piped python subprocess | 7,391,689 | 10 | 2011-09-12T17:36:03Z | 7,391,809 | 12 | 2011-09-12T17:46:55Z | [
"python",
"shell",
"subprocess",
"pipeline"
] | Here is what I can read in the python subprocess module documentation:
```
Replacing shell pipeline
output=`dmesg | grep hda`
==>
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output ... | From [Wikipedia](http://en.wikipedia.org/wiki/SIGPIPE), **SIGPIPE** is the signal sent to a process when it attempts to write to a pipe without a process connected to the other end.
When you first create `p1` using `stdout=PIPE`, there is one process connected to the pipe, which is your Python process, and you can rea... |
How do I read image data from a URL in Python? | 7,391,945 | 69 | 2011-09-12T18:01:46Z | 7,391,983 | 21 | 2011-09-12T18:06:30Z | [
"python",
"python-imaging-library"
] | What I'm trying to do is fairly simple when we're dealing with a local file, but the problem comes when I try to do this with a remote URL.
Basically, I'm trying to create a PIL image object from a file pulled from a URL. Sure, I could always just fetch the URL and store it in a temp file, then open it into an image o... | Use `StringIO` to turn the read string into a file-like object:
```
from StringIO import StringIO
import urllib
Image.open(StringIO(urllib.urlopen(url).read()))
``` |
How do I read image data from a URL in Python? | 7,391,945 | 69 | 2011-09-12T18:01:46Z | 7,391,991 | 107 | 2011-09-12T18:07:32Z | [
"python",
"python-imaging-library"
] | What I'm trying to do is fairly simple when we're dealing with a local file, but the problem comes when I try to do this with a remote URL.
Basically, I'm trying to create a PIL image object from a file pulled from a URL. Sure, I could always just fetch the URL and store it in a temp file, then open it into an image o... | you could try using a StringIO
```
import urllib, cStringIO
file = cStringIO.StringIO(urllib.urlopen(URL).read())
img = Image.open(file)
``` |
How do I read image data from a URL in Python? | 7,391,945 | 69 | 2011-09-12T18:01:46Z | 13,024,547 | 39 | 2012-10-23T06:19:24Z | [
"python",
"python-imaging-library"
] | What I'm trying to do is fairly simple when we're dealing with a local file, but the problem comes when I try to do this with a remote URL.
Basically, I'm trying to create a PIL image object from a file pulled from a URL. Sure, I could always just fetch the URL and store it in a temp file, then open it into an image o... | I use the requests library. It seems to be more robust.
```
from PIL import Image
import requests
from StringIO import StringIO
response = requests.get(url)
img = Image.open(StringIO(response.content))
``` |
How do I read image data from a URL in Python? | 7,391,945 | 69 | 2011-09-12T18:01:46Z | 23,489,503 | 39 | 2014-05-06T08:21:51Z | [
"python",
"python-imaging-library"
] | What I'm trying to do is fairly simple when we're dealing with a local file, but the problem comes when I try to do this with a remote URL.
Basically, I'm trying to create a PIL image object from a file pulled from a URL. Sure, I could always just fetch the URL and store it in a temp file, then open it into an image o... | In Python3 the StringIO and cStringIO modules are gone.
In Python3 you should use:
```
from PIL import Image
import requests
from io import BytesIO
response = requests.get(url)
img = Image.open(BytesIO(response.content))
``` |
Trying to understand insertion sort algorithm | 7,392,225 | 4 | 2011-09-12T18:28:58Z | 7,392,788 | 11 | 2011-09-12T19:15:21Z | [
"python",
"algorithm",
"sorting",
"insertion-sort"
] | I'm reading some books on Python, data structures, and analysis and design of algorithms. I want to really understand the in's and out's of coding, and become an efficient programmer. It's difficult to ask the book to clarify, hence my question on stackoverflow. I'm really finding Algorithms and recursion challenging .... | Let me try to break this down.
Start by considering a list. It is "almost" sorted. That is, the first few elements are sorted, but the last element is not sorted. So it looks something like this:
```
[10, 20, 30, 50, 15]
```
Obviously, the 15 is in the wrong place. So how do we move it?
```
key = mylist[4]
... |
How do you use __init__.py? | 7,392,373 | 5 | 2011-09-12T18:42:08Z | 7,392,398 | 7 | 2011-09-12T18:45:12Z | [
"python",
"module"
] | I'm trying to learn how the `__init__.py` file works for packaging and calling modules from different directories.
I have a directory structure like this:
```
init_test\
__init__.py
a\
aaa.py
b\
bbb.py
```
in `aaa.py` there is a function called `test`
`bbb.py` looks like this:
```
import ... | You also need to have \_\_init\_\_.py in a and b directories
For your example to work first you should add your base directory to the path:
```
import sys
sys.path.append('../..')
import init_test.a.aaa
...
``` |
Python threads - number of arguments Error | 7,392,636 | 5 | 2011-09-12T19:01:12Z | 7,392,657 | 20 | 2011-09-12T19:03:04Z | [
"python",
"multithreading"
] | I am executing a command in a thread for almost 25k times like
```
if threaded is True:
thread = Thread(target=threadedCommand, args=(cmd))
thread.start()
thread.join()
def threadedCommand(command):
if command is None:
print 'can\'t execute threaded comman... | `args` must be a tuple. `(cmd)` is the same as `cmd`; you want a one-element tuple instead:
```
thread = Thread(target=threadedCommand, args=(cmd,))
# ^
``` |
Getting an error that doesn't seem to make much sense. | 7,393,748 | 3 | 2011-09-12T20:40:40Z | 7,393,787 | 7 | 2011-09-12T20:43:43Z | [
"python",
"debugging",
"dictionary",
"pdb"
] | I keep getting an error that's referencing one of my Dictionaries in the code. But I can't seem to find anything that would be causing the problem. Something is probably slipping past my eyes, but here's the error from *command line pdb* anyways.
To explain what's going on, this is a rather large dictionary and it's t... | Missing comma just before 51.
In future, to help trace this kind of error, its helpful not to put everything on one giant line, split it across several lines. That way the arrow will be more helpful. |
Numpy modify ndarray diagonal | 7,394,760 | 8 | 2011-09-12T22:27:34Z | 7,394,841 | 13 | 2011-09-12T22:36:58Z | [
"python",
"numpy"
] | is there any way in numpy to get a reference to the array diagonal?
I want my array diagonal to be divided by a certain factor
Thanks | If `X` is your array and `c` is the factor,
```
X[np.diag_indices_from(X)] /= c
```
See [`diag_indices_from`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.diag_indices_from.html#numpy.diag_indices_from) in the Numpy manual. |
Numpy modify ndarray diagonal | 7,394,760 | 8 | 2011-09-12T22:27:34Z | 10,465,404 | 12 | 2012-05-05T19:47:44Z | [
"python",
"numpy"
] | is there any way in numpy to get a reference to the array diagonal?
I want my array diagonal to be divided by a certain factor
Thanks | A quick way to access the diagonal of a square `(n,n)` numpy array is with `arr.flat[::n+1]`:
```
n = 1000
c = 20
a = np.random.rand(n,n)
a[np.diag_indices_from(a)] /= c # 119 microseconds
a.flat[::n+1] /= c # 25.3 microseconds
``` |
Pytest: Deselecting tests | 7,395,444 | 19 | 2011-09-13T00:07:34Z | 7,406,812 | 10 | 2011-09-13T18:41:10Z | [
"python",
"py.test"
] | With pytest, one can mark tests using a decorator
```
@pytest.mark.slow
def some_slow_test():
pass
```
Then, from the command line, one can tell pytest to skip the tests marked "slow"
```
pytest -k-slow
```
If I have an additional tag:
```
@pytest.mark.long
def some_long_test()
pass
```
I would like to be... | Looking through the `pytest` code (`mark.py`) and further experimentation shows the following seems to work:
```
pytest -k "-slow -long"
```
(Using the `--collect-only` option speeds up experimentation) |
Pytest: Deselecting tests | 7,395,444 | 19 | 2011-09-13T00:07:34Z | 9,117,335 | 19 | 2012-02-02T17:53:46Z | [
"python",
"py.test"
] | With pytest, one can mark tests using a decorator
```
@pytest.mark.slow
def some_slow_test():
pass
```
Then, from the command line, one can tell pytest to skip the tests marked "slow"
```
pytest -k-slow
```
If I have an additional tag:
```
@pytest.mark.long
def some_long_test()
pass
```
I would like to be... | Additionally, with the recent addition of the "-m" command line option you should be able to write:
```
py.test -m "not (slow or long)"
```
IOW, the "-m" option accepts an expression which can make use of markers as boolean values (if a marker does not exist on a test function it's value is False, if it exists, it is... |
Is explicitly closing files important? | 7,395,542 | 81 | 2011-09-13T00:27:07Z | 7,395,906 | 15 | 2011-09-13T01:39:01Z | [
"python",
"file",
"garbage-collection"
] | In Python, if you either open a file without calling `close()`, or close the file but not using `try`-`finally` or the "`with`" statement, is this a problem? Or does it suffice as a coding practice to rely on the Python garbage-collection to close all files? For example, if one does this:
```
for line in open("filenam... | Some Pythons will close files automatically when they are no longer referenced, while others will not and it's up to the O/S to close files when the Python interpreter exits.
Even for the Pythons that will close files for you, the timing is not guaranteed: it could be immediately, or it could be seconds/minutes/hours/... |
Is explicitly closing files important? | 7,395,542 | 81 | 2011-09-13T00:27:07Z | 7,396,043 | 72 | 2011-09-13T02:00:38Z | [
"python",
"file",
"garbage-collection"
] | In Python, if you either open a file without calling `close()`, or close the file but not using `try`-`finally` or the "`with`" statement, is this a problem? Or does it suffice as a coding practice to rely on the Python garbage-collection to close all files? For example, if one does this:
```
for line in open("filenam... | In your example the file isn't guaranteed to be closed before the interpreter exits. In current versions of CPython the file will be closed at the end of the for loop because CPython uses reference counting as its primary garbage collection mechanism but that's an implementation detail, not a feature of the language. O... |
Is explicitly closing files important? | 7,395,542 | 81 | 2011-09-13T00:27:07Z | 17,365,122 | 8 | 2013-06-28T12:50:07Z | [
"python",
"file",
"garbage-collection"
] | In Python, if you either open a file without calling `close()`, or close the file but not using `try`-`finally` or the "`with`" statement, is this a problem? Or does it suffice as a coding practice to rely on the Python garbage-collection to close all files? For example, if one does this:
```
for line in open("filenam... | Although it is quite safe to use such construct in this particular case, there are some caveats for generalising such practice:
* run can potentially run out of file descriptors, although unlikely, imagine hunting a bug like that
* you may not be able to delete said file on some systems, e.g. win32
* if you run anythi... |
Replacing a weird single-quote (â) with blank string in Python | 7,395,789 | 6 | 2011-09-13T01:13:35Z | 7,396,665 | 9 | 2011-09-13T04:03:13Z | [
"python"
] | I'm trying to use `string.replace('â','')` to replace the dreaded weird single-quote character: â (aka \xe2 aka #8217). But when I run that line of code, I get this error:
```
SyntaxError: Non-ASCII character '\xe2' in file
```
**EDIT**: I get this error when trying to replace characters in a CSV file obtained re... | The problem here is with the encoding *of the file you downloaded* (`aa_meetings.csv`). The server doesn't declare an encoding in its HTTP headers, but the only non-ASCII1 octet in the file has the value 0x92. You say that this is supposed to be "the dreaded weird single-quote character", therefore the file's encoding ... |
Is there a static constructor or static initializer in Python? | 7,396,092 | 23 | 2011-09-13T02:11:12Z | 7,396,119 | 12 | 2011-09-13T02:17:29Z | [
"python"
] | **Is there such a thing as a static constructor in Python?**
How do I implement a static constructor in Python?
Here is my code... The `__init__` doesn't fire when I call App like this. The `__init__` is not a static constructor or static initializer.
```
App.EmailQueue.DoSomething()
```
I have to call it like this... | Hint: anything that references `self` is going to require an instantiation of the class. You could do it like this:
```
class App:
email_queue = EmailQueue()
App.email_queue.DoSomething()
```
But come on, that seems like a lot of fluff. I'm with SLaks, just initialize it outside of the class. Alternatively, you ... |
Is there a static constructor or static initializer in Python? | 7,396,092 | 23 | 2011-09-13T02:11:12Z | 7,396,353 | 14 | 2011-09-13T02:59:47Z | [
"python"
] | **Is there such a thing as a static constructor in Python?**
How do I implement a static constructor in Python?
Here is my code... The `__init__` doesn't fire when I call App like this. The `__init__` is not a static constructor or static initializer.
```
App.EmailQueue.DoSomething()
```
I have to call it like this... | There's a fundamental difference between static and dynamic languages that isn't always apparent at first. In a static language the class is defined at compile time and everything is all nice and set in concrete before the program ever runs. In a dynamic language the class is actually defined at runtime. As soon as the... |
Python & GTK3: How to create a Liststore | 7,396,723 | 5 | 2011-09-13T04:12:49Z | 7,397,268 | 8 | 2011-09-13T05:36:02Z | [
"python",
"pygobject",
"gtk3"
] | In PyGtk I always used this to create a ListStore with an Image (using it with an IconView for displaying files):
```
store = gtk.ListStore(str, gtk.gdk.Pixbuf, bool)
```
But I can't figure out how to do this with Python 3 and PyGObject. | Here's how:
```
from gi.repository import Gtk, GdkPixbuf
store = Gtk.ListStore(str, GdkPixbuf.Pixbuf, bool)
``` |
Convert binary to ASCII and vice versa | 7,396,849 | 40 | 2011-09-13T04:34:14Z | 7,397,195 | 8 | 2011-09-13T05:23:37Z | [
"python",
"binary",
"ascii"
] | Using this code to take a string and convert it to binary:
```
bin(reduce(lambda x, y: 256*x+y, (ord(c) for c in 'hello'), 0))
```
this outputs:
```
0b110100001100101011011000110110001101111
```
Which, if I put it into [this site](http://www.roubaixinteractive.com/PlayGround/Binary_Conversion/Binary_To_Text.asp) (o... | I'm not sure how you think you can do it other than character-by-character -- it's inherently a character-by-character operation. There is certainly code out there to do this for you, but there is no "simpler" way than doing it character-by-character.
First, you need to strip the `0b` prefix, and left-zero-pad the str... |
Convert binary to ASCII and vice versa | 7,396,849 | 40 | 2011-09-13T04:34:14Z | 7,397,689 | 78 | 2011-09-13T06:29:17Z | [
"python",
"binary",
"ascii"
] | Using this code to take a string and convert it to binary:
```
bin(reduce(lambda x, y: 256*x+y, (ord(c) for c in 'hello'), 0))
```
this outputs:
```
0b110100001100101011011000110110001101111
```
Which, if I put it into [this site](http://www.roubaixinteractive.com/PlayGround/Binary_Conversion/Binary_To_Text.asp) (o... | For ASCII characters in the range `[ -~]` on Python 2:
```
>>> import binascii
>>> bin(int(binascii.hexlify('hello'), 16))
'0b110100001100101011011000110110001101111'
```
In reverse:
```
>>> n = int('0b110100001100101011011000110110001101111', 2)
>>> binascii.unhexlify('%x' % n)
'hello'
```
---
In Python 3.2+:
``... |
which similarity function of nltk.corpus.wordnet is Appropriate for find similarity of two words? | 7,400,533 | 5 | 2011-09-13T10:42:56Z | 7,406,207 | 7 | 2011-09-13T17:50:31Z | [
"python",
"nlp",
"nltk",
"wordnet",
"corpus"
] | which similarity function in `nltk.corpus.wordnet` is Appropriate for find similarity of two words?
```
path_similarity()?
lch_similarity()?
wup_similarity()?
res_similarity()?
jcn_similarity()?
lin_similarity()?
```
I want use a function for `word clustering` and `yarowsky` algorightm for find s... | These measure are actually for word senses (or concepts) not words. That distinction might matter. In other words, the word "train" can mean "locomotive" or "being taught to do something". To use these measures you'd need to know which sense was intended.
If you want to do word clustering, these measures *might* not b... |
ImportError: No module named suds | 7,403,738 | 4 | 2011-09-13T14:42:21Z | 7,404,912 | 8 | 2011-09-13T16:01:31Z | [
"python",
"import",
"path",
"suds",
"importerror"
] | Having trouble with py2exe importing the suds module, and narrowed it down to the following:
```
>>> imp.find_module('suds', sys.path)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named suds
```
However, a simple import works fine:
```
>>> import suds
>>> suds.__ver... | Extracted the `suds` egg at:
> C:\Python27\lib\site-packages\suds-0.4-py2.7.egg
and created `C:\Python27\lib\site-packages\suds` directory that contains source files. Module is now found:
```
>>> imp.find_module('suds')
(None, 'C:\\Python27\\lib\\site-packages\\suds', ('', '', 5))
```
py2exe build completes success... |
Cross-platform Desktop directory path? | 7,403,918 | 13 | 2011-09-13T14:53:32Z | 7,404,298 | 12 | 2011-09-13T15:16:27Z | [
"python",
"path",
"directory",
"cross-platform",
"desktop"
] | Is there a way of obtaining the **Desktop directory path** in a *cross-platform* way, ideally only using standard modules, in Python?
My current Mac OS X + Windows solution is to check which system is running Python with [sys.platform](http://docs.python.org/library/sys.html#sys.platform) and then do the following:
*... | Underneath windows, the users home is `%HOMEPATH%` which is the equivalent of the linux and Mac `~`. Underneath this, there is a folder `Desktop` just like on Mac. Python automatically converts `~` to %HOMEPATH% on windows, so your Mac command will work out of the box on Mac and windows.
On linux, it's a bit trickier.... |
Cross-platform Desktop directory path? | 7,403,918 | 13 | 2011-09-13T14:53:32Z | 19,206,699 | 9 | 2013-10-06T08:01:44Z | [
"python",
"path",
"directory",
"cross-platform",
"desktop"
] | Is there a way of obtaining the **Desktop directory path** in a *cross-platform* way, ideally only using standard modules, in Python?
My current Mac OS X + Windows solution is to check which system is running Python with [sys.platform](http://docs.python.org/library/sys.html#sys.platform) and then do the following:
*... | I used the following:
```
import os
desktopFile = os.path.expanduser("~/Desktop/myfile.txt")
```
> On Unix and Windows, return the argument with an initial component of
> ~ or ~user replaced by that userâs home directory.
Reference: os.path.[expanduser](http://docs.python.org/2/library/os.path.html#os.path.expandu... |
Defining the midpoint of a colormap in matplotlib | 7,404,116 | 38 | 2011-09-13T15:04:37Z | 7,404,517 | 9 | 2011-09-13T15:31:42Z | [
"python",
"matplotlib"
] | I want to set the middle point of a colormap, ie my data goes from -5 to 10, i want zero to be the middle. I think the way to do it is subclassing normalize and using the norm, but i didn't find any example and it is not clear to me, what exactly i have to implement. | It's easiest to just use the `vmin` and `vmax` arguments to `imshow` (assuming you're working with image data) rather than subclassing `matplotlib.colors.Normalize`.
E.g.
```
import numpy as np
import matplotlib.pyplot as plt
data = np.random.random((10,10))
# Make the data range from about -5 to 10
data = 10 / 0.75... |
Defining the midpoint of a colormap in matplotlib | 7,404,116 | 38 | 2011-09-13T15:04:37Z | 7,746,125 | 13 | 2011-10-12T20:26:14Z | [
"python",
"matplotlib"
] | I want to set the middle point of a colormap, ie my data goes from -5 to 10, i want zero to be the middle. I think the way to do it is subclassing normalize and using the norm, but i didn't find any example and it is not clear to me, what exactly i have to implement. | Here is a solution subclassing Normalize. To use it
```
norm = MidPointNorm(midpoint=3)
imshow(X, norm=norm)
```
Here is the Class:
```
from numpy import ma
from matplotlib import cbook
class MidPointNorm(Normalize):
def __init__(self, midpoint=0, vmin=None, vmax=None, clip=False):
Normalize.__init... |
Defining the midpoint of a colormap in matplotlib | 7,404,116 | 38 | 2011-09-13T15:04:37Z | 20,528,097 | 39 | 2013-12-11T19:20:17Z | [
"python",
"matplotlib"
] | I want to set the middle point of a colormap, ie my data goes from -5 to 10, i want zero to be the middle. I think the way to do it is subclassing normalize and using the norm, but i didn't find any example and it is not clear to me, what exactly i have to implement. | I know this is late to the game, but I just went through this process and came up with a solution that perhaps less robust than subclassing normalize, but much simpler. I thought it'd be good to share it here for posterity.
### The function
```
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from... |
NLTK fails to find the Java executable | 7,404,720 | 12 | 2011-09-13T15:46:27Z | 22,208,156 | 28 | 2014-03-05T20:10:37Z | [
"java",
"python",
"tags",
"config",
"nltk"
] | I am using NLTK's nltk.tag.stanford, which needs to call the java executable.
I set JAVAHOME to C:\Program Files\Java\jdk1.6.0\_25 where my jdk is installed, but when run the program I get the error
```
"NLTK was unable to find the java executable! Use the config_java() or set the JAVAHOME variable"
```
Then I spent... | If setting the JAVA\_HOME environment doesn't help you, try this:
`config_java()` did not work for me. I add the following lines to my code and it worked:
```
import os
java_path = "C:/Program Files/Java/jdk1.7.0_11/bin/java.exe"
os.environ['JAVAHOME'] = java_path
```
I am running Windows 7 64-bit |
How to create Mac application bundle for Python script via Python | 7,404,792 | 3 | 2011-09-13T15:52:26Z | 7,405,367 | 9 | 2011-09-13T16:37:40Z | [
"python",
"osx",
"py2app"
] | I want to create a simple Mac application bundle which calls a simple Python script. I want to do that in Python.
Is there an easy way?
I tried to use py2app but that fails somehow, e.g.:
```
from setuptools import setup
setup(app=["foo.py"], setup_requires=["py2app"])
```
gives:
```
------------------------------... | This is exactly what I wanted and works just fine:
```
#!/usr/bin/python
import sys
assert len(sys.argv) > 1
apppath = sys.argv[1]
import os, os.path
assert os.path.splitext(apppath)[1] == ".app"
os.makedirs(apppath + "/Contents/MacOS")
version = "1.0.0"
bundleName = "Test"
bundleIdentifier = "org.test.test"
f =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.