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 |
|---|---|---|---|---|---|---|---|---|---|
How to stop SIGINT being passed to subprocess in python? | 3,232,613 | 13 | 2010-07-12T21:57:58Z | 3,731,948 | 13 | 2010-09-17T00:42:51Z | [
"python",
"subprocess",
"signals",
"intercept",
"sigint"
] | My python script intercepts the SIGINT signal with the signal process module to prevent premature exit, but this signal is passed to a subprocess that I open with Popen. is there some way to prevent passing this signal to the subprocess so that it also is not exited prematurely when the user presses ctrl-c? | Signal handlers are inherited when you start a subprocess, so if you use the signal module to ignore SIGINT (`signal.signal(signal.SIGINT, signal.SIG_IGN)`), then your child process automatically will also.
There are two important caveats, though:
* You have to set the ignore handler *before* you spawn the child proc... |
Adding attributes to existing elements, removing elements, etc with lxml | 3,232,618 | 4 | 2010-07-12T21:58:24Z | 3,232,738 | 9 | 2010-07-12T22:22:07Z | [
"python",
"xml",
"lxml"
] | I parse in the XML using
```
from lxml import etree
tree = etree.parse('test.xml', etree.XMLParser())
```
Now I want to work on the parsed XML. I'm having trouble removing elements with namespaces or just elements in general such as
```
<rdf:description><dc:title>Example</dc:title></rdf:description>
```
and I want... | You can get to the root element via this call: `root=tree.getroot()`
Using that root element, you can use `findall()` and remove elements that match your criteria:
```
deleteThese = root.findall("title")
for element in deleteThese: root.remove(element)
```
Finally, you can see what your new tree looks like with this... |
Update value of a nested dictionary of varying depth | 3,232,943 | 68 | 2010-07-12T23:01:12Z | 3,233,356 | 113 | 2010-07-13T00:31:53Z | [
"python"
] | I'm looking for a way to update dict dictionary1 with the contents of dict update wihout overwriting levelA
```
dictionary1={'level1':{'level2':{'levelA':0,'levelB':1}}}
update={'level1':{'level2':{'levelB':10}}}
dictionary1.update(update)
print dictionary1
{'level1': {'level2': {'levelB': 10}}}
```
I know that updat... | @FM's answer has the right general idea, i.e., a recursive solution, but somewhat peculiar coding and at least one bug. I'd recommend, instead:
Python 2:
```
import collections
def update(d, u):
for k, v in u.iteritems():
if isinstance(v, collections.Mapping):
r = update(d.get(k, {}), v)
... |
Update value of a nested dictionary of varying depth | 3,232,943 | 68 | 2010-07-12T23:01:12Z | 18,394,648 | 12 | 2013-08-23T04:21:05Z | [
"python"
] | I'm looking for a way to update dict dictionary1 with the contents of dict update wihout overwriting levelA
```
dictionary1={'level1':{'level2':{'levelA':0,'levelB':1}}}
update={'level1':{'level2':{'levelB':10}}}
dictionary1.update(update)
print dictionary1
{'level1': {'level2': {'levelB': 10}}}
```
I know that updat... | Took me a little bit on this one, but thanks to @Alex's post, he filled in the gap I was missing. However, I came across an issue if a value within the recursive `dict` happens to be a `list`, so I thought I'd share, and extend his answer.
```
import collections
def update(orig_dict, new_dict):
for key, val in ne... |
Python: Removing spaces from list objects | 3,232,953 | 18 | 2010-07-12T23:04:42Z | 3,232,961 | 40 | 2010-07-12T23:06:26Z | [
"python",
"list"
] | I have a list of objects appended from a mysql database and contain spaces. I wish to remove the spaces such as below, but the code im using doesnt work?
```
hello = ['999 ',' 666 ']
k = []
for i in hello:
str(i).replace(' ','')
k.append(i)
print k
``` | Strings in Python are immutable (meaning that their data cannot be modified) so the replace method doesn't modify the string - it returns a new string. You could fix your code as follows:
```
for i in hello:
j = i.replace(' ','')
k.append(j)
```
However a better way to achieve your aim is to use a list compre... |
How can I get the installed GDAL/OGR version from python? | 3,233,674 | 7 | 2010-07-13T02:00:27Z | 3,236,392 | 10 | 2010-07-13T10:51:49Z | [
"python",
"gis",
"geospatial",
"gdal",
"ogr"
] | How can I get the installed GDAL/OGR version from python?
I aware of the `gdal-config` program and are currently using the following:
```
In [3]: import commands
In [4]: commands.getoutput('gdal-config --version')
Out[4]: '1.7.2'
```
However, I suspect there is a way to do this using the python API itself. Any dice... | The `__version__` property in the osgeo.gdal module is a string that contains the version number
```
import osgeo.gdal
print osgeo.gdal.__version__
```
On my ubuntu machine gives:
```
>> '1.6.3'
``` |
How can I get the installed GDAL/OGR version from python? | 3,233,674 | 7 | 2010-07-13T02:00:27Z | 3,412,259 | 10 | 2010-08-05T06:29:29Z | [
"python",
"gis",
"geospatial",
"gdal",
"ogr"
] | How can I get the installed GDAL/OGR version from python?
I aware of the `gdal-config` program and are currently using the following:
```
In [3]: import commands
In [4]: commands.getoutput('gdal-config --version')
Out[4]: '1.7.2'
```
However, I suspect there is a way to do this using the python API itself. Any dice... | **`gdal.VersionInfo()`** does what I want:
```
>>> osgeo.gdal.VersionInfo()
'1604'
```
This works on both my Windows box and Ubuntu install. `gdal.__version__` gives an error on my Windows installation, although it works on my Ubuntu installation:
```
>>> import osgeo.gdal
>>> print osgeo.gdal.__version__
Traceback ... |
Python: Using .format() on a Unicode-escaped string | 3,235,386 | 93 | 2010-07-13T08:29:12Z | 3,235,418 | 151 | 2010-07-13T08:34:48Z | [
"python",
"unicode",
"string"
] | I am using Python 2.6.5. My code requires the use of the "more than or equal to" sign. Here it goes:
```
>>> s = u'\u2265'
>>> print s
>>> â¥
>>> print "{0}".format(s)
Traceback (most recent call last):
File "<input>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2265'
in p... | Just make the second string also a unicode string
```
>>> s = u'\u2265'
>>> print s
â¥
>>> print "{0}".format(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2265' in position 0: ordinal not in range(128)
>>> print u"{0}".format(... |
Python: Using .format() on a Unicode-escaped string | 3,235,386 | 93 | 2010-07-13T08:29:12Z | 3,235,421 | 35 | 2010-07-13T08:35:36Z | [
"python",
"unicode",
"string"
] | I am using Python 2.6.5. My code requires the use of the "more than or equal to" sign. Here it goes:
```
>>> s = u'\u2265'
>>> print s
>>> â¥
>>> print "{0}".format(s)
Traceback (most recent call last):
File "<input>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2265'
in p... | `unicode`s need `unicode` format strings.
```
>>> print u'{0}'.format(s)
â¥
``` |
Django - How to rename a model field using South? | 3,235,995 | 198 | 2010-07-13T09:53:02Z | 3,236,197 | 223 | 2010-07-13T10:26:56Z | [
"python",
"django",
"django-models",
"django-south"
] | I would like to change a name of specific fields in a model:
```
class Foo(models.Model):
name = models.CharField()
rel = models.ForeignKey(Bar)
```
should change to:
```
class Foo(models.Model):
full_name = models.CharField()
odd_relation = models.ForeignKey(Bar)
```
What's the easiest way to... | You can use the [`db.rename_column`](http://south.readthedocs.org/en/latest/databaseapi.html#db-rename-column) function.
```
class Migration:
def forwards(self, orm):
# Rename 'name' field to 'full_name'
db.rename_column('app_foo', 'name', 'full_name')
def backwards(self, orm):
# R... |
Django - How to rename a model field using South? | 3,235,995 | 198 | 2010-07-13T09:53:02Z | 3,239,421 | 14 | 2010-07-13T16:49:30Z | [
"python",
"django",
"django-models",
"django-south"
] | I would like to change a name of specific fields in a model:
```
class Foo(models.Model):
name = models.CharField()
rel = models.ForeignKey(Bar)
```
should change to:
```
class Foo(models.Model):
full_name = models.CharField()
odd_relation = models.ForeignKey(Bar)
```
What's the easiest way to... | I didn't know about db.rename column, sounds handy, however in the past I have added the new column as one schemamigration, then created a datamigration to move values into the new field, then a second schemamigration to remove the old column |
Django - How to rename a model field using South? | 3,235,995 | 198 | 2010-07-13T09:53:02Z | 20,302,278 | 38 | 2013-11-30T15:57:35Z | [
"python",
"django",
"django-models",
"django-south"
] | I would like to change a name of specific fields in a model:
```
class Foo(models.Model):
name = models.CharField()
rel = models.ForeignKey(Bar)
```
should change to:
```
class Foo(models.Model):
full_name = models.CharField()
odd_relation = models.ForeignKey(Bar)
```
What's the easiest way to... | Here's what I do:
1. Make the column name change in your model (in this example it would be `myapp/models.py`)
2. Run `./manage.py schemamigration myapp renaming_column_x --auto`
Note `renaming_column_x` can be anything you like, it's just a way of giving a descriptive name to the migration file.
This will generate ... |
Django - How to rename a model field using South? | 3,235,995 | 198 | 2010-07-13T09:53:02Z | 29,227,945 | 7 | 2015-03-24T08:29:21Z | [
"python",
"django",
"django-models",
"django-south"
] | I would like to change a name of specific fields in a model:
```
class Foo(models.Model):
name = models.CharField()
rel = models.ForeignKey(Bar)
```
should change to:
```
class Foo(models.Model):
full_name = models.CharField()
odd_relation = models.ForeignKey(Bar)
```
What's the easiest way to... | Django 1.7 introduced [Migrations](https://docs.djangoproject.com/en/1.7/topics/migrations/) so now you don't even need to install extra package to manage your migrations.
To rename your model you need to create empty migration first:
```
$ manage.py makemigrations <app_name> --empty
```
Then you need to edit your m... |
Iterating over objects in pyquery | 3,236,208 | 9 | 2010-07-13T10:29:01Z | 7,124,883 | 8 | 2011-08-19T16:55:02Z | [
"python",
"pyquery"
] | I'm scraping a page with Python's pyquery, and I'm kinda confused by the types it returns, and in particular how to iterate over a list of results.
If my HTML looks a bit like this:
```
<div class="formwrap">blah blah <h3>Something interesting</h3></div>
<div class="formwrap">more rubbish <h3>Something else interesti... | I think you can do something like this:
```
from pyquery import PyQuery as pq
def get_h3_contents(index, node):
d = pq(node)
d.find('h3').text()
formwraps.each(get_h3_contents)
```
Hope that helps someone if not the original poster. |
Iterating over objects in pyquery | 3,236,208 | 9 | 2010-07-13T10:29:01Z | 17,438,586 | 11 | 2013-07-03T02:03:52Z | [
"python",
"pyquery"
] | I'm scraping a page with Python's pyquery, and I'm kinda confused by the types it returns, and in particular how to iterate over a list of results.
If my HTML looks a bit like this:
```
<div class="formwrap">blah blah <h3>Something interesting</h3></div>
<div class="formwrap">more rubbish <h3>Something else interesti... | Since [pyquery 1.2.3](https://pypi.python.org/pypi/pyquery/1.2.3) ([commit](https://github.com/gawel/pyquery/commit/0ca5ba5dbcbbb983f0f72794acb374e3bb493279)), you can use `items()` of a `PyQuery` object for going through each item as `PyQuery` object:
```
print(type(formwraps.items()))
for my_div in formwraps.items()... |
How to create decorator for lazy initialization of a property | 3,237,678 | 6 | 2010-07-13T13:34:54Z | 3,237,722 | 13 | 2010-07-13T13:39:13Z | [
"python",
"decorator",
"descriptor",
"lazy-initialization"
] | I want to create a decorator that works like a property, only it calls the decorated function only once, and on subsequent calls always return the result of the first call. An example:
```
def SomeClass(object):
@LazilyInitializedProperty
def foo(self):
print "Now initializing"
return 5
>>> x ... | [Denis Otkidach's CachedAttribute](http://code.activestate.com/recipes/276643-caching-and-aliasing-with-descriptors/) is a method decorator which makes attributes lazy (computed once, accessible many). To make it also read-only, I added a `__set__` method. To retain the ability to recalculate (see below) I added a `__d... |
Subclassing int in Python | 3,238,350 | 26 | 2010-07-13T14:49:04Z | 3,238,445 | 41 | 2010-07-13T14:57:44Z | [
"python",
"inheritance",
"subclass",
"python-2.5"
] | I'm interested in subclassing the built-in `int` type in Python (I'm using v. 2.5), but having some trouble getting the initialization working.
Here's some example code, which should be fairly obvious.
```
class TestClass(int):
def __init__(self):
int.__init__(self, 5)
```
However, when I try to use this... | `int` is immutable so you can't modify it after they are created, use `__new__` instead
```
class TestClass(int):
def __new__(cls, *args, **kwargs):
return super(TestClass, cls).__new__(cls, 5)
print TestClass()
``` |
Does anyone have a "dark" pycharm schema file? | 3,238,893 | 13 | 2010-07-13T15:49:00Z | 3,382,427 | 9 | 2010-08-01T14:49:35Z | [
"python",
"themes",
"pycharm"
] | I'm trying out pycharm for django development and I can't stand the white background. Can someone provide a place to download a schema file? Switching all the colors manually is tedious and time consuming.
Is it possible to use komodo schemas? | I just found this wonderful theme :
<http://github.com/nek4life/pycharm-twilight> |
Does anyone have a "dark" pycharm schema file? | 3,238,893 | 13 | 2010-07-13T15:49:00Z | 16,975,742 | 8 | 2013-06-07T03:22:04Z | [
"python",
"themes",
"pycharm"
] | I'm trying out pycharm for django development and I can't stand the white background. Can someone provide a place to download a schema file? Switching all the colors manually is tedious and time consuming.
Is it possible to use komodo schemas? | Tomorrow Night has been ported to IntelliJ / PyCharms
<https://github.com/chriskempson/tomorrow-theme>
<https://github.com/chriskempson/tomorrow-theme/tree/master/Jetbrains>
## Tomorrow Night Theme
Sorry, screenshot is in Ruby |
Python URLLib / URLLib2 POST | 3,238,925 | 27 | 2010-07-13T15:53:03Z | 3,239,251 | 39 | 2010-07-13T16:29:25Z | [
"python",
"post",
"urllib2",
"urllib"
] | I'm trying to create a super-simplistic Virtual In / Out Board using wx/Python. I've got the following code in place for one of my requests to the server where I'll be storing the data:
```
data = urllib.urlencode({'q': 'Status'})
u = urllib2.urlopen('http://myserver/inout-tracker', data)
for line in u.readlines():
... | ```
u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)
```
Using the path `/inout-tracker` without a trailing `/` doesn't fetch `index.php`. Instead the server will issue a `302` redirect to the version with the trailing `/`.
Doing a 302 will typica... |
How can I open an Excel file in Python? | 3,239,207 | 34 | 2010-07-13T16:26:10Z | 3,239,246 | 12 | 2010-07-13T16:29:15Z | [
"python",
"excel"
] | How do I open a file that is an Excel file for reading in Python?
I've opened text files, for example, `sometextfile.txt` with the reading command. How do I do that for an Excel file? | This isn't as straightforward as opening a plain text file and will require some sort of external module since nothing is built-in to do this. Here are some options:
<http://www.python-excel.org/>
If possible, you may want to consider exporting the excel spreadsheet as a CSV file and then using the built-in python cs... |
How can I open an Excel file in Python? | 3,239,207 | 34 | 2010-07-13T16:26:10Z | 3,239,248 | 23 | 2010-07-13T16:29:22Z | [
"python",
"excel"
] | How do I open a file that is an Excel file for reading in Python?
I've opened text files, for example, `sometextfile.txt` with the reading command. How do I do that for an Excel file? | Try [the xlrd library](http://www.lexicon.net/sjmachin/xlrd.htm).
**[Edit]** - from what I can see from your comment, something like the snippet below might do the trick. I'm assuming here that you're just searching one column for the word 'john', but you could add more or make this into a more generic function.
```
... |
How can I open an Excel file in Python? | 3,239,207 | 34 | 2010-07-13T16:26:10Z | 17,291,339 | 24 | 2013-06-25T07:16:42Z | [
"python",
"excel"
] | How do I open a file that is an Excel file for reading in Python?
I've opened text files, for example, `sometextfile.txt` with the reading command. How do I do that for an Excel file? | you can use pandas package as well....
When you are working with an excel file with multiple sheets, you can use:
```
import pandas as pd
xl = pd.ExcelFile(path + filename)
xl.sheet_names
>>> [u'Sheet1', u'Sheet2', u'Sheet3']
df = xl.parse("Sheet1")
df.head()
```
`df.head()` will print first 5 rows of your Excel f... |
How to manage python threads results? | 3,239,617 | 9 | 2010-07-13T17:15:36Z | 3,239,710 | 13 | 2010-07-13T17:26:12Z | [
"python",
"multithreading",
"arrays"
] | I am using this code:
```
def startThreads(arrayofkeywords):
global i
i = 0
while len(arrayofkeywords):
try:
if i<maxThreads:
keyword = arrayofkeywords.pop(0)
i = i+1
thread = doStuffWith(keyword)
thread.start()
exc... | Use a [`Queue.Queue`](http://docs.python.org/library/queue.html) instance, which is intrinsically thread-safe. Each thread can `.put` its results to that global instance when it's done, and the main thread (when it knows all working threads are done, by `.join`ing them for example as in @unholysampler's answer) can loo... |
How to manage python threads results? | 3,239,617 | 9 | 2010-07-13T17:15:36Z | 3,239,815 | 10 | 2010-07-13T17:37:04Z | [
"python",
"multithreading",
"arrays"
] | I am using this code:
```
def startThreads(arrayofkeywords):
global i
i = 0
while len(arrayofkeywords):
try:
if i<maxThreads:
keyword = arrayofkeywords.pop(0)
i = i+1
thread = doStuffWith(keyword)
thread.start()
exc... | First, you actually need to save *all* those `thread` objects to call `join()` on them. As written, you're saving only the last one of them, and then only if there isn't an exception.
An easy way to do multithreaded programming is to give each thread all the data it needs to run, and then have it not write to anything... |
Generate UUID for Cassandra in Python | 3,240,267 | 10 | 2010-07-13T18:34:44Z | 3,240,346 | 9 | 2010-07-13T18:44:18Z | [
"python",
"cassandra",
"uuid",
"pycassa"
] | Heh,
I'm using
`cf.insert(uuid.uuid1().bytes_le, {'column1': 'val1'})` (pycassa)
to create a TimeUUID for Cassandra, but getting the error
```
InvalidRequestException:
InvalidRequestException(why='UUIDs must be exactly 16 bytes')
```
It doesn't work with
```
uuid.uuid1()
uuid.uuid1().bytes
str(uuid.uuid1())
```
... | Looks like you are using the uuid as the row key and not the column name.
The '**compare\_with: TimeUUIDType**' attribute specifies that the column names will be compared with using the TimeUUIDType, i.e it [tells Cassandra how to sort the *columns* for slicing operations](http://wiki.apache.org/cassandra/StorageConfi... |
How to increment the day in datetime? Python | 3,240,458 | 64 | 2010-07-13T18:58:04Z | 3,240,486 | 112 | 2010-07-13T19:01:46Z | [
"python",
"datetime"
] | How to increment the day in datetime? In python.
```
for i in xrange(1,5)
date=datetime.datetime(2003,8,i,12,4,5)
print date
```
But i need pass through years? Any ideas?
Should be easyier way.... | ```
date = datetime.datetime(2003,8,1,12,4,5)
for i in range(5):
date += datetime.timedelta(days=1)
print(date)
``` |
How to increment the day in datetime? Python | 3,240,458 | 64 | 2010-07-13T18:58:04Z | 3,240,493 | 29 | 2010-07-13T19:02:22Z | [
"python",
"datetime"
] | How to increment the day in datetime? In python.
```
for i in xrange(1,5)
date=datetime.datetime(2003,8,i,12,4,5)
print date
```
But i need pass through years? Any ideas?
Should be easyier way.... | Incrementing dates can be accomplished using timedelta objects:
```
import datetime
datetime.datetime.now() + datetime.timedelta(days=1)
```
Look up timedelta objects in the Python docs: <http://docs.python.org/library/datetime.html> |
Getting python exceptions printed the normal way with PyObjC | 3,240,867 | 2 | 2010-07-13T19:46:29Z | 3,609,745 | 7 | 2010-08-31T14:01:12Z | [
"python",
"objective-c",
"exception",
"exception-handling",
"pyobjc"
] | I'm getting errors like this:
> 2010-07-13 20:43:15.131
> Python[1527:60f] main: Caught
> OC\_PythonException: :
> LoginMenuSet instance has no attribute
> 'play\_sound'
That's with this code:
```
@try {
[section loop]; //Loop through section
} @catch (NSException *exception) {
NSLog(@"Caught %@: %@", [excep... | One trick to see Python exceptions is to call `objc.setVerbose(1)`. This makes PyObjC slightly more verbose and causes it to print Python stack traces when converting exceptions from Python to Objective-C. |
Authentication in Google App Engine: app.yaml vs. python code | 3,240,990 | 4 | 2010-07-13T20:01:37Z | 3,241,214 | 13 | 2010-07-13T20:25:09Z | [
"python",
"google-app-engine",
"authentication"
] | I am writing a small app that uses the GAE. I have parts of my app that are for administrative use only. I have two options using `login: admin` option in the app.yaml or `google.appengine.api.users.is_current_user_admin()` in python code. The basic authentication is sufficient for my case.
Which solution is better?
... | I would say your assertions are correct. Let's say you have the following in your app.yaml:
```
- url: /admin/.*
script: admin.py
login: admin
```
If you want everything in `admin.py` to be restricted to administrators, the configuration above ought to be more performant: you can fail unauthorized requests withou... |
obtaining error number of an error | 3,241,378 | 6 | 2010-07-13T20:45:01Z | 3,241,538 | 7 | 2010-07-13T21:08:19Z | [
"python",
"error-handling",
"paramiko"
] | I need to obtain the error number from an error that has occurred in Python.
Ex; When trying to transfer a directory via the Paramiko package, an error is caught with this piece of code:
```
try:
sftp.put(local_path,target_path)
except (IOError,OSError),errno:
print "Error:",errno
```
For which I get the... | Thanks for clarifying your question.
Most `Exception`s in Python don't have "error numbers". One exception (no pun intended) are `HTTPError` exceptions, for example:
```
import urllib2
try:
page = urllib2.urlopen("some url")
except urllib2.HTTPError, err:
if err.code == 404:
print "Page not found!"
e... |
Printing numbers in python | 3,241,594 | 9 | 2010-07-13T21:16:02Z | 3,241,656 | 7 | 2010-07-13T21:23:04Z | [
"python"
] | I have a script that generates some numbers (specifically times in epoch form).
Everytime it generates a number, I append the number to an array (called VALUES) and print both the array and that number. However, the number does not contain as many places after the decimal as the number in the array.
For example, a sa... | When python prints out a number, it sometimes prints out more decimal places based on whether the internal method is calling `repr` or `str` (which both convert the number to a string). `repr` will return more decimal places, while str does not.
`print` calls `str`, so when you do `print Number`, it will trim it a tad... |
How to install SSL for python 2.5 on Debian Linux? | 3,241,658 | 4 | 2010-07-13T21:23:12Z | 6,978,110 | 8 | 2011-08-08T05:35:11Z | [
"python",
"ssl",
"installation"
] | ## Question
How do I install SSL for Python 2.5 on Debian?
I have tried:
```
sudo easy_install ssl
```
But getting:
```
$ python setup.py build
looking for /usr/include/openssl/ssl.h
looking for /usr/include/krb5.h
running build
running build_py
running build_ext
building 'ssl._ssl2' extension
creating build/temp.... | For reference, you must install `libbluetooth-dev`. |
Problems adding path and calling external program from Python | 3,241,735 | 3 | 2010-07-13T21:35:23Z | 3,241,761 | 7 | 2010-07-13T21:38:29Z | [
"python",
"linux"
] | I have an executable called "foo" in "/home/myname/mydir/" and am trying to call it from Python, but I am doing something basic and wrong here. Can you help me?
```
import os, sys
sys.path.append("/home/myname/mydir/")
os.system("foo") # os.system("./foo") doesn't work either
```
Thanks | `sys.path` is the path to Python libraries, not the system PATH to search for binaries. Try changing `os.environ['PATH']` instead.
```
>>> sys.path.append("/opt/local/bin")
>>> os.system("wget")
sh: wget: command not found
32512
>>> os.environ['PATH'] += os.pathsep + '/opt/local/bin'
>>> os.system("wget")
wget: missin... |
Python - Find dominant/most common color in an image | 3,241,929 | 31 | 2010-07-13T22:05:55Z | 3,242,290 | 9 | 2010-07-13T23:19:07Z | [
"python",
"image",
"image-processing",
"colors"
] | I'm looking for a way to find the most dominant color/tone in an image using python. Either the average shade or the most common out of RGB will do. I've looked at the Python Imaging library, and could not find anything relating to what I was looking for in their manual, and also briefly at VTK.
I did however find a P... | Python Imaging Library has method getcolors on Image objects:
> **im.getcolors()** => a list of (count,
> color) tuples or None
I guess you can still try resizing the image before that and see if it performs any better. |
Python - Find dominant/most common color in an image | 3,241,929 | 31 | 2010-07-13T22:05:55Z | 3,244,061 | 30 | 2010-07-14T07:14:42Z | [
"python",
"image",
"image-processing",
"colors"
] | I'm looking for a way to find the most dominant color/tone in an image using python. Either the average shade or the most common out of RGB will do. I've looked at the Python Imaging library, and could not find anything relating to what I was looking for in their manual, and also briefly at VTK.
I did however find a P... | Here's code making use of [PIL](http://www.pythonware.com/products/pil/) and [Scipy's cluster package](http://docs.scipy.org/doc/scipy/reference/cluster.html).
For simplicity I've hardcoded the filename as "image.jpg". Resizing the image is for speed: if you don't mind the wait, comment out the resize call. When run o... |
Why does python think this is a local variable? | 3,241,930 | 4 | 2010-07-13T22:06:11Z | 3,241,959 | 14 | 2010-07-13T22:10:22Z | [
"python"
] | I have a global variable I called Y\_VAL which is initialized to a value of 2.
I then have a function, called f() (for brevity), which uses Y\_VAL.
```
def f():
y = Y_VAL
Y_VAL += 2
```
However, when trying to run my code, python gives the error message:
```
UnboundLocalError: local variable 'Y_VAL' referen... | You're missing the line `global Y_VAL` inside the function.
When `Y_VAL` occurs on the right-hand-side of an assignment, it's no problem because the local scope is searched first, then the global scope is searched. However, on the left-hand-side, you can only *assign* to a global that way when you've explicitly declar... |
Django (1.2) Forms: ManyToManyField Help Text | 3,242,174 | 8 | 2010-07-13T22:50:14Z | 4,530,783 | 13 | 2010-12-25T16:26:20Z | [
"python",
"django",
"django-forms",
"manytomanyfield"
] | I hope I'm wrong, but it looks to me like the only way to have no `help_text` for a ManyToManyField is write an `__init__` method for the form and overwrite `self.fields[fieldname].help_text`. Is that really the only way? I prefer to use `CheckboxSelectMultple` widgets, so am I really going to have to define an `__init... | ```
class Item(models.Model):
...
category = models.ManyToManyField(Category, null=True,blank=True)
category.help_text = ''
...
``` |
In Python, how does a for loop with `range` work? | 3,242,314 | 19 | 2010-07-13T23:24:26Z | 3,242,325 | 15 | 2010-07-13T23:26:33Z | [
"python"
] | ```
for number in range(1,101):
print number
```
Can someone please explain to me why the above code prints 1-100? I understand that the range function excludes the last number in the specified range, however, what is the 'number' part of the syntax?
I am more used to C++ & Java where I'd write the code like:
```
f... | `number` is equivalent to `i` in your C loop, i.e., it is a **variable** that holds the value of each loop iteration.
A simple translation of your Python code to C would result in something along these lines:
```
for (int number = 1; number < 101; number++) {
printf("%d\n", number);
}
``` |
In Python, how does a for loop with `range` work? | 3,242,314 | 19 | 2010-07-13T23:24:26Z | 3,242,334 | 8 | 2010-07-13T23:28:03Z | [
"python"
] | ```
for number in range(1,101):
print number
```
Can someone please explain to me why the above code prints 1-100? I understand that the range function excludes the last number in the specified range, however, what is the 'number' part of the syntax?
I am more used to C++ & Java where I'd write the code like:
```
f... | [Python 2.7 documentation](http://docs.python.org/library/functions.html) states:
> range([start], stop[, step])¶
>
> This is a versatile function to create
> lists containing arithmetic
> progressions. It is most often used in
> for loops. The arguments must be plain
> integers. If the step argument is
> omitted, it... |
Interpolation over an irregular grid | 3,242,382 | 15 | 2010-07-13T23:37:18Z | 3,244,618 | 7 | 2010-07-14T08:51:23Z | [
"python",
"numpy",
"scipy",
"interpolation"
] | So, I have three numpy arrays which store latitude, longitude, and some property value on a grid -- that is, I have LAT(y,x), LON(y,x), and, say temperature T(y,x), for some limits of x and y. The grid isn't necessarily regular -- in fact, it's tripolar.
I then want to interpolate these property (temperature) values o... | Try the combination of inverse-distance weighting and
[scipy.spatial.KDTree](http://docs.scipy.org/doc/scipy/reference/spatial.html)
described in SO
[inverse-distance-weighted-idw-interpolation-with-python](http://stackoverflow.com/questions/3104781/inverse-distance-weighted-idw-interpolation-with-python).
[Kd-trees](h... |
Pythonic syntax for appending an arbitrary class object list property | 3,242,391 | 4 | 2010-07-13T23:39:57Z | 3,242,400 | 9 | 2010-07-13T23:43:33Z | [
"python"
] | Is there an analog of `setattr()` that allows for appending an arbitrary list property of an instantiated class object? If not, is there a recommended way of doing so?
This is a trivialized version of what I'm doing currently:
```
foo = SomeClass()
...
attr = "names"
value = "Eric"
values = getattr(foo, attr)
values.... | The `setattr` call is redundant, *if* `foo.names` is indeed a list (if it's something else, could you please clarify?). `getattr(foo, attr).append(value)` is all you need. |
Unit testing infrastructure for a python module | 3,242,875 | 7 | 2010-07-14T02:01:57Z | 3,242,931 | 11 | 2010-07-14T02:15:19Z | [
"python",
"unit-testing",
"code-coverage",
"doctest"
] | I'm writing a python module and I would like to unit test it. I am new to python and somewhat bamboozled by the options available.
Currently, I would like to write my tests as [doctests](http://docs.python.org/library/doctest.html) as I like the declarative rather than imperative style (however, feel free to disabuse ... | > feel free to disabuse me of this
> preference if it is misinformed
I believe I used `doctest` more extensively (*way* stretching its intended use boundaries) than any other open source developer, at least within a single project -- *all* the tests in my [gmpy](http://code.google.com/p/gmpy/) project are doctests. It... |
Django unable to find MySQLdb python module | 3,243,073 | 18 | 2010-07-14T02:49:55Z | 3,256,288 | 33 | 2010-07-15T14:05:34Z | [
"python",
"django",
"mysql"
] | Installed Django from source (python setup.py install and such), installed MySQLdb from source (python setup.py build, python setup.py install). Using Python 2.4 which came installed on the OS (CentOS 5.5). Getting the following error message after launching the server:
```
Error loading MySQLdb module: No module name... | Have you considered installing MySQLdb from python packages?
I would also recommend doing this with `pip` instead of `easy_install`.
First you can replace `easy_install` with `pip`:
```
easy_install pip
pip install pip --upgrade
```
And then install Django via PIP:
```
pip install MySQL-python
pip install Django
``... |
Django unable to find MySQLdb python module | 3,243,073 | 18 | 2010-07-14T02:49:55Z | 5,054,267 | 16 | 2011-02-19T23:45:29Z | [
"python",
"django",
"mysql"
] | Installed Django from source (python setup.py install and such), installed MySQLdb from source (python setup.py build, python setup.py install). Using Python 2.4 which came installed on the OS (CentOS 5.5). Getting the following error message after launching the server:
```
Error loading MySQLdb module: No module name... | Did you try building the dependencies? This solved it for me on Ubuntu:
```
sudo apt-get build-dep python-mysqldb
pip install MySQLdb-python
``` |
Django unable to find MySQLdb python module | 3,243,073 | 18 | 2010-07-14T02:49:55Z | 14,905,844 | 7 | 2013-02-16T01:10:48Z | [
"python",
"django",
"mysql"
] | Installed Django from source (python setup.py install and such), installed MySQLdb from source (python setup.py build, python setup.py install). Using Python 2.4 which came installed on the OS (CentOS 5.5). Getting the following error message after launching the server:
```
Error loading MySQLdb module: No module name... | What worked for me (Linux Mint):
```
sudo apt-get install libmysqlclient-dev (this was the key for me)
pip install mysql-python
pip install django
``` |
python twisted threading | 3,243,431 | 3 | 2010-07-14T04:45:31Z | 3,247,714 | 13 | 2010-07-14T15:26:09Z | [
"python",
"twisted"
] | Hi can you please tell me how use different functions in different thread using thread pool
in twisted...say
I have a list of ids `x=[1,2,3,4]` where 1,2,...etc are ids(I got from data base and each one contains python script in some where disk).
what I want to do is
scanning of x traverse on list and run every scri... | Threads in Twisted are primarily used via `twisted.internet.threads.deferToThread`. Alternatively, there's a new interface which is slightly more flexible, `twisted.internet.threads.deferToThreadPool`. Either way, the answer is roughly the same, though. Iterate over your data and use one of these functions to dispatch ... |
No more BeautifulSoup | 3,244,335 | 3 | 2010-07-14T08:05:06Z | 3,244,458 | 13 | 2010-07-14T08:27:36Z | [
"python",
"parsing"
] | I have been using BeautifulSoup but as I understand it that library is no longer being maintained. So what should I use ? I have heard about Xpath but what else is there ? | There was a [bugfix release in April](http://groups.google.com/group/beautifulsoup/browse_thread/thread/67b8b6d82e7e4818#), so I'm not even sure where you get the idea that it's no longer being maintained. However, even if that were true, BeautifulSoup is still plenty functional and I don't really see even the current ... |
Python equivalent of Curl HTTP post | 3,246,021 | 11 | 2010-07-14T12:26:21Z | 3,246,066 | 18 | 2010-07-14T12:31:44Z | [
"python",
"http",
"curl"
] | I am posting to Hudson server using curl from the command line using the following--
```
curl -X POST -d '<run><log encoding="hexBinary">4142430A</log><result>0</result><duration>2000</duration></run>' \
http://user:pass@myhost/hudson/job/_jobName_/postBuildResult
```
as shown in the hudson documentation..can I emula... | ```
import urllib2
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
result = response.read()
```
where data is the encoded data you want to POST.
You can encode a dict using urllib like this:
```
import urllib
values = { 'foo': 'bar' }
data = urllib.urlencode(values)
``` |
variable table name in sqlite | 3,247,183 | 18 | 2010-07-14T14:34:39Z | 3,247,553 | 17 | 2010-07-14T15:10:32Z | [
"python",
"database",
"sqlite",
"table"
] | Question: Is it possible to use a variable as your table name w/o having to use string constructors to do so?
---
Info:
I'm working on a project right now that catalogs data from a star simulation of mine. To do so I'm loading all the data into a sqlite database. It's working pretty well, but I've decided to add a l... | Unfortunately, tables can't be the target of parameter substitution (I didn't find any definitive source, but I have seen it on a few web forums).
If you are worried about injection (you probably should be), you can write a function that cleans the string before passing it. Since you are looking for just a table name,... |
How to elementwise-multiply a scipy.sparse matrix by a broadcasted dense 1d array? | 3,247,775 | 30 | 2010-07-14T15:31:55Z | 3,357,645 | 34 | 2010-07-28T21:27:58Z | [
"python",
"numpy",
"scipy",
"sparse-matrix"
] | Suppose I have a 2d sparse array. In my real usecase both the number of rows and columns are much bigger (say 20000 and 50000) hence it cannot fit in memory when a dense representation is used:
```
>>> import numpy as np
>>> import scipy.sparse as ssp
>>> a = ssp.lil_matrix((5, 3))
>>> a[1, 2] = -1
>>> a[4, 1] = 2
>>... | I replied over at scipy.org as well, but I thought I should add an answer here, in case others find this page when searching.
You can turn the vector into a sparse diagonal matrix and then use matrix multiplication (with \*) to do the same thing as broadcasting, but efficiently.
```
>>> d = ssp.lil_matrix((3,3))
>>> ... |
How to elementwise-multiply a scipy.sparse matrix by a broadcasted dense 1d array? | 3,247,775 | 30 | 2010-07-14T15:31:55Z | 4,503,369 | 17 | 2010-12-21T20:01:07Z | [
"python",
"numpy",
"scipy",
"sparse-matrix"
] | Suppose I have a 2d sparse array. In my real usecase both the number of rows and columns are much bigger (say 20000 and 50000) hence it cannot fit in memory when a dense representation is used:
```
>>> import numpy as np
>>> import scipy.sparse as ssp
>>> a = ssp.lil_matrix((5, 3))
>>> a[1, 2] = -1
>>> a[4, 1] = 2
>>... | I think A.multiply(B) should work in scipy sparse. The method multiply does "point-wise" multiplication, not matrix multiplication.
HTH |
How find values in an array that meet two conditions using Python | 3,248,542 | 18 | 2010-07-14T16:55:55Z | 3,248,599 | 20 | 2010-07-14T17:03:34Z | [
"python",
"find",
"numpy"
] | I have an array
```
a=[1,2,3,4,5,6,7,8,9]
```
and I want to find the indices of the element s that meet two conditions i.e.
```
a>3 and a<8
ans=[3,4,5,6]
a[ans]=[4,5,6,7]
```
I can use `numpy.nonzero(a>3)` or `numpy.nonzero(a<8)`
but not
`numpy.nonzero(a>3 and a<8)` which gives the error:
```
ValueError: The truth... | ```
numpy.nonzero((a > 3) & (a < 8))
```
& does an element-wise boolean and. |
Setting an excel sheet in landscape mode from XLWT | 3,248,993 | 6 | 2010-07-14T17:56:59Z | 3,249,174 | 7 | 2010-07-14T18:20:45Z | [
"python",
"excel",
"xlwt"
] | I have a Python program that creates an excel sheet, but I have been asked by one of the users to modify it so that if he hits print it will print out to landscape mode, without him having to specify this. Is there some way to set the sheet to landscape in XLWT or some similar Python library for excel?
Thank you. | With XLWT, I believe it's as easy as:
```
worksheetObject.portrait = False
``` |
Override "remaining elements truncated" in Python | 3,249,287 | 11 | 2010-07-14T18:37:22Z | 3,249,390 | 20 | 2010-07-14T18:48:22Z | [
"python",
"django"
] | I'm using the Python shell in Django to make some queries. The results keep getting truncated. I get the message, "remaining elements truncated." How can I see all the results? Or, how can I write the results to a file? | Querysets do this automatically when you just output them in the shell - which implictly calls `repr` on them. If you call `list` on the queryset instead, that will output everything:
```
list(MyModel.objects.all())
```
Note that you don't need to do this within your code, this is just for output within the shell. Ob... |
Print in one line dynamically | 3,249,524 | 124 | 2010-07-14T19:03:37Z | 3,249,537 | 41 | 2010-07-14T19:05:42Z | [
"python",
"printing"
] | I would like to make several statements that give standard output without seeing newlines in between statements.
Specifically, suppose I have:
```
for item in range(1,100):
print item
```
The result is:
```
1
2
3
4
.
.
.
```
How get this to instead look like:
```
1 2 3 4 5 ...
```
Even better, is it possible... | Use `print item,` to make the print statement omit the newline.
In Python 3, it's `print(item, end=" ")`.
If you want every number to display in the same place, use for example (Python 2.7):
```
to = 20
digits = len(str(to - 1))
delete = "\b" * (digits + 1)
for i in range(to):
print "{0}{1:{2}}".format(delete, i... |
Print in one line dynamically | 3,249,524 | 124 | 2010-07-14T19:03:37Z | 3,249,539 | 239 | 2010-07-14T19:05:48Z | [
"python",
"printing"
] | I would like to make several statements that give standard output without seeing newlines in between statements.
Specifically, suppose I have:
```
for item in range(1,100):
print item
```
The result is:
```
1
2
3
4
.
.
.
```
How get this to instead look like:
```
1 2 3 4 5 ...
```
Even better, is it possible... | Change `print item` to:
* `print item,` in Python 2.7
* `print(item, end=" ")` in Python 3 |
Print in one line dynamically | 3,249,524 | 124 | 2010-07-14T19:03:37Z | 3,249,563 | 12 | 2010-07-14T19:08:03Z | [
"python",
"printing"
] | I would like to make several statements that give standard output without seeing newlines in between statements.
Specifically, suppose I have:
```
for item in range(1,100):
print item
```
The result is:
```
1
2
3
4
.
.
.
```
How get this to instead look like:
```
1 2 3 4 5 ...
```
Even better, is it possible... | You can add a trailing comma to your print statement to print a space instead of a newline in each iteration:
```
print item,
```
Alternatively, if you're using Python 2.6 or later, you can use the new print function, which would allow you to specify that not even a space should come at the end of each item being pri... |
Print in one line dynamically | 3,249,524 | 124 | 2010-07-14T19:03:37Z | 3,249,684 | 105 | 2010-07-14T19:22:08Z | [
"python",
"printing"
] | I would like to make several statements that give standard output without seeing newlines in between statements.
Specifically, suppose I have:
```
for item in range(1,100):
print item
```
The result is:
```
1
2
3
4
.
.
.
```
How get this to instead look like:
```
1 2 3 4 5 ...
```
Even better, is it possible... | > By the way...... How to refresh it every time so it print mi in one place just change the number.
In general, the way to do that is with [terminal control codes](http://www.termsys.demon.co.uk/vtansi.htm). This is a particularly simple case, for which you only need one special character: U+000D CARRIAGE RETURN, whic... |
Print in one line dynamically | 3,249,524 | 124 | 2010-07-14T19:03:37Z | 6,361,028 | 12 | 2011-06-15T16:27:23Z | [
"python",
"printing"
] | I would like to make several statements that give standard output without seeing newlines in between statements.
Specifically, suppose I have:
```
for item in range(1,100):
print item
```
The result is:
```
1
2
3
4
.
.
.
```
How get this to instead look like:
```
1 2 3 4 5 ...
```
Even better, is it possible... | Like the other examples,
I use a similar approach but instead of spending time calculating out the last output length, etc,
I simply use ANSI code escapes to move back to the beginning of the line and then clear that entire line before printing my current status output.
```
import sys
class Printer():
"""Print... |
How to print a string of variables without spaces in Python (minimal coding!) | 3,249,949 | 3 | 2010-07-14T19:56:43Z | 3,249,993 | 7 | 2010-07-14T20:03:14Z | [
"python",
"printing",
"stdout"
] | I have something like : `print "\n","|",id,"|",var1,"|",var2,"|",var3,"|",var4,"|"`
It prints with spaces for each variable.
```
| 1 | john | h | johnny | mba |
```
I want something like this :
```
|1|john|h|johnny|mba|
```
I have 20 variables that I have to print and I hate use sys.stdout.write(var) for each one ... | For a variable number of values:
```
print '|%s|' % '|'.join(str(x) for x in [id, var1, var2, var3, var4])
``` |
How can Twisted Deferred errors without errbacks be tested with trial? | 3,250,168 | 9 | 2010-07-14T20:24:40Z | 3,252,306 | 15 | 2010-07-15T03:44:12Z | [
"python",
"unit-testing",
"testing",
"twisted"
] | I have some Twisted code which creates multiple chains of Deferreds. Some of these may fail without having an errback which puts them back on the callback chain. I haven't been able to write a unit test for this code - the failing Deferred causes the test to fail after the test code has completed. How can I write a pas... | There are two important things about trial related to this question.
First, a test method will not pass if a Failure is logged while it is running. Deferreds which are garbage collected with a Failure result cause the Failure to be logged.
Second, a test method which returns a Deferred will not pass if the Deferred f... |
Python twisted asynchronous write using deferred | 3,250,327 | 2 | 2010-07-14T20:42:24Z | 3,261,650 | 8 | 2010-07-16T03:04:05Z | [
"python",
"asynchronous",
"twisted"
] | With regard to the Python Twisted framework, can someone explain to me how to write asynchronously a very large data string to a consumer, say the protocol.transport object?
I think what I am missing is a `write(data_chunk)` function that returns a `Deferred`. This is what I would like to do:
```
data_block = get_lot... | As Jean-Paul says, you should use [IProducer and IConsumer](http://twistedmatrix.com/documents/10.1.0/core/howto/producers.html), but you should also note that the lack of `deferredWrite` is a somewhat intentional omission.
For one thing, creating a `Deferred` for potentially every byte of data that gets written is a ... |
Using Windows Python from Cygwin | 3,250,749 | 48 | 2010-07-14T21:38:54Z | 3,250,975 | 21 | 2010-07-14T22:11:51Z | [
"python",
"windows",
"cygwin"
] | I've been using Cygwin on Windows recently. I want to use the Windows installation of Python, so during testing I'm using `/cygdrive/c/Python26/python.exe myfile.py` rather than `python myfile.exe`.
This is working almost perfectly, except for printing. When I run the Windows Python from Cygwin the output doesn't prin... | Perhaps if you flush the output
```
import sys
V = range(100000)
for x in V:
print x
sys.stdout.flush()
``` |
Using Windows Python from Cygwin | 3,250,749 | 48 | 2010-07-14T21:38:54Z | 9,549,255 | 96 | 2012-03-03T19:44:01Z | [
"python",
"windows",
"cygwin"
] | I've been using Cygwin on Windows recently. I want to use the Windows installation of Python, so during testing I'm using `/cygdrive/c/Python26/python.exe myfile.py` rather than `python myfile.exe`.
This is working almost perfectly, except for printing. When I run the Windows Python from Cygwin the output doesn't prin... | The real problem is that when you run a command in any of the Cygwin terminal programs like mintty, they don't act as Windows Consoles. Only Windows Console-based ones like CMD or Console2 do that. So, with Cygwin terminals the Windows python.exe doesn't think it is talking to an interactive console.
That leads to buf... |
Using Windows Python from Cygwin | 3,250,749 | 48 | 2010-07-14T21:38:54Z | 12,245,297 | 27 | 2012-09-03T09:34:53Z | [
"python",
"windows",
"cygwin"
] | I've been using Cygwin on Windows recently. I want to use the Windows installation of Python, so during testing I'm using `/cygdrive/c/Python26/python.exe myfile.py` rather than `python myfile.exe`.
This is working almost perfectly, except for printing. When I run the Windows Python from Cygwin the output doesn't prin... | Not answering the initial question, but for those who want to use **Python interactive session** from within Cygwin terminal (for example in mintty) - start Python with "-i" option to tell it explicitly that it needs to run in interactive mode:
```
$ python -i
```
The neat way is also to create an alias in your .bash... |
Automatically recognize patterns in images | 3,251,069 | 5 | 2010-07-14T22:34:06Z | 3,251,373 | 8 | 2010-07-14T23:32:34Z | [
"python",
"algorithm",
"image-processing",
"python-imaging-library"
] | Recently I downloaded some flags from the [CIA world factbook](https://www.cia.gov/library/publications/the-world-factbook/docs/flagsoftheworld.html). Now I want to "classify them.
1. Get the colors
2. Get some shapes (stars, moons etc.)
While browsing I came across the Python Image Library which allows me to extract... | The Python Imaging Library - PIL just does basic image manipulation - opening, some transforms or filters, and saving to other formats.
Pattern recognition, is part of an advanced image processign field and evolving -- it deos use algorithms far different than those present in PIL.
There are some libraries and framew... |
Numpy and line intersections | 3,252,194 | 11 | 2010-07-15T03:03:25Z | 3,252,222 | 14 | 2010-07-15T03:13:46Z | [
"python",
"performance",
"numpy",
"line-intersection"
] | How would I use numpy to calculate the intersection between two line segments?
In the code I have segment1 = ((x1,y1),(x2,y2)) and segment2 = ((x1,y1),(x2,y2)). Note segment 1 does not equal segment2. So in my code I've also been calculating the slope and y-intercept, it would be nice if that could be avoided but I do... | Stolen directly from <http://www.cs.mun.ca/~rod/2500/notes/numpy-arrays/numpy-arrays.html>
```
#
# line segment intersection using vectors
# see Computer Graphics by F.S. Hill
#
from numpy import *
def perp( a ) :
b = empty_like(a)
b[0] = -a[1]
b[1] = a[0]
return b
# line segment a given by endpoints ... |
Numpy and line intersections | 3,252,194 | 11 | 2010-07-15T03:03:25Z | 9,110,966 | 7 | 2012-02-02T10:44:41Z | [
"python",
"performance",
"numpy",
"line-intersection"
] | How would I use numpy to calculate the intersection between two line segments?
In the code I have segment1 = ((x1,y1),(x2,y2)) and segment2 = ((x1,y1),(x2,y2)). Note segment 1 does not equal segment2. So in my code I've also been calculating the slope and y-intercept, it would be nice if that could be avoided but I do... | This is is a late response, perhaps, but it was the first hit when I Googled 'numpy line intersections'. In my case, I have two lines in a plane, and I wanted to quickly get any intersections between them, and Hamish's solution would be slow -- requiring a nested for loop over all line segments.
Here's how to do it wi... |
Python: Why is functools.partial necessary? | 3,252,228 | 121 | 2010-07-15T03:16:10Z | 3,252,364 | 47 | 2010-07-15T04:03:37Z | [
"python",
"functional-programming",
"partial-application"
] | Partial application is cool. What functionality does [`functools.partial`](http://docs.python.org/2/library/functools.html#functools.partial) offer that you can't get through lambdas?
```
>>> sum = lambda x, y : x + y
>>> sum(1, 2)
3
>>> incr = lambda y : sum(1, y)
>>> incr(2)
3
>>> def sum2(x, y):
return x + y
>... | Well, here's an example that shows a difference:
```
In [132]: sum = lambda x, y: x + y
In [133]: n = 5
In [134]: incr = lambda y: sum(n, y)
In [135]: incr2 = partial(sum, n)
In [136]: print incr(3), incr2(3)
8 8
In [137]: n = 9
In [138]: print incr(3), incr2(3)
12 8
```
These posts by Ivan Moore expand on the ... |
Python: Why is functools.partial necessary? | 3,252,228 | 121 | 2010-07-15T03:16:10Z | 3,252,425 | 185 | 2010-07-15T04:16:21Z | [
"python",
"functional-programming",
"partial-application"
] | Partial application is cool. What functionality does [`functools.partial`](http://docs.python.org/2/library/functools.html#functools.partial) offer that you can't get through lambdas?
```
>>> sum = lambda x, y : x + y
>>> sum(1, 2)
3
>>> incr = lambda y : sum(1, y)
>>> incr(2)
3
>>> def sum2(x, y):
return x + y
>... | > What functionality does
> functools.partial offer that you can't
> get through lambdas?
Not much in terms of extra *functionality* (but, see later) -- and, readability is in the eye of the beholder. Most people who are familiar with functional programming languages (those in the Lisp/Scheme families in particular) a... |
Python: Why is functools.partial necessary? | 3,252,228 | 121 | 2010-07-15T03:16:10Z | 18,627,082 | 7 | 2013-09-05T03:08:02Z | [
"python",
"functional-programming",
"partial-application"
] | Partial application is cool. What functionality does [`functools.partial`](http://docs.python.org/2/library/functools.html#functools.partial) offer that you can't get through lambdas?
```
>>> sum = lambda x, y : x + y
>>> sum(1, 2)
3
>>> incr = lambda y : sum(1, y)
>>> incr(2)
3
>>> def sum2(x, y):
return x + y
>... | Besides the extra functionality Alex mentioned, another advantage of functools.partial is speed. With partial you can avoid constructing (and destructing) another stack frame.
The function generated by partial inherits the docstring from the original function while lambdas have no docstrings by default(though you can ... |
Python: Why is functools.partial necessary? | 3,252,228 | 121 | 2010-07-15T03:16:10Z | 19,279,016 | 19 | 2013-10-09T17:41:20Z | [
"python",
"functional-programming",
"partial-application"
] | Partial application is cool. What functionality does [`functools.partial`](http://docs.python.org/2/library/functools.html#functools.partial) offer that you can't get through lambdas?
```
>>> sum = lambda x, y : x + y
>>> sum(1, 2)
3
>>> incr = lambda y : sum(1, y)
>>> incr(2)
3
>>> def sum2(x, y):
return x + y
>... | In the latest versions of Python (>=2.7), you can `pickle` a `partial`, but not a `lambda`:
```
>>> pickle.dumps(partial(int))
'cfunctools\npartial\np0\n(c__builtin__\nint\np1\ntp2\nRp3\n(g1\n(tNNtp4\nb.'
>>> pickle.dumps(lambda x: int(x))
Traceback (most recent call last):
File "<ipython-input-11-e32d5a050739>", li... |
Python: Why is functools.partial necessary? | 3,252,228 | 121 | 2010-07-15T03:16:10Z | 24,653,777 | 10 | 2014-07-09T12:31:08Z | [
"python",
"functional-programming",
"partial-application"
] | Partial application is cool. What functionality does [`functools.partial`](http://docs.python.org/2/library/functools.html#functools.partial) offer that you can't get through lambdas?
```
>>> sum = lambda x, y : x + y
>>> sum(1, 2)
3
>>> incr = lambda y : sum(1, y)
>>> incr(2)
3
>>> def sum2(x, y):
return x + y
>... | > Is functools somehow more efficient..?
As a partly answer to this I decided to test the performance. Here is my example:
```
from functools import partial
import time, math
def make_lambda():
x = 1.3
return lambda: math.sin(x)
def make_partial():
x = 1.3
return partial(math.sin, x)
Iter = 10**7
... |
Converting a number to binary with a fixed length | 3,252,528 | 6 | 2010-07-15T04:45:56Z | 3,252,544 | 24 | 2010-07-15T04:48:59Z | [
"python",
"for-loop"
] | Say I get a random number between 1 and 127. I change the number to binary and remove the `0b` from it with the fallowing code:
```
key_one= int(raw_input("Enter key (0 <= key <= 127): "))
if key_one in range(128):
bin_key_one=bin(key_one)[2:]
print bin_key_one
else:
print "You have to enter key (0 <= key <= ... | No you don't.
```
>>> '{0:07b}'.format(12)
'0001100'
``` |
Converting a number to binary with a fixed length | 3,252,528 | 6 | 2010-07-15T04:45:56Z | 3,252,583 | 10 | 2010-07-15T05:03:39Z | [
"python",
"for-loop"
] | Say I get a random number between 1 and 127. I change the number to binary and remove the `0b` from it with the fallowing code:
```
key_one= int(raw_input("Enter key (0 <= key <= 127): "))
if key_one in range(128):
bin_key_one=bin(key_one)[2:]
print bin_key_one
else:
print "You have to enter key (0 <= key <= ... | So it happens that Python has a string method `.zfill()` for that:
```
>>> '1'.zfill(7)
'0000001'
>>> '10010'.zfill(7)
'0010010'
``` |
Why is Python faster than Ruby? | 3,252,568 | 12 | 2010-07-15T04:56:30Z | 3,252,575 | 20 | 2010-07-15T04:58:43Z | [
"python",
"ruby",
"performance",
"programming-languages"
] | They seem to share a lot of the same characteristics but as far as I can tell, Python 2.5 is faster than 1.8.7 by a lot.
Is there a deeper underlying reason behind this? | One reason is Python's being compiled into bytecode which is then executed by a highly optimized VM. AFAIK Ruby doesn't work this way in 1.8 and earlier - but interprets the trees on the fly.
Think of it this way:
Python:
1. Parse code into ASTs
2. Convert ASTs into bytecode
3. Run bytecode on a VM
Ruby (prior to 1... |
Why is Python faster than Ruby? | 3,252,568 | 12 | 2010-07-15T04:56:30Z | 3,252,623 | 24 | 2010-07-15T05:10:59Z | [
"python",
"ruby",
"performance",
"programming-languages"
] | They seem to share a lot of the same characteristics but as far as I can tell, Python 2.5 is faster than 1.8.7 by a lot.
Is there a deeper underlying reason behind this? | Nothing *deep*, I am pretty sure -- it's strictly a matter of implementation choices and maturity. Python was quite a bit slower in many aspects not so long ago, after all! Consider for example:
```
$ py24 -mtimeit '[i+i for i in xrange(55)]'
100000 loops, best of 3: 10.8 usec per loop
$ py25 -mtimeit '[i+i for i in x... |
Python: Finding a (string) key in a dictionary that contains a substring | 3,252,590 | 9 | 2010-07-15T05:04:34Z | 3,252,598 | 19 | 2010-07-15T05:06:44Z | [
"python",
"data-structures",
"dictionary"
] | In my script I build a dictionary of keys(albums) mapped to artists(values) so that I can do a quick lookup of what artists made what albums. However, I want the user to be able to find all albums which contain a substring. For example a search on "Light" should return
`[Light Chasers] = Cloud Cult` and also `[Night L... | ```
[(k, v) for (k, v) in D.iteritems() if 'Light' in k]
``` |
What is the best way to write the contents of a StringIO to a file? | 3,253,258 | 9 | 2010-07-15T07:13:24Z | 3,253,819 | 16 | 2010-07-15T08:36:22Z | [
"python",
"file-io",
"stringio"
] | What is the best way to write the contents of a `StringIO` buffer to a file ?
I currently do something like:
```
buf = StringIO()
fd = open ('file.xml', 'w')
# populate buf
fd.write (buf.getvalue ())
```
But then `buf.getvalue ()` would make a copy of the contents? | Use [shutil.copyfileobj](http://docs.python.org/library/shutil.html#shutil.copyfileobj):
```
with open ('file.xml', 'w') as fd:
buf.seek (0)
shutil.copyfileobj (buf, fd)
``` |
Parsing text files using Python | 3,253,383 | 5 | 2010-07-15T07:34:38Z | 3,253,500 | 7 | 2010-07-15T07:49:13Z | [
"python",
"parsing"
] | I am very new to Python and am looking to use it to parse a text file. The file has between 250-300 lines of the following format:
```
---- Mark Grey (mark.grey@gmail.com) changed status from Busy to Available @ 14/07/2010 16:32:36 ----
---- Silvia Pablo (spablo@gmail.com) became Available @ 14/07/2010 16:32:39 ----
... | ```
import re
pat = re.compile(r"----\s+(.*?) \((.*?)\) (?:changed status from (\w+) to|became) (\w+) @ (.*?) ----\s*")
with open("data.txt") as f:
for line in f:
(name, email, prev, curr, date) = pat.match(line).groups()
print "{0}/{1} {2} {3} {4}".format(name, email, prev or "NaN", curr, date)
`... |
Parsing text files using Python | 3,253,383 | 5 | 2010-07-15T07:34:38Z | 3,253,522 | 15 | 2010-07-15T07:52:49Z | [
"python",
"parsing"
] | I am very new to Python and am looking to use it to parse a text file. The file has between 250-300 lines of the following format:
```
---- Mark Grey (mark.grey@gmail.com) changed status from Busy to Available @ 14/07/2010 16:32:36 ----
---- Silvia Pablo (spablo@gmail.com) became Available @ 14/07/2010 16:32:39 ----
... | To get you started:
```
result = []
regex = re.compile(
r"""^-*\s+
(?P<name>.*?)\s+
\((?P<email>.*?)\)\s+
(?:changed\s+status\s+from\s+(?P<previous>.*?)\s+to|became)\s+
(?P<new>.*?)\s+@\s+
(?P<date>\S+)\s+
(?P<time>\S+)\s+
-*$""", re.VERBOSE)
with open("inputfile") as f:
for line in... |
Parsing text files using Python | 3,253,383 | 5 | 2010-07-15T07:34:38Z | 3,253,537 | 7 | 2010-07-15T07:55:35Z | [
"python",
"parsing"
] | I am very new to Python and am looking to use it to parse a text file. The file has between 250-300 lines of the following format:
```
---- Mark Grey (mark.grey@gmail.com) changed status from Busy to Available @ 14/07/2010 16:32:36 ----
---- Silvia Pablo (spablo@gmail.com) became Available @ 14/07/2010 16:32:39 ----
... | The two RE patterns of interest seem to be...:
```
p1 = r'^---- ([^(]+) \(([^)]+)\) changed status from (\w+) to (\w+) (\S+) (\S+) ----$'
p2 = r'^---- ([^(]+) \(([^)]+)\) became (\w+) (\S+) (\S+) ----$'
```
so I'd do:
```
import csv, re, sys
# assign p1, p2 as above (or enhance them, etc etc)
r1 = re.compile(p1)
r... |
Pass list as argument to Python C module? | 3,253,563 | 6 | 2010-07-15T07:59:12Z | 3,253,609 | 12 | 2010-07-15T08:06:46Z | [
"python",
"c",
"list",
"integration",
"arguments"
] | I found [this](http://superjared.com/entry/anatomy-python-c-module/) nice example of a Python C Module, where a single integer is passed along as the only argument. How can I instead pass a python list as argument? | From <http://code.activestate.com/lists/python-list/31841/>:
```
...
char * tok; /* delimiter tokens for strtok */
int cols; /* number of cols to parse, from the left */
int numLines; /* how many lines we passed for parsing */
char * line; /* pointer to the line as a string */
char * to... |
Python string to attribute | 3,253,966 | 20 | 2010-07-15T08:55:47Z | 3,254,009 | 9 | 2010-07-15T08:59:31Z | [
"python",
"attributes"
] | How can I achieve such job:
```
def get_foo(someobject, foostring):
return someobject.foostring
```
IE:
if I do `get_foo(obj, "name")` it should be calling `obj.name` (see input as string but I call it as an attritube.
Thanks | You should use setattr and getattr:
```
setattr(object,'property',value)
getattr(object,'property',default)
``` |
Python string to attribute | 3,253,966 | 20 | 2010-07-15T08:55:47Z | 3,254,017 | 29 | 2010-07-15T09:00:13Z | [
"python",
"attributes"
] | How can I achieve such job:
```
def get_foo(someobject, foostring):
return someobject.foostring
```
IE:
if I do `get_foo(obj, "name")` it should be calling `obj.name` (see input as string but I call it as an attritube.
Thanks | Use the builtin function `getattr`
```
getattr(...)
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
... |
Python string to attribute | 3,253,966 | 20 | 2010-07-15T08:55:47Z | 3,254,188 | 16 | 2010-07-15T09:23:58Z | [
"python",
"attributes"
] | How can I achieve such job:
```
def get_foo(someobject, foostring):
return someobject.foostring
```
IE:
if I do `get_foo(obj, "name")` it should be calling `obj.name` (see input as string but I call it as an attritube.
Thanks | If `someobject` has an attribute named `foostring` then
```
def get_foo(someobject, foostring):
return getattr(someobject,foostring)
```
or if you want to set an attribute to the supplied object then:
```
def set_foo(someobject, foostring, value):
return setattr(someobject,foostring, value)
```
Try it |
Django Model Mixins: inherit from models.Model or from object? | 3,254,436 | 27 | 2010-07-15T09:57:11Z | 3,254,482 | 14 | 2010-07-15T10:02:53Z | [
"python"
] | This is a question about Python Mixins that might be useful in general. I'm just using Django models as that is the use-case I'm most familiar with.
Should a mixin inherit from the class it is designed to mix-in with or from 'object'?
Examples by code, what is more correct or better, or better depending on what you w... | I would recommend that it inherits from `object`. That way you can ensure that it only provides those methods and attributes you actually define explicitly.
Also, you should always ensure that you put the mixin class *first* when defining your concrete class. Python's resolution rules mean that the superclasses are se... |
Django Model Mixins: inherit from models.Model or from object? | 3,254,436 | 27 | 2010-07-15T09:57:11Z | 25,817,237 | 25 | 2014-09-12T21:37:19Z | [
"python"
] | This is a question about Python Mixins that might be useful in general. I'm just using Django models as that is the use-case I'm most familiar with.
Should a mixin inherit from the class it is designed to mix-in with or from 'object'?
Examples by code, what is more correct or better, or better depending on what you w... | Django does a lot of meta magic when it comes to its model classes, so unfortunately the usual approach to mixins as suggested in Daniel Roseman's answer -- where they inherit from `object` -- does not work well in the Django universe.
The correct way to structure your mixins, using the example provided, would be:
``... |
Why does Twisted think I'm calling request.finish() twice when I am not? | 3,254,965 | 6 | 2010-07-15T11:09:39Z | 3,269,237 | 7 | 2010-07-16T22:19:04Z | [
"python",
"twisted.web"
] | This is an annoying problem I am having with Twisted.web. Basically, I have a class that inherits from `twisted.web.resource.Resource` and adds some default stuff to Mako templates:
```
from twisted.web.resource import Resource
from mako.lookup import TemplateLookup
from project.session import SessionData
from project... | ## Short Answer
---
It has to be:
```
request.redirect("/test")
request.finish()
return twisted.web.server.NOT_DONE_YET
```
## Long Answer
---
I decided to go sifting through some Twisted source code. I first added a traceback to the area that prints the error if `request.finish()` is called twice:
```
def finis... |
Importing python modules in jython | 3,256,135 | 6 | 2010-07-15T13:48:54Z | 3,257,999 | 12 | 2010-07-15T17:00:19Z | [
"python",
"import",
"jython",
"importerror",
"scapy"
] | I'm having some issues importing scapy under jython. I've been doing java forever, but python for only a day or two.
The simple case to reproduce the problem is:
```
$jython
>>> import sys
>>> sys.path
['', '/usr/share/jython/Lib', '/usr/lib/site-python', '__classpath__']
>>> from scapy.all import *
Traceback (inner... | You've done the right thing printing sys.path. Now you should go to your python shell, and do this:
```
$ python
>>> import scapy
>>> print scapy.__file__
```
This will show where scapy is being imported from. The most likely problem is that your jython sys.path doesn't include the directory containing scapy. |
Catching http errors | 3,256,576 | 8 | 2010-07-15T14:33:53Z | 3,256,610 | 18 | 2010-07-15T14:36:12Z | [
"python",
"urllib"
] | how can I catch the 404 and 403 errors for pages in python and urllib(2), for example?
Are there any fast ways without big class-wrappers?
Added info (stack trace):
```
Traceback (most recent call last):
File "test.py", line 3, in <module>
page = urllib2.urlopen("http://localhost:4444")
File "/usr/lib/python... | ```
import urllib2
try:
page = urllib2.urlopen("some url")
except urllib2.HTTPError, err:
if err.code == 404:
print "Page not found!"
elif err.code == 403:
print "Access denied!"
else:
print "Something happened! Error code", err.code
except urllib2.URLError, err:
print "Some other ... |
Call back in Python | 3,257,093 | 4 | 2010-07-15T15:26:25Z | 3,257,140 | 7 | 2010-07-15T15:32:09Z | [
"python"
] | Could some explain how call back methods work, and if possible, give me an example in Python? So as far as I understand them, they are methods which are provided by the user of an API, to the API, so that the user doesn't have to wait till that particular API function completes. So does the user program continue execut... | Callbacks are just user-supplied hooks. They allow you to specify what function to call in case of certain events. `re.sub` has a callback, but it sounds like you are dealing with a GUI, so I'll give a GUI example:
Here is a very simple example of a callback:
```
from Tkinter import *
master = Tk()
def my_callback(... |
Difference between binary and text I/O in python on Windows | 3,257,869 | 11 | 2010-07-15T16:45:48Z | 3,257,886 | 14 | 2010-07-15T16:48:20Z | [
"python",
"windows",
"file",
"file-io"
] | I know that I should open a binary file using `"rb"` instead of `"r"` because Windows behaves differently for binary and non-binary files.
But I don't understand what exactly happens if I open a file the wrong way and why this distinction is even necessary. Other operating systems seem to do fine by treating both kind... | This mode is about conversion of line endings.
When reading in text mode, the platform's native line endings (`\r\n` on Windows) are converted to Python's Unix-style `\n` line endings. When writing in text mode, the reverse happens.
In binary mode, no such conversion is done.
Other platforms usually do fine without ... |
Difference between binary and text I/O in python on Windows | 3,257,869 | 11 | 2010-07-15T16:45:48Z | 3,262,082 | 7 | 2010-07-16T05:06:30Z | [
"python",
"windows",
"file",
"file-io"
] | I know that I should open a binary file using `"rb"` instead of `"r"` because Windows behaves differently for binary and non-binary files.
But I don't understand what exactly happens if I open a file the wrong way and why this distinction is even necessary. Other operating systems seem to do fine by treating both kind... | Well this is for historical (or as i like to say it, *hysterical*) reasons. The file open modes are inherited from C stdio library and hence we follow it.
For Windows, there is no difference between text and binary files, just like in any of the Unix clones. No, i mean it! - there are (were) file systems/OSes in which... |
What is the difference between " is None " and " ==None " | 3,257,919 | 107 | 2010-07-15T16:52:10Z | 3,257,951 | 29 | 2010-07-15T16:55:04Z | [
"python",
"jython"
] | I recently came across this syntax, I am unaware of the difference.
I would appreciate it if someone could tell me the difference. | In this case, they are the same. `None` is a singleton object (there only ever exists one `None`).
`is` checks to see if the object is the same object, while == just checks if they are equivalent.
For example:
```
p = [1]
q = [1]
p is q # False because they are not the same actual object
p == q # True because they a... |
What is the difference between " is None " and " ==None " | 3,257,919 | 107 | 2010-07-15T16:52:10Z | 3,257,957 | 111 | 2010-07-15T16:55:39Z | [
"python",
"jython"
] | I recently came across this syntax, I am unaware of the difference.
I would appreciate it if someone could tell me the difference. | The answer is explained [here](http://jaredgrubb.blogspot.com/2009/04/python-is-none-vs-none.html).
To quote:
> A class is free to implement
> comparison any way it chooses, and it
> can choose to make comparison against
> None mean something (which actually
> makes sense; if someone told you to
> implement the None ... |
What is the difference between " is None " and " ==None " | 3,257,919 | 107 | 2010-07-15T16:52:10Z | 3,258,748 | 57 | 2010-07-15T18:38:17Z | [
"python",
"jython"
] | I recently came across this syntax, I am unaware of the difference.
I would appreciate it if someone could tell me the difference. | ```
class Foo:
def __eq__(self,other):
return True
foo=Foo()
print(foo==None)
# True
print(foo is None)
# False
``` |
Overcoming os.system() limitation in Python 2.3 | 3,258,229 | 3 | 2010-07-15T17:30:49Z | 3,258,304 | 8 | 2010-07-15T17:41:44Z | [
"python",
"subprocess",
"alias",
"csh",
"os.system"
] | I am having a problem converting one of my company's scripts from csh to Python. The csh script calls an aliased command, but when I call that same aliased command via os.system(), it does not work.
So, if `foo` is the aliased command:
CSH Script (this works, executes foo):
```
foo <argument>
```
Python (this does ... | What made you think os.system would use csh? It uses standard C function system, that on Unix system will call just basic /bin/sh. This will not be csh, but most probably bash, or some simpler version of it.
BTW: note that what you do with shell environment in os.system will not affect subsequent calls to os.system, b... |
Converting from hex to binary without losing leading 0's python | 3,258,330 | 8 | 2010-07-15T17:46:21Z | 3,258,407 | 14 | 2010-07-15T17:54:18Z | [
"python",
"binary",
"hex"
] | I have a hex value in a string like
```
h = '00112233aabbccddee'
```
I know I can convert this to binary with:
```
h = bin(int(h, 16))[2:]
```
However, this loses the leading 0's. Is there anyway to do this conversion without losing the 0's? Or is the best way to do this just to count the number of leading 0's befo... | I don't think there is a way to keep those leading zeros by default.
Each hex digit translates to 4 binary digits, so the length of the new string should be exactly 4 times the size of the original.
```
h_size = len(h) * 4
```
Then, you can use `.zfill` to fill in zeros to the size you want:
```
h = ( bin(int(h, 16... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.