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 |
|---|---|---|---|---|---|---|---|---|---|
Having trouble building python deb package , complain about modified binary | 9,677,971 | 7 | 2012-03-13T03:25:33Z | 9,679,610 | 9 | 2012-03-13T07:00:37Z | [
"python",
"package",
"deb",
"dpkg",
"debhelper"
] | I have built my packages before using debhelper, but I'm running into a very frustrating problem.
This is my file tree:
```
usr/
`-- share
|-- applications
| `-- create-launcher.desktop
`-- create-launcher
|-- bin
| |-- callbacks.py
| |-- callbacks.pyc
| |-- create_... | After a lot of reading and trial and error, I figured out what was wrong. I had run a
```
dpkg-source -b create-launcher_0.1.2+alpha
```
And for some reason, it failed to delete the unpacked create-launcher\_0.1.2+alpha.orig.tar.gz file directory that looks something like create-launcher-0.1.2+alpha.orig.6h0gQo. I lo... |
Can't install psycopg2 with pip in virtualenv on Mac OS X 10.7 | 9,678,408 | 17 | 2012-03-13T04:32:09Z | 28,219,851 | 19 | 2015-01-29T16:35:24Z | [
"python",
"django",
"heroku",
"pip",
"psycopg2"
] | I am following Heroku's tutorial to deploy a Django app: <http://devcenter.heroku.com/articles/django#prerequisites>.
Everything is working fine until I get to this part:
```
$ pip install Django psycopg2
```
I can install Django by itself, but the probelm is with psycopg2.
I keep getting this error:
```
ld: libra... | First, download [`Postgres.app`](http://postgresapp.com/).
Then, before running `pip install psycopg2`, put the binary in your path:
```
export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/9.3/bin
```
**NOTICE**:
`9.3` stands for version and will differ over time. |
Accessing form fields as properties in a django view | 9,678,642 | 4 | 2012-03-13T05:05:16Z | 9,695,604 | 7 | 2012-03-14T03:42:31Z | [
"python",
"django",
"forms",
"validation"
] | According to the Django tutorial, you should access form fields using cleaned\_data dictionary. I'm wondering why I can't access the properties of the form directly? My form validates just fine, but when I try to access it, Django complains that the object does not have the attribute. I added some code below that I hop... | The way you define fields using `django.forms` is just a convenient, declarative syntax; it's not really representative of what the final Form class, or an instance of it, looks like in terms of attributes.
Forms have a [metaclass](http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python) (without getti... |
How can I get last modified datetime of S3 objects with boto? | 9,679,344 | 12 | 2012-03-13T06:31:32Z | 9,688,496 | 18 | 2012-03-13T16:56:09Z | [
"python",
"amazon-s3",
"amazon-web-services",
"boto"
] | I'm writing a python scripts to upload files to s3 using boto. I want to only upload changed files which I can check by it's last modified datetime. But I can't find the api to get the last modify in boto API. | Here's a snippet of Python/boto code that will print the last\_modified attribute of all keys in a bucket:
```
>>> import boto
>>> s3 = boto.connect_s3()
>>> bucket = s3.lookup('mybucket')
>>> for key in bucket:
print key.name, key.size, key.last_modified
index.html 13738 2012-03-13T03:54:07.000Z
markdown.css 5... |
How do I use Flask routes with Apache and mod_wsgi? | 9,680,073 | 14 | 2012-03-13T07:42:19Z | 9,686,722 | 16 | 2012-03-13T15:08:21Z | [
"python",
"apache",
"mod-wsgi",
"flask"
] | I've got my Apache server setup and it is handling Flask responses via mod\_wsgi. I've registered the WSGI script via the alias:
[httpd.conf]
```
WSGIScriptAlias /service "/mnt/www/wsgi-scripts/service.wsgi"
```
I've added the corresponding WSGI file at the above path:
[/mnt/www/wsgi-scripts/service.wsgi]
```
impo... | In your wsgi file you are doing `from service import application`, which is importing only your `application` method.
Change that to `from service import app as application` and everything will work as expected.
After your comment, I thought I'd expand the answer a bit:
Your wsgi file is python code - you can have a... |
How can I use xdotool from within a python module/script? | 9,681,959 | 2 | 2012-03-13T10:07:16Z | 9,682,073 | 7 | 2012-03-13T10:15:33Z | [
"python",
"ubuntu"
] | For example, if i wanted to use something like:
xdotool mousemove 945 132
xdotool click 1
In order to move the mouse to a certain location and click. In ubuntu I can just type these commands straight into the terminal to get the desired effect but I would like to put them inside of a Python script. Thanks in advance... | ```
import subprocess
subprocess.call(["xdotool", "mousemove", "945", "132"])
```
etc. See the [`subprocess`](http://docs.python.org/library/subprocess.html) docs. |
composite key in web2py | 9,683,604 | 2 | 2012-03-13T12:00:47Z | 9,685,846 | 9 | 2012-03-13T14:18:21Z | [
"python",
"web2py",
"composite-key"
] | I have a table defined in web2py
```
db.define_table(
'pairing',
Field('user',writable=True,readable=True),
Field('uid', writable=True , readable=True)
)
```
This table needs to have user and uid combination being unique. I have looked through the web2py documentation , but there isn't direct way to define composite ... | It depends on what you are trying to do. By default, web2py automatically creates an auto-incrementing `id` field to serve as the primary key for each table, and that is the recommended approach whenever possible. If you are dealing with a legacy database with composite primary keys and cannot change the schema, you ca... |
I cannot install numpy because it can't find python 2.7, althought I have installed python | 9,684,254 | 29 | 2012-03-13T12:51:30Z | 9,684,873 | 21 | 2012-03-13T13:26:33Z | [
"python",
"numpy"
] | I cannot install numpy because it can't find python 2.7, althought I have installed python.
I have message: "Python version 2.7 required, which can't find in registry"
Do have a solve of my problem? | You should install Python 32bit, or use the numpy package for python 64bit from [this unofficial site](http://www.lfd.uci.edu/~gohlke/pythonlibs/) |
I cannot install numpy because it can't find python 2.7, althought I have installed python | 9,684,254 | 29 | 2012-03-13T12:51:30Z | 11,507,968 | 52 | 2012-07-16T15:55:17Z | [
"python",
"numpy"
] | I cannot install numpy because it can't find python 2.7, althought I have installed python.
I have message: "Python version 2.7 required, which can't find in registry"
Do have a solve of my problem? | This is not uncommon with installers (e.g. Numpy) that depend on or look for a previously installed 64 bit core application (e.g. Python x64). The problem and solution are easy to explain.
**PROBLEM**
IMHO this is an error on the part of the developer of the already-installed 64 bit applicaiton by placing the registry... |
I cannot install numpy because it can't find python 2.7, althought I have installed python | 9,684,254 | 29 | 2012-03-13T12:51:30Z | 13,573,063 | 7 | 2012-11-26T20:58:55Z | [
"python",
"numpy"
] | I cannot install numpy because it can't find python 2.7, althought I have installed python.
I have message: "Python version 2.7 required, which can't find in registry"
Do have a solve of my problem? | This problem also affects 32-bit numpy on 32-bit Python.
The cause is that the numpy installer assumes you opted for "*install for all users*" when you installed Python, i.e. that the Python installer used the machine-wide **HKEY\_LOCAL\_MACHINE** part of the registry.
If you instead chose "*install for me only*", tho... |
how to delete a key from a dictionary with the highest value? | 9,685,423 | 5 | 2012-03-13T13:55:42Z | 9,685,534 | 9 | 2012-03-13T14:01:27Z | [
"python"
] | I have a simple question (or so I thought).
I have a dictionary, lets say it looks like this:
```
dict = {'A':100, 'a':10, 'T':50, 't':5}
```
I simply want to delete the key with the highest value. I tried this:
```
del max(dict.values())
```
and this is the error message: 'Syntax Error: can´t delete function cal... | `max(d.values())` will give you the maximum value (100), but to delete an entry from a dictionary you need the corresponding key (`'A'`).
You can do this:
```
d = {'A':100, 'a':10, 'T':50, 't':5}
key_to_delete = max(d, key=lambda k: d[k])
del d[key_to_delete]
```
By the way, you shouldn't name your dictionary `dict`... |
how to delete a key from a dictionary with the highest value? | 9,685,423 | 5 | 2012-03-13T13:55:42Z | 9,685,551 | 8 | 2012-03-13T14:02:10Z | [
"python"
] | I have a simple question (or so I thought).
I have a dictionary, lets say it looks like this:
```
dict = {'A':100, 'a':10, 'T':50, 't':5}
```
I simply want to delete the key with the highest value. I tried this:
```
del max(dict.values())
```
and this is the error message: 'Syntax Error: can´t delete function cal... | You need to get a hold of the key to the max value.
Try this instead:
```
del d[max(d, key=d.get)]
```
Also, you should avoid calling your variable `dict` because it shadows the built-in name. |
Math operations from string | 9,685,946 | 16 | 2012-03-13T14:23:38Z | 9,686,074 | 23 | 2012-03-13T14:30:20Z | [
"python",
"string",
"math"
] | Let's say I have a standard Python string (such as one obtained from `raw_input()`), maybe "2 + 2" for simplicity's sake. I'd like to convert this string to standard math operations in Python, such that "2 + 2" would return 4. Is there an easy way to do this, or would I have to split on the spaces and parse each number... | Use the eval function.
```
print eval('2 + 4')
```
Output:
```
6
```
You can even use variables or regular python code.
```
a = 5
print eval('a + 4')
```
Output:
```
9
```
You also can get return values:
```
d = eval('4 + 5')
print d
```
Output:
```
9
```
Or call functions:
```
def add(a, b):
return a ... |
How to store a dictionary in a Django database model's field | 9,686,409 | 10 | 2012-03-13T14:49:01Z | 16,437,627 | 12 | 2013-05-08T09:54:20Z | [
"python",
"django",
"dictionary",
"model",
"save"
] | I need to save a dictionary in a model's field. How do I do that?
For example I have this code:
```
def create_random_bill(self):
name_chars = re.compile("[a-zA-Z0-9 -_]")
bill_name = "".join(random.choice(name_chars for x in range(10)))
rand_products = random.randint(1,100)
for x in rand_products:
... | I just discovered the [django-jsonfield](https://github.com/bradjasper/django-jsonfield) package, which
> is a reusable Django field that allows you to store validated JSON in your model.
Looks like a viable option to achieve what you want. |
How do I create a histogram from a hashmap in python? | 9,689,085 | 5 | 2012-03-13T17:34:16Z | 9,689,251 | 15 | 2012-03-13T17:45:06Z | [
"python",
"dictionary",
"matplotlib",
"hashmap",
"histogram"
] | I have data in a hashmap, and I want to create a histogram over this data using the keys as bins and the values as data.
My data:
```
N = {1: 12, 2: 15, 3: 8, 4: 4, 5: 1}
```
What I want plotted:
```
|
15| X
| X
| X
| X X
| X X
10| X X
| X X
| X X X
| X X X
| X X X
5| X X X
... | Just plot a bar graph. That's all `hist` does.
E.g.:
```
import matplotlib.pyplot as plt
N = {1: 12, 2: 15, 3: 8, 4: 4, 5: 1}
plt.bar(N.keys(), N.values(), align='center')
plt.show()
```
 |
Shape recognition with numpy/scipy (perhaps watershed) | 9,689,173 | 10 | 2012-03-13T17:39:45Z | 9,692,312 | 12 | 2012-03-13T21:14:55Z | [
"python",
"numpy",
"scipy",
"watershed"
] | My goal is to trace drawings that have a lot of separate shapes in them and to split these shapes into individual images. It is black on white. I'm quite new to numpy,opencv&co - but here is my current thought:
* scan for black pixels
* black pixel found -> watershed
* find watershed boundary (as polygon path)
* conti... | @Hooked has already answered most of your question, but I was in the middle of writing this up when he answered, so I'll post it in the hopes that it's still useful...
You're trying to jump through a few too many hoops. You don't need `watershed_ift`.
You use `scipy.ndimage.label` to differentiate separate objects in... |
Python - 'import' or pass modules as paramaters? | 9,689,355 | 13 | 2012-03-13T17:51:33Z | 9,689,381 | 16 | 2012-03-13T17:53:27Z | [
"python"
] | I was wondering if passing module objects to a class or object which requires it rather than using `import` might not be a bad idea, as it avoids hard dependencies on those modules.
I was wondering if someone more aware of the Python Zen than I might be able to explain why this is a terrible/not terrible idea? | What you're talking about is called [dependency injection](http://en.wikipedia.org/wiki/Dependency_injection) and is considered a good practice for making your code testable. I don't think there's anything about Python that would make it unPythonic or a bad practice.
There are other ways you could do it in Python, for... |
Pick N items at random from sequence of unknown length | 9,690,009 | 9 | 2012-03-13T18:36:29Z | 9,690,069 | 20 | 2012-03-13T18:40:30Z | [
"python",
"algorithm"
] | I am trying to write an algorithm that would pick N distinct items from an sequence at random, without knowing the size of the sequence in advance, and where it is expensive to iterate over the sequence more than once. For example, the elements of the sequence might be the lines of a huge file.
I have found a solution... | Use [reservoir sampling](http://en.wikipedia.org/wiki/Reservoir_sampling). It's a very simple algorithm that works for any `N`.
[Here](http://data-analytics-tools.blogspot.com/2009/09/reservoir-sampling-algorithm-in-perl.html) is one Python implementation, and [here](http://stackoverflow.com/questions/2612648/reservoi... |
Pick N items at random from sequence of unknown length | 9,690,009 | 9 | 2012-03-13T18:36:29Z | 24,366,302 | 21 | 2014-06-23T12:45:13Z | [
"python",
"algorithm"
] | I am trying to write an algorithm that would pick N distinct items from an sequence at random, without knowing the size of the sequence in advance, and where it is expensive to iterate over the sequence more than once. For example, the elements of the sequence might be the lines of a huge file.
I have found a solution... | If your sequence is short enough that reading it into memory and randomly sorting it is acceptable, then a straightforward approach would be to just use [`random.shuffle`](https://docs.python.org/library/random.html#random.shuffle):
```
import random
arr=[1,2,3,4]
# In-place shuffle
random.shuffle(arr)
# Take the fi... |
Reading/writing to google docs/spreadsheets with Python | 9,690,138 | 47 | 2012-03-13T18:46:51Z | 10,056,273 | 48 | 2012-04-07T16:35:49Z | [
"python",
"google-api",
"google-spreadsheet",
"google-docs-api",
"google-sheets-api"
] | I am wondering if you can point me to an example of reading/writing to/from a google doc/spreadsheet using python.
I did look at google docs API here <https://developers.google.com/google-apps/spreadsheets/> but not sure if I hit the right link. Also an example will be of great help.
What I am trying to do is query s... | Have a look at <https://github.com/burnash/gspread>. I found it to be very easy to use and since you can retrieve a whole column by first\_col = worksheet.col\_values(1) and a whole row by second\_row = worksheet.row\_values(2) you can more or less build some basic select ... where ... = ... easily. |
Reading/writing to google docs/spreadsheets with Python | 9,690,138 | 47 | 2012-03-13T18:46:51Z | 15,162,837 | 28 | 2013-03-01T16:55:14Z | [
"python",
"google-api",
"google-spreadsheet",
"google-docs-api",
"google-sheets-api"
] | I am wondering if you can point me to an example of reading/writing to/from a google doc/spreadsheet using python.
I did look at google docs API here <https://developers.google.com/google-apps/spreadsheets/> but not sure if I hit the right link. Also an example will be of great help.
What I am trying to do is query s... | I know this thread is old now, but here is some decent documentation on Google Docs API. It was ridiculously hard to find, but useful, so maybe it will help you some. <http://pythonhosted.org/gdata/docs/api.html>.
I used gspread recently for a project to graph employee time data. I don't know how much it might help yo... |
Reading/writing to google docs/spreadsheets with Python | 9,690,138 | 47 | 2012-03-13T18:46:51Z | 37,868,852 | 35 | 2016-06-16T20:32:59Z | [
"python",
"google-api",
"google-spreadsheet",
"google-docs-api",
"google-sheets-api"
] | I am wondering if you can point me to an example of reading/writing to/from a google doc/spreadsheet using python.
I did look at google docs API here <https://developers.google.com/google-apps/spreadsheets/> but not sure if I hit the right link. Also an example will be of great help.
What I am trying to do is query s... | **(Jun-Aug 2016)** Most answers here are now out-of-date as: 1) [GData APIs](http://developers.google.com/gdata/docs/directory) are the previous generation of Google APIs, and that's why it was hard for @[Josh Brown](http://stackoverflow.com/users/1445649/josh-brown) to find that old GData Docs API documentation. While... |
Flask-SQLAlchemy import/context issue | 9,692,962 | 56 | 2012-03-13T22:07:01Z | 9,695,045 | 114 | 2012-03-14T02:15:58Z | [
"python",
"flask",
"flask-sqlalchemy"
] | I want to structure my Flask app something like:
```
./site.py
./apps/members/__init__.py
./apps/members/models.py
```
`apps.members` is a Flask Blueprint.
Now, in order to create the model classes I need to have a hold of the app, something like:
```
# apps.members.models
from flask import current_app
from flaskex... | The `flask_sqlalchemy` module does not have to be initialized with the app right away - you can do this instead:
```
# apps.members.models
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Member(db.Model):
# fields here
pass
```
And then in your application setup you can call `init_app`:
```... |
Flask-SQLAlchemy import/context issue | 9,692,962 | 56 | 2012-03-13T22:07:01Z | 19,849,375 | 11 | 2013-11-08T00:15:51Z | [
"python",
"flask",
"flask-sqlalchemy"
] | I want to structure my Flask app something like:
```
./site.py
./apps/members/__init__.py
./apps/members/models.py
```
`apps.members` is a Flask Blueprint.
Now, in order to create the model classes I need to have a hold of the app, something like:
```
# apps.members.models
from flask import current_app
from flaskex... | an original **app.py**: <http://pythonhosted.org/Flask-SQLAlchemy/quickstart.html#quickstart>
```
...
app = flask.Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:////tmp/test.db'
db = flask.ext.sqlalchemy.SQLAlchemy(app)
class Person(db.Model):
id = db.Column(db.Integer... |
Convert rgb color to english color name, like 'green' | 9,694,165 | 27 | 2012-03-14T00:14:19Z | 9,694,246 | 37 | 2012-03-14T00:24:48Z | [
"python",
"css",
"image",
"colors",
"tuples"
] | I want to convert a color tuple to a color name, like 'yellow' or 'blue'
```
>>> im = Image.open("test.jpg")
>>> n, color = max(im.getcolors(im.size[0]*im.size[1]))
>>> print color
(119, 172, 152)
```
Is there a simple way in python to do this? | It looks like [webcolors](http://pypi.python.org/pypi/webcolors/1.3) will allow you to do this:
> rgb\_to\_name(rgb\_triplet, spec='css3')
>
> Convert a 3-tuple of integers, suitable for use in an rgb() color triplet, to its corresponding normalized color name, if any such name exists; valid values are html4, css2, cs... |
Convert rgb color to english color name, like 'green' | 9,694,165 | 27 | 2012-03-14T00:14:19Z | 9,694,258 | 9 | 2012-03-14T00:26:02Z | [
"python",
"css",
"image",
"colors",
"tuples"
] | I want to convert a color tuple to a color name, like 'yellow' or 'blue'
```
>>> im = Image.open("test.jpg")
>>> n, color = max(im.getcolors(im.size[0]*im.size[1]))
>>> print color
(119, 172, 152)
```
Is there a simple way in python to do this? | There is a program called pynche which can change RGB to colour name in English for Python.
You can try to use the method `ColorDB.nearest()` in `ColorDB.py` which can do what you want.
You can find more information about this method here : [ColorDB Pynche](http://fossies.org/dox/Python-3.2.2/namespacepynche_1_1Color... |
Remove element from tuple in a list | 9,694,739 | 9 | 2012-03-14T01:31:25Z | 9,694,758 | 22 | 2012-03-14T01:34:07Z | [
"python",
"list",
"tuples"
] | I've knocking my head against a wall with this:
Basically what I want is to remove " " items from this list of tuples:
```
[('650', '724', '6354', '', '', ''), ('', '', '', '650', '723', '4539')]
```
and obtain the following new list:
```
[('650', '724', '6354'), ('650', '723', '4539')]
```
any ideas? | Tuples in Python are *immutable*. This means that once you have created a tuple, you can't change the elements contained within it. However, you can create a *new* tuple that doesn't contain the items you don't want. For example:
```
>>> a = [('650', '724', '6354', '', '', ''), ('', '', '', '650', '723', '4539')]
>>> ... |
Using TastyPie to update a ForeignKey field to null | 9,695,798 | 6 | 2012-03-14T04:09:49Z | 9,874,145 | 9 | 2012-03-26T14:34:47Z | [
"python",
"django",
"rest",
"tastypie"
] | Is it possible to use TastyPie to update a `ForeignKey` field to `None`?
Related question: [tastypie won't remove foreignkey reference during PUT](http://stackoverflow.com/questions/9307619/tastypie-wont-remove-foreignkey-reference-during-put)
**What I have:**
```
class SomeObject(models.Model):
some_field = mod... | Here is a generic solution. Create a base resource and extend all other resources from this one. It's a hack, but it works.
```
class MyResource(ModelResource):
def obj_update(self, bundle, request=None, **kwargs):
for field_name in self.fields:
field = self.fields[field_name]
if t... |
Python: How to make Reportlab move to next page in PDF output | 9,696,211 | 5 | 2012-03-14T05:02:51Z | 9,696,838 | 7 | 2012-03-14T06:13:20Z | [
"python",
"pdf",
"png",
"reportlab"
] | I'm using the open source version Reportlab with Python on Windows. My code loops through multiple PNG files & combines them to form a single PDF. Each PNG is stretched to the full LETTER spec (8.5x11).
Problem is, all the images saved to output.pdf are sandwiched on top of each other and only the last image added is ... | [Follow up of the post's comment]
Use `canv.showPage()` after you use `canv.drawImage(...)` each time.
( <http://www.reportlab.com/apis/reportlab/dev/pdfgen.html#reportlab.pdfgen.canvas.Canvas.showPage> )
Follow the source document(for that matter any tool you are using, you should dig into it's respective website do... |
Scrapy and response status code: how to check against it? | 9,698,372 | 12 | 2012-03-14T08:40:10Z | 9,698,718 | 15 | 2012-03-14T09:06:10Z | [
"python",
"scrapy",
"http-status-codes"
] | I'm using scrapy to crawl my sitemap, to check for 404, 302 and 200 pages. But i can't seem to be able to get the response code. This is my code so far:
```
from scrapy.contrib.spiders import SitemapSpider
class TothegoSitemapHomesSpider(SitemapSpider):
name ='tothego_homes_spider'
## robe che ci servono pe... | <http://readthedocs.org/docs/scrapy/en/latest/topics/spider-middleware.html#module-scrapy.contrib.spidermiddleware.httperror>
Assuming default spider middleware is enabled, response codes outside of the 200-300 range are filtered out by HttpErrorMiddleware. You can tell the middleware you want to handle 404s by settin... |
Driving a Windows GUI program from a script | 9,698,512 | 17 | 2012-03-14T08:51:43Z | 9,699,535 | 8 | 2012-03-14T09:53:42Z | [
"python",
"winapi",
"user-interface",
"automation",
"gui-testing"
] | I have to use a Windows simulation package to perform a repetitive task with slightly different options each time.
Since I hate repetitive clicking, on grounds of both laziness and the amount of errors that a human introduces, I would like to drive this program automatically. The program in question doesn't support sc... | > Sikuli is a visual technology to automate and test graphical user
> interfaces (GUI) using images (screenshots). Sikuli includes Sikuli
> Script, a visual scripting API for Jython, and Sikuli IDE, an
> integrated development environment for writing visual scripts with
> screenshots easily. Sikuli Script automates any... |
Driving a Windows GUI program from a script | 9,698,512 | 17 | 2012-03-14T08:51:43Z | 15,362,282 | 7 | 2013-03-12T13:13:25Z | [
"python",
"winapi",
"user-interface",
"automation",
"gui-testing"
] | I have to use a Windows simulation package to perform a repetitive task with slightly different options each time.
Since I hate repetitive clicking, on grounds of both laziness and the amount of errors that a human introduces, I would like to drive this program automatically. The program in question doesn't support sc... | Take a look at [Automa](http://www.getautoma.com/) - it is written in Python. It can be used either as a standalone tool or as a Python library in your own scripts:
```
from automa.api import *
```
It allows automation of any Windows application through commands like click, press, write, etc.
Some examples of the au... |
How to use pip on windows behind an authenticating proxy | 9,698,557 | 32 | 2012-03-14T08:54:46Z | 11,869,484 | 40 | 2012-08-08T16:58:14Z | [
"python",
"authentication",
"proxy",
"pip"
] | My computer is running windows behind a proxy on a windows server (using active directory), and I can't figure out how to get through it with `pip` (in python3). I have tried using `--proxy`, but it still just timeouts. I have also tried setting a long timeout (60s), but that made no difference. My proxy settings are c... | I have tried 2 options which both work on my company's NTLM authenticated proxy.
Option 1 is to use `--proxy http://user:pass@proxyAddress:proxyPort`
If you are still having trouble I would suggest installing a proxy authentication service (I use [CNTLM](http://cntlm.sourceforge.net/)) and pointing pip at it ie someth... |
super() raises "TypeError: must be type, not classobj" for new-style class | 9,698,614 | 263 | 2012-03-14T08:59:02Z | 9,698,706 | 15 | 2012-03-14T09:04:56Z | [
"python",
"superclass",
"super",
"typeerror"
] | The following use of `super()` raises a TypeError: why?
```
>>> from HTMLParser import HTMLParser
>>> class TextParser(HTMLParser):
... def __init__(self):
... super(TextParser, self).__init__()
... self.all_data = []
...
>>> TextParser()
(...)
TypeError: must be type, not classobj
```
T... | If you look at the inheritance tree (in version 2.6), `HTMLParser` inherits from `SGMLParser` which inherits from `ParserBase` which *doesn't* inherits from `object`. I.e. HTMLParser is an old-style class.
About your checking with `isinstance`, I did a quick test in ipython:
```
In [1]: class A:
...: pass
.... |
super() raises "TypeError: must be type, not classobj" for new-style class | 9,698,614 | 263 | 2012-03-14T08:59:02Z | 9,698,750 | 153 | 2012-03-14T09:07:52Z | [
"python",
"superclass",
"super",
"typeerror"
] | The following use of `super()` raises a TypeError: why?
```
>>> from HTMLParser import HTMLParser
>>> class TextParser(HTMLParser):
... def __init__(self):
... super(TextParser, self).__init__()
... self.all_data = []
...
>>> TextParser()
(...)
TypeError: must be type, not classobj
```
T... | super() can be used only in the new-style classes, which means the root class needs to inherit from the 'object' class.
For example, the top class need to be like this:
```
class SomeClass(object):
def __init__(self):
....
```
not
```
class SomeClass():
def __init__(self):
....
```
So, the ... |
super() raises "TypeError: must be type, not classobj" for new-style class | 9,698,614 | 263 | 2012-03-14T08:59:02Z | 9,719,731 | 201 | 2012-03-15T12:31:37Z | [
"python",
"superclass",
"super",
"typeerror"
] | The following use of `super()` raises a TypeError: why?
```
>>> from HTMLParser import HTMLParser
>>> class TextParser(HTMLParser):
... def __init__(self):
... super(TextParser, self).__init__()
... self.all_data = []
...
>>> TextParser()
(...)
TypeError: must be type, not classobj
```
T... | Alright, it's the usual "`super()` cannot be used with an old-style class".
However, the important point is that **the correct test** for "is this a new-style **instance** (i.e. object)?" is
```
>>> class OldStyle: pass
>>> instance = OldStyle()
>>> issubclass(instance.__class__, object)
False
```
and not (as in the... |
super() raises "TypeError: must be type, not classobj" for new-style class | 9,698,614 | 263 | 2012-03-14T08:59:02Z | 11,810,015 | 18 | 2012-08-04T16:01:49Z | [
"python",
"superclass",
"super",
"typeerror"
] | The following use of `super()` raises a TypeError: why?
```
>>> from HTMLParser import HTMLParser
>>> class TextParser(HTMLParser):
... def __init__(self):
... super(TextParser, self).__init__()
... self.all_data = []
...
>>> TextParser()
(...)
TypeError: must be type, not classobj
```
T... | You can also use `class TextParser(HTMLParser, object):`. This makes `TextParser` a *new-style* class, and `super()` can be used. |
super() raises "TypeError: must be type, not classobj" for new-style class | 9,698,614 | 263 | 2012-03-14T08:59:02Z | 33,191,827 | 9 | 2015-10-17T21:34:52Z | [
"python",
"superclass",
"super",
"typeerror"
] | The following use of `super()` raises a TypeError: why?
```
>>> from HTMLParser import HTMLParser
>>> class TextParser(HTMLParser):
... def __init__(self):
... super(TextParser, self).__init__()
... self.all_data = []
...
>>> TextParser()
(...)
TypeError: must be type, not classobj
```
T... | The problem is that `super` needs an `object` as a ancestor:
```
>>> class oldstyle:
... def __init__(self): self.os = True
>>> class myclass(oldstyle):
... def __init__(self): super(myclass, self).__init__()
>>> myclass()
TypeError: must be type, not classobj
```
On closer examination one finds:
```
>>> t... |
How do I stop all spiders and the engine immediately after a condition in a pipeline is met? | 9,699,049 | 8 | 2012-03-14T09:25:01Z | 9,699,317 | 9 | 2012-03-14T09:40:19Z | [
"python",
"scrapy",
"web-crawler"
] | We have a system written with scrapy to crawl a few websites. There are **several spiders**, and a **few cascaded pipelines for all** items passed by all crawlers.
One of the pipeline components queries the **google servers for geocoding addresses**.
Google imposes a limit of **2500 requests per day per IP address**, a... | You can [raise a CloseSpider exception](http://doc.scrapy.org/en/0.14/topics/exceptions.html#closespider) to close down a spider.
However, I don't think this will work from a pipeline.
**EDIT**: avaleske notes in the comments to this answer that he was able to raise a CloseSpider exception from a pipeline. Most wise w... |
Instance is an "object", but class is not a subclass of "object": how is this possible? | 9,699,591 | 11 | 2012-03-14T09:56:47Z | 9,699,961 | 12 | 2012-03-14T10:18:45Z | [
"python",
"object",
"instance",
"subclass"
] | How is it possible to have an instance of a class which is an `object`, without the class being a subclass of `object`? here is an example:
```
>>> class OldStyle(): pass
>>> issubclass(OldStyle, object)
False
>>> old_style = OldStyle()
>>> isinstance(old_style, object)
True
``` | In Python 2, *type* and *class* are not the same thing, specifically, for old-style classes, `type(obj)` [is not the same object](http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python) as `obj.__class__`. So it is possible because instances of old-style classes are actually of a d... |
Why python reduce() behaves differently with the `None` element? | 9,701,227 | 2 | 2012-03-14T11:38:55Z | 9,701,279 | 8 | 2012-03-14T11:42:13Z | [
"python",
"functional-programming"
] | I don't understand the answers for a [similar question.](http://stackoverflow.com/questions/9359677/why-python-reduce-skip-over-the-none-element)
It is clear that this should return `True`
```
l = [1,1,1]
reduce(lambda x,y: x== y, l)
```
However, how do you explain this retuns `False` (when `None==None` is `True`)
... | Because
```
1 == True # 1 == (1 == 1)
```
is `True`, but
```
None == True # None == (None == None)
```
is `False` (and `None == False` is `False` as well, so once you got `False`, it stays `False`).
That's how `reduce` works: It passes each element and the **result** of the previous evaluation to the callback. And... |
Filter part of image using PIL, python | 9,701,515 | 4 | 2012-03-14T11:58:24Z | 9,708,858 | 10 | 2012-03-14T19:30:55Z | [
"python",
"filtering",
"python-imaging-library"
] | I can't understand how to apply blur filter to part of an image using PIL.
I've tried to search with google and read PIL documentation but didn't find anything useful.
Thanks for help. | You can crop out a section of the image, blur it, and stick it back in. Like this:
```
box = (30, 30, 110, 110)
ic = image.crop(box)
for i in range(10): # with the BLUR filter, you can blur a few times to get the effect you're seeking
ic = ic.filter(ImageFilter.BLUR)
image.paste(ic, box)
```
![enter image descri... |
Extend argparse to write set names in the help text for optional argument choices and define those sets once at the end | 9,702,414 | 12 | 2012-03-14T12:57:12Z | 9,847,476 | 18 | 2012-03-23T22:51:07Z | [
"python",
"argparse"
] | # Example of the problem
If I have a list of valid option strings which is shared between several arguments, the list is written in multiple places in the help string. Making it harder to read:
```
def main():
elements = ['a', 'b', 'c', 'd', 'e', 'f']
parser = argparse.ArgumentParser()
parser.add_argumen... | My answer doesn't attempt to extend argparse at all, but rather uses the available options of argparse as it is... Does this solve your situation?
```
import argparse
import textwrap
def main():
elements = ['a', 'b', 'c', 'd', 'e', 'f']
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDe... |
Extend argparse to write set names in the help text for optional argument choices and define those sets once at the end | 9,702,414 | 12 | 2012-03-14T12:57:12Z | 9,882,408 | 10 | 2012-03-27T02:01:11Z | [
"python",
"argparse"
] | # Example of the problem
If I have a list of valid option strings which is shared between several arguments, the list is written in multiple places in the help string. Making it harder to read:
```
def main():
elements = ['a', 'b', 'c', 'd', 'e', 'f']
parser = argparse.ArgumentParser()
parser.add_argumen... | A completely generic solution as per request by the now deleted bounty-donator and in contrast to the other answers:
```
import argparse
from operator import itemgetter
class OptionListGroup(object):
class GroupAction(object):
def __init__(self, left, right):
self.help = right
self.option_strings = ... |
Check that list of tuples has tuple with 1st element as defined string | 9,703,088 | 4 | 2012-03-14T13:37:29Z | 9,703,219 | 9 | 2012-03-14T13:45:23Z | [
"python",
"list",
"parsing",
"tuples"
] | I'm parsing HTML and I need to get only tags with selector like `div.content`.
For parsing I'm using [HTMLParser](http://docs.python.org/library/htmlparser.html). I'm so far that I get list of tags' attributes.
It looks something like this:
`[('class', 'content'), ('title', 'source')]`
The problem is that I don't k... | When looping through your elements:
```
if ('class', 'content') in element_attributes:
#do stuff
``` |
Populate numpy matrix from the difference of two vectors | 9,704,565 | 8 | 2012-03-14T15:05:54Z | 9,704,775 | 9 | 2012-03-14T15:19:51Z | [
"python",
"numpy"
] | Is it possible to construct a `numpy` matrix from a function? In this case specifically the function is the absolute difference of two vectors: `S[i,j] = abs(A[i] - B[j])`. A minimal working example that uses regular python:
```
import numpy as np
A = np.array([1,3,6])
B = np.array([2,4,6])
S = np.zeros((3,3))
for i... | I recommend taking a look into numpy's broadcasting capabilities:
```
In [6]: np.abs(A[:,np.newaxis] - B)
Out[6]:
array([[1, 3, 5],
[1, 1, 3],
[4, 2, 0]])
```
<http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html>
Then you could simply write your function as:
```
In [7]: def build_matrix(fun... |
Populate numpy matrix from the difference of two vectors | 9,704,565 | 8 | 2012-03-14T15:05:54Z | 9,705,180 | 12 | 2012-03-14T15:43:57Z | [
"python",
"numpy"
] | Is it possible to construct a `numpy` matrix from a function? In this case specifically the function is the absolute difference of two vectors: `S[i,j] = abs(A[i] - B[j])`. A minimal working example that uses regular python:
```
import numpy as np
A = np.array([1,3,6])
B = np.array([2,4,6])
S = np.zeros((3,3))
for i... | In addition to what @JoshAdel has suggested, you can also use the [`outer` method](http://docs.scipy.org/doc/numpy/reference/ufuncs.html#methods) of any numpy `ufunc` to do the broadcasting in the case of two arrays.
In this case, you just want `np.subtract.outer(A, B)` (Or, rather, the absolute value of it).
While e... |
Pyramid / SQL Alchemy DetachedInstanceError | 9,704,927 | 4 | 2012-03-14T15:30:53Z | 9,705,458 | 13 | 2012-03-14T15:59:02Z | [
"python",
"sqlalchemy",
"pyramid"
] | I'm trying to implement email confirmation using Pyramid framework.
Here's the code that confirms the user in the database and redirects them to the home page.
```
user = DbSession.query(User).filter_by(email=email).one()
if user.approved:
return {'msg': _('Already approved')}
if user.chec... | The error is because model objects (`user`) are managed by the session (`DbSession`). When you store the instance in a session (`request.session`) and then access it again in another request, this is using a different `DbSession`. Moving a managed object between sessions is supported, but not automatically. When retrie... |
pythonw.exe or python.exe? | 9,705,982 | 75 | 2012-03-14T16:30:07Z | 9,706,045 | 88 | 2012-03-14T16:33:34Z | [
"python",
"python-3.x"
] | Long story short: `pythonw.exe` does nothing, `python.exe` accepts nothing (which one should I use?)
test.py:
```
print "a"
```
CMD window:
```
C:\path>pythonw.exe test.py
<BLANK LINE>
C:\path>
C:\path>python.exe test.py
File "C:\path\test.py", line 7
print "a"
^
SyntaxError: invalid syntax
C:\p... | If you don't want a terminal window to pop up when you run your program use `pythonw.exe`;
Otherwise, use `python.exe`
Regarding the syntax error: `print` [is now a function in 3.x](http://www.python.org/dev/peps/pep-3105/)
So use instead:
```
print("a")
``` |
pythonw.exe or python.exe? | 9,705,982 | 75 | 2012-03-14T16:30:07Z | 9,706,060 | 15 | 2012-03-14T16:34:20Z | [
"python",
"python-3.x"
] | Long story short: `pythonw.exe` does nothing, `python.exe` accepts nothing (which one should I use?)
test.py:
```
print "a"
```
CMD window:
```
C:\path>pythonw.exe test.py
<BLANK LINE>
C:\path>
C:\path>python.exe test.py
File "C:\path\test.py", line 7
print "a"
^
SyntaxError: invalid syntax
C:\p... | See here: <http://docs.python.org/using/windows.html>
pythonw.exe "This suppresses the terminal window on startup." |
pythonw.exe or python.exe? | 9,705,982 | 75 | 2012-03-14T16:30:07Z | 9,706,168 | 12 | 2012-03-14T16:39:58Z | [
"python",
"python-3.x"
] | Long story short: `pythonw.exe` does nothing, `python.exe` accepts nothing (which one should I use?)
test.py:
```
print "a"
```
CMD window:
```
C:\path>pythonw.exe test.py
<BLANK LINE>
C:\path>
C:\path>python.exe test.py
File "C:\path\test.py", line 7
print "a"
^
SyntaxError: invalid syntax
C:\p... | If you're going to call a python script from some other process (say, from the command line), use `pythonw.exe`. Otherwise, your user will continuously see a `cmd` window launching the python process. It'll still run your script just the same, but it won't intrude on the user experience.
An example might be sending an... |
pythonw.exe or python.exe? | 9,705,982 | 75 | 2012-03-14T16:30:07Z | 30,313,091 | 59 | 2015-05-18T21:28:01Z | [
"python",
"python-3.x"
] | Long story short: `pythonw.exe` does nothing, `python.exe` accepts nothing (which one should I use?)
test.py:
```
print "a"
```
CMD window:
```
C:\path>pythonw.exe test.py
<BLANK LINE>
C:\path>
C:\path>python.exe test.py
File "C:\path\test.py", line 7
print "a"
^
SyntaxError: invalid syntax
C:\p... | To summarize and complement the existing answers:
* **`python.exe`** is a console (terminal) application **for launching CLI-type scripts**.
+ Unless run from an existing console window, `python.exe` **opens a new console window**.
+ **Standard streams** `sys.stdin`, `sys.stdout` and `sys.stderr` are **connected ... |
finding index of an item closest to the value in a list that's not entirely sorted | 9,706,041 | 33 | 2012-03-14T16:33:21Z | 9,706,105 | 82 | 2012-03-14T16:36:53Z | [
"python",
"list",
"search"
] | As an example my list is:
```
[25.75443, 26.7803, 25.79099, 24.17642, 24.3526, 22.79056, 20.84866, 19.49222, 18.38086, 18.0358, 16.57819, 15.71255, 14.79059, 13.64154, 13.09409, 12.18347, 11.33447, 10.32184, 9.544922, 8.813385, 8.181152, 6.983734, 6.048035, 5.505096, 4.65799]
```
and I'm looking for the index of the ... | Try the following:
```
min(range(len(a)), key=lambda i: abs(a[i]-11.5))
```
For example:
```
>>> a = [25.75443, 26.7803, 25.79099, 24.17642, 24.3526, 22.79056, 20.84866, 19.49222, 18.38086, 18.0358, 16.57819, 15.71255, 14.79059, 13.64154, 13.09409, 12.18347, 11.33447, 10.32184, 9.544922, 8.813385, 8.181152, 6.983734... |
Setting a default value in sqlalchemy | 9,706,059 | 23 | 2012-03-14T16:34:15Z | 9,706,386 | 22 | 2012-03-14T16:53:35Z | [
"python",
"sqlalchemy"
] | I would like to set a column default value that is based off of another table in my SQLAlchemy model.
Currently I have this:
```
Column('version', Integer, default=1)
```
What I need is (roughly) this:
```
Column('version', Integer, default="SELECT MAX(1, MAX(old_versions)) FROM version_table")
```
How can I imple... | The documentation gives the following possibilities for `default`:
> A scalar, Python callable, or ClauseElement representing the default
> value for this column, which will be invoked upon insert if this
> column is otherwise not specified in the VALUES clause of the insert.
You may look into using a simple function... |
increase the linewidth of the legend lines in matplotlib | 9,706,845 | 20 | 2012-03-14T17:20:32Z | 9,707,180 | 33 | 2012-03-14T17:44:10Z | [
"python",
"matplotlib",
"legend"
] | I know that if I change the linewidth of a line, that is automatically updated in the legend.
However I would like to just change the legend linewidth without affecting the plot. | Here's a simple example of how to do it:
```
import numpy as np
import matplotlib.pyplot as plt
# make some data
x = np.linspace(0, 2*np.pi)
y1 = np.sin(x)
y2 = np.cos(x)
# plot sin(x) and cos(x)
p1 = plt.plot(x, y1, 'b-', linewidth=1.0)
p2 = plt.plot(x, y2, 'r-', linewidth=1.0)
# make a legend for both plots
leg =... |
Python functions and their __call__ attribute | 9,707,600 | 11 | 2012-03-14T18:07:06Z | 9,707,643 | 11 | 2012-03-14T18:10:15Z | [
"python"
] | I am using Python 2.7.2. I want to understand the relationship between calling a function and calling the `__call__` attribute of the function. For example, consider the following code
```
def foo():
return 5
print foo() # ==> 5
print foo.__call__() # ==> 5
foo.__call__ = lambda : 6
print foo() ... | I recommend you read [special method lookup for new-style classes](http://docs.python.org/reference/datamodel.html#special-method-lookup-for-new-style-classes) (especially the last paragraph).
> For new-style classes, implicit invocations of special methods are
> only guaranteed to work correctly if defined on an obje... |
Defining a discrete colormap for imshow in matplotlib | 9,707,676 | 26 | 2012-03-14T18:12:21Z | 9,708,079 | 48 | 2012-03-14T18:39:00Z | [
"python",
"matplotlib"
] | I have a simple image that I'm showing with imshow in matplotlib. I'd like to apply a custom colormap so that values between 0-5 are white, 5-10 are red (very simple colors), etc. I've tried following this tutorial:
<http://assorted-experience.blogspot.com/2007/07/custom-colormaps.html> with the following code:
```
c... | You can use a `ListedColormap` to specify the white and red as the only colors in the color map, and the bounds determine where the transition is from one color to the next:
```
import matplotlib.pyplot as plt
from matplotlib import colors
import numpy as np
np.random.seed(101)
zvals = np.random.rand(100, 100) * 10
... |
In practice, what are the main uses for the new "yield from" syntax in Python 3.3? | 9,708,902 | 126 | 2012-03-14T19:33:41Z | 9,709,131 | 55 | 2012-03-14T19:48:42Z | [
"python",
"yield"
] | I'm having a hard time wrapping my brain around [PEP 380](http://www.python.org/dev/peps/pep-0380/).
1. What are the situations where "yield from" is useful?
2. What is the classic use case?
3. Why is it compared to micro-threads?
[ update ]
Now I understand the cause of my difficulties. I've used generators, but ne... | > What are the situations where "yield from" is useful?
Every situation where you have a loop like this:
```
for x in subgenerator:
yield x
```
As the PEP describes, this is a rather naive attempt at using the subgenerator, it's missing several aspects, especially the proper handling of the `.throw()`/`.send()`/`.... |
In practice, what are the main uses for the new "yield from" syntax in Python 3.3? | 9,708,902 | 126 | 2012-03-14T19:33:41Z | 9,709,324 | 22 | 2012-03-14T19:58:51Z | [
"python",
"yield"
] | I'm having a hard time wrapping my brain around [PEP 380](http://www.python.org/dev/peps/pep-0380/).
1. What are the situations where "yield from" is useful?
2. What is the classic use case?
3. Why is it compared to micro-threads?
[ update ]
Now I understand the cause of my difficulties. I've used generators, but ne... | Wherever you invoke a generator from within a generator you need a "pump" to re-`yield` the values: `for v in inner_generator: yield v`. As the PEP points out there are subtle complexities to this which most people ignore. Non-local flow-control like `throw()` is one example given in the PEP. The new syntax `yield from... |
In practice, what are the main uses for the new "yield from" syntax in Python 3.3? | 9,708,902 | 126 | 2012-03-14T19:33:41Z | 26,109,157 | 150 | 2014-09-29T21:22:57Z | [
"python",
"yield"
] | I'm having a hard time wrapping my brain around [PEP 380](http://www.python.org/dev/peps/pep-0380/).
1. What are the situations where "yield from" is useful?
2. What is the classic use case?
3. Why is it compared to micro-threads?
[ update ]
Now I understand the cause of my difficulties. I've used generators, but ne... | Let's get one thing out of the way first. The explanation that `yield from g` is equivalent to `for v in g: yield v` **does not even begin to do justice** to what `yield from` is all about. Because, let's face it, if all `yield from` does is expand the `for` loop, then it does not warrant adding `yield from` to the lan... |
What to set MEDIA_ROOT and MEDIA_URL to when deploying django app on Heroku | 9,710,335 | 2 | 2012-03-14T21:11:30Z | 9,710,721 | 11 | 2012-03-14T21:43:03Z | [
"python",
"django",
"heroku"
] | I have deployed an app on Heroku using their free account.
I have my js and css files inside a folder called 'media'. It looks like these are normally placed in 'static', but the project I was building on top of already had them in media so I just went with it.
So I have:
```
<link rel="stylesheet" type="text/css" m... | `MEDIA_URL` and `MEDIA_ROOT` together dictate where uploads go, i.e. anything added to `FileField`s or `ImageField`s on your models.
`STATIC_URL` and `STATIC_ROOT` together dictate the location that static resources will be dumped by the `collectstatic` management command and subsequently what URL prefix will be used ... |
Python HTMLParser dividing data at & | 9,710,845 | 4 | 2012-03-14T21:52:52Z | 9,711,015 | 7 | 2012-03-14T22:06:09Z | [
"python",
"escaping",
"html-parsing"
] | I'm using a simple HTMLParser to parse a webpage with code that is always well-formed (it's automatically generated). It works well, until it hits a piece of data with an '&' sign in it - it seems to think that that makes it two separate pieces of data and processes them separately. (That is, it calls "handle\_data" tw... | This is because `&` is the beginning of an HTML entity. A displayed `&` should be represented as `&` in the HTML (though browsers will display an `&` followed by a space as an ampersand, I believe that technically this is invalid).
You'll just need to write your `handle_data()` to accommodate the multiple calls, f... |
How to work with nulls in docutils | 9,710,987 | 6 | 2012-03-14T22:03:10Z | 9,711,072 | 7 | 2012-03-14T22:11:00Z | [
"python",
"doctest"
] | I'm trying to run doctest on a function that works with nulls. But doctest doesn't seem to like the nulls...
```
def do_something_with_hex(c):
"""
>>> do_something_with_hex('\x00')
'\x00'
"""
return repr(c)
import doctest
doctest.testmod()
```
I'm seeing these errors
```
Failed example:
do_somet... | You could escape all of the backslashes, or alternatively change your docstring to a [raw string literal](http://docs.python.org/reference/lexical_analysis.html#string-literals):
```
def do_something_with_hex(c):
r"""
>>> do_something_with_hex('\x00')
'\x00'
"""
return repr(c)
```
With the `r` pre... |
Open file in Django app | 9,711,255 | 11 | 2012-03-14T22:27:33Z | 9,711,761 | 22 | 2012-03-14T23:13:51Z | [
"python",
"django",
"file",
"directory"
] | I want to open a file from a Django app using `open()`. The problem is that `open()` seems to use whatever directory from which I run the `runserver` command as the root.
E.g. if I run the server from a directory called foo like this
```
$pwd
/Users/foo
$python myapp/manage.py runserver
```
`open()` uses `foo` as th... | The solution has been described in the [Favorite Django Tips&Tricks](http://stackoverflow.com/questions/550632/favorite-django-tips-features) question. The solution is as follows:
```
import os
module_dir = os.path.dirname(__file__) # get current directory
file_path = os.path.join(module_dir, 'baz.txt')
```
Which do... |
CSV Module AttributeError | 9,711,799 | 11 | 2012-03-14T23:17:06Z | 9,711,845 | 49 | 2012-03-14T23:22:13Z | [
"python",
"csv"
] | So I copied and pasted a demo program from the book I am using to learn Python:
```
#!/usr/bin/env python
import csv
total = 0
priciest = ('',0,0,0)
r = csv.reader(open('purchases.csv'))
for row in r:
cost = float(row[1]) * float(row[2])
total += cost
if cost == priciest[3]:
priciest = row + [c... | Don't name your file `csv.py`.
When you do, Python will look in your file for the `csv` code instead of the standard library `csv` module. |
How to programmatically capture a webcam photo | 9,711,946 | 12 | 2012-03-14T23:34:49Z | 9,712,070 | 11 | 2012-03-14T23:49:45Z | [
"python",
"video",
"ubuntu",
"webcam"
] | What's the simplest way in Ubuntu 11.10 to programmatically guide (either from Bash or Python) the user to capture a webcam photo of themselves?
I can launch a simple app like Cheese, but I don't see an easy way to immediately detect or retrieve the photo it captures. I can also access and record the webcam stream dir... | If you want to do this via Python, it looks like you have a few options. [The Pygame library has the ability to access cameras](http://www.pygame.org/docs/tut/camera/CameraIntro.html).
if that's unsatisfactory, you can go much lower level and access the [Video 4 Linux 2 API](http://alumnos.elo.utfsm.cl/~yanez/video-fo... |
How to programmatically capture a webcam photo | 9,711,946 | 12 | 2012-03-14T23:34:49Z | 9,712,824 | 32 | 2012-03-15T01:31:57Z | [
"python",
"video",
"ubuntu",
"webcam"
] | What's the simplest way in Ubuntu 11.10 to programmatically guide (either from Bash or Python) the user to capture a webcam photo of themselves?
I can launch a simple app like Cheese, but I don't see an easy way to immediately detect or retrieve the photo it captures. I can also access and record the webcam stream dir... | I like using pygame for that -
it does not require you to open a Pygame SDL window, unlike when you want to use it to capture keyboard events, for example.
```
import pygame.camera
pygame.camera.init()
cam = pygame.camera.Camera(pygame.camera.list_cameras()[0])
cam.start()
img = cam.get_image()
import pygame.image
pyg... |
NumPy: Pretty print tabular data | 9,712,085 | 11 | 2012-03-14T23:52:05Z | 9,713,042 | 17 | 2012-03-15T02:07:38Z | [
"python",
"numpy",
"pretty-print",
"tabular"
] | I would like to print NumPy tabular array data, so that it looks nice. R and database consoles seem to demonstrate good abilities to do this. However, NumPy's built-in printing of tabular arrays looks like garbage:
```
import numpy as np
dat_dtype = {
'names' : ('column_one', 'col_two', 'column_3'),
'formats' ... | I seem to be having good output with [prettytable](http://code.google.com/p/prettytable/):
```
from prettytable import PrettyTable
x = PrettyTable(dat.dtype.names)
for row in dat:
x.add_row(row)
# Change some column alignments; default was 'c'
x.align['column_one'] = 'r'
x.align['col_two'] = 'r'
x.align['column_3'... |
Newbie Django: Creating a project with several apps or all in one | 9,712,790 | 3 | 2012-03-15T01:26:38Z | 9,712,928 | 7 | 2012-03-15T01:49:49Z | [
"python",
"django"
] | I am begginer in the Django world, I developed some "information sites" (nothing complicated) but this week my boss order me to make a migration of a big software that has 7 modules.
So I went to read the documentation page and search in google for how I could design this software using Django. I know that the every "... | A good place to start (dated, but worth reading; look at user comment bubbles too): <http://www.djangobook.com/en/2.0/> . Chapter 1 - 10 are essential reading. You can pick-and-choose to read the remaining chapters, if desired.
Yes, all Django Apps can share data with one another. You make multiple Django Application'... |
EPFImporter creates table but imports nothing | 9,713,202 | 6 | 2012-03-15T02:31:23Z | 15,276,846 | 10 | 2013-03-07T16:44:16Z | [
"python",
"mysql"
] | I'm using Apple's EPFImporter tool <http://www.apple.com/itunes/affiliates/resources/documentation/epfimporter.html>
It's a Python script that will take space separated EPF file lists and import them into my database.
Here's what I have:
```
Braden-Keiths-MacBook-Pro:~ bradenkeith$ ./EPFImporter.py /Users/bradenkeit... | You can get it to work by altering EPFIngester.py according to:
1. Find function
```
def _populateTable(self, tableName, resumeNum=0,
isIncremental=False, skipKeyViolators=False):
```
2. In the function, within the while loop, find row:
```
cur = conn.cursor()
```
3. Under it insert:
```
... |
Configuration setting for Vim PEP-8 plugin to ignore errors and warnings? | 9,714,302 | 15 | 2012-03-15T05:08:18Z | 9,717,619 | 10 | 2012-03-15T10:10:33Z | [
"python",
"vim",
"pep8"
] | I am using this plugin to detect PEP-8 errors and warnings in Vim:
<http://www.vim.org/scripts/script.php?script_id=3430>
I want to ignore few errors and warnings like E501 & W601 given in the backend pep8 tool:
<http://pypi.python.org/pypi/pep8>
When I looked at the plugin code, I can see it has support for this:
`... | You need to set the variable `g:pep8_ignore`; you should put this in your vimrc.
```
let g:pep8_ignore="E501,W601"
``` |
Configuration setting for Vim PEP-8 plugin to ignore errors and warnings? | 9,714,302 | 15 | 2012-03-15T05:08:18Z | 17,299,571 | 23 | 2013-06-25T14:08:47Z | [
"python",
"vim",
"pep8"
] | I am using this plugin to detect PEP-8 errors and warnings in Vim:
<http://www.vim.org/scripts/script.php?script_id=3430>
I want to ignore few errors and warnings like E501 & W601 given in the backend pep8 tool:
<http://pypi.python.org/pypi/pep8>
When I looked at the plugin code, I can see it has support for this:
`... | For those folks that stumble across this question and the above answer doesn't work, here's some solutions for other Vim Python plugins:
For [Syntastic](https://github.com/scrooloose/syntastic):
```
let g:syntastic_python_checker="flake8"
let g:syntastic_python_checker_args="--ignore=E501,W601"
```
UPDATE: newer ver... |
How to install Python module without setup.py? | 9,714,635 | 11 | 2012-03-15T05:51:42Z | 9,714,750 | 20 | 2012-03-15T06:05:35Z | [
"python",
"ubuntu",
"install",
"setup.py"
] | I'm new to Python and am trying to install this module:
<http://www.catonmat.net/blog/python-library-for-google-search/>
There is no setup.py in the directory, but there are these files:
```
BeautifulSoup.py browser.pyc __init__.pyc sponsoredlinks.py
BeautifulSoup.pyc googlesets.py search.py translate.p... | The simplest way to begin using that code on your system is:
1. put the files into a directory on your machine,
2. add that directory's path to your PYTHONPATH
Step 2 can be accomplished from the Python REPL as follows:
```
import sys
sys.path.append("/home/username/google_search")
```
An example of how your filesy... |
how strings are stored by python in computers? | 9,715,877 | 3 | 2012-03-15T08:03:31Z | 9,715,989 | 7 | 2012-03-15T08:14:48Z | [
"python",
"string",
"encoding",
"utf"
] | I believe most of you who are familiar with Python have read Dive Into Python 3. In chapter 4.3, it says this:
> In Python 3, all strings are sequences of Unicode characters. There is no such thing as a Python string encoded in UTF-8, or a Python string encoded as CP-1252. âIs this string UTF-8?â is an invalid que... | Python 3 distinguishes between *text* and binary *data*. Text is guaranteed to be in Unicode, though no specific encoding is specified, as far as I could see. So it could be UTF-8, or UTF-16, or UTF-32¹ â but you wouldn't even notice.
The main point here is: You shouldn't even care. If you want to deal with text, t... |
Convert numbers to grades in python list | 9,717,908 | 19 | 2012-03-15T10:30:30Z | 9,718,050 | 15 | 2012-03-15T10:40:18Z | [
"python",
"list",
"filter",
"lambda"
] | I have a list which has the number of marks students have.
```
s = [50,62,15,76,57,97,82,99,45,23]
```
I want to grade students according to marks:
```
<40 - Fail
>50 - A Grade
>75 - A++ Grade
```
I can do this with iterating loops or I can find every list using lambda.
for example :
```
>>> filter(lambda x:x>=50,... | Forget `lambda`, forget `filter`; the following does the grading in one expression, assuming there's a B grade between A and "fail".
```
["fail" if g < 40 else "B" if g < 60 else "A" if g < 75 else "A++" for g in s]
```
You can `zip` the result of this with `s` to get marks and grades in one list. |
Convert numbers to grades in python list | 9,717,908 | 19 | 2012-03-15T10:30:30Z | 9,718,316 | 21 | 2012-03-15T10:58:38Z | [
"python",
"list",
"filter",
"lambda"
] | I have a list which has the number of marks students have.
```
s = [50,62,15,76,57,97,82,99,45,23]
```
I want to grade students according to marks:
```
<40 - Fail
>50 - A Grade
>75 - A++ Grade
```
I can do this with iterating loops or I can find every list using lambda.
for example :
```
>>> filter(lambda x:x>=50,... | Define a function that takes a mark and returns a human readable representation, you can use [larsmans's expression](http://stackoverflow.com/a/9718050/56763) or this one:
```
def grade(i):
if i<40: return "Fail"
if i>75: return "A++"
if i>50: return "A"
```
Use string.format to format each entry and map ... |
Reconstructing absolute urls from relative urls on a page | 9,718,541 | 14 | 2012-03-15T11:13:52Z | 9,718,651 | 23 | 2012-03-15T11:21:41Z | [
"python",
"html",
"url-parsing"
] | Given an absolute url of a page, and a relative link found within that page, would there be a way to **a)** definitively reconstruct or **b)** best-effort reconstruct the absolute url of the relative link?
In my case, I'm reading an html file from a given url using beautiful soup, stripping out all the img tag sources... | very simple:
```
>>> from urlparse import urljoin
>>> urljoin('http://mysite.com/foo/bar/x.html', '../../images/img.png')
'http://mysite.com/images/img.png'
``` |
Reconstructing absolute urls from relative urls on a page | 9,718,541 | 14 | 2012-03-15T11:13:52Z | 9,719,228 | 9 | 2012-03-15T11:59:34Z | [
"python",
"html",
"url-parsing"
] | Given an absolute url of a page, and a relative link found within that page, would there be a way to **a)** definitively reconstruct or **b)** best-effort reconstruct the absolute url of the relative link?
In my case, I'm reading an html file from a given url using beautiful soup, stripping out all the img tag sources... | Use [`urlparse.urljoin`](http://docs.python.org/library/urlparse.html#urlparse.urljoin) to resolve a (possibly relative) URL against a base URL.
*But*, the base URL of a web page isn't necessarily the same as the URL you fetched the document from, because HTML allows a page to specify its preferred base URL [via the `... |
Do I have to do StringIO.close()? | 9,718,950 | 19 | 2012-03-15T11:40:58Z | 9,719,180 | 10 | 2012-03-15T11:56:41Z | [
"python",
"stringio"
] | Some code:
```
import cStringIO
def f():
buffer = cStringIO.StringIO()
buffer.write('something')
return buffer.getvalue()
```
The [documentation](http://docs.python.org/library/stringio.html#StringIO.StringIO.close) says:
> `StringIO.close()`: Free the memory buffer. Attempting to do further
> operation... | Generally it's still better to call `close()` or use the `with` statement, because there may be some unexpected behaviour in special circumstances. For example, the expat-`IncrementalParser` seems to expect a file to be closed, or it won't return the last tidbit of parsed xml until a timeout occurs in some rare circums... |
Do I have to do StringIO.close()? | 9,718,950 | 19 | 2012-03-15T11:40:58Z | 18,398,862 | 7 | 2013-08-23T09:01:37Z | [
"python",
"stringio"
] | Some code:
```
import cStringIO
def f():
buffer = cStringIO.StringIO()
buffer.write('something')
return buffer.getvalue()
```
The [documentation](http://docs.python.org/library/stringio.html#StringIO.StringIO.close) says:
> `StringIO.close()`: Free the memory buffer. Attempting to do further
> operation... | From the source:
```
class StringIO:
...
def close(self):
"""Free the memory buffer.
"""
if not self.closed:
self.closed = True
del self.buf, self.pos
```
So `StringIO.close` just frees the memory buffer deleting references to `StringIO.buf` and `StringIO.pos`. ... |
python and UnboundLocalError | 9,720,626 | 2 | 2012-03-15T13:25:37Z | 9,721,008 | 8 | 2012-03-15T13:46:43Z | [
"python"
] | I have a little problem with local variables and python (2.7).
I have a little code :
```
def foo(a):
def bar():
print a
return bar()
>>>foo(5)
5
```
Well, it's working, but if want to modify a , like this :
```
def foo(a):
def bar():
a -= 1
return bar()
>>>foo(5)
UnboundLocalError... | You've found something that used to be an issue in Python! The short answer is that you can't do this in Python 2.x (though you can [simulate](http://davidchambersdesign.com/simulating-nonlocal-in-python-2.x/)) it, but you can in 3.x using the `nonlocal` keyword.
See [PEP 3104](http://www.python.org/dev/peps/pep-3104/... |
How do I read a fix width format text file in pandas | 9,721,429 | 8 | 2012-03-15T14:08:31Z | 9,730,620 | 7 | 2012-03-16T01:26:47Z | [
"python",
"pandas"
] | I just got my hands on pandas and am figuring out how I can read a file. The file is from WRDS database and is the SP500 constituents list all the way back to 1960s. I checked the file and no matter what I do to import it using 'read\_csv', i still cant display the data correctly.
```
df = read_csv('sp500-sb.txt')
... | Wes answered me in an email. Cheers.
This is a fixed-width-format file (not delimited by commas or tabs as
usual). I realize that pandas does not have a fixed-width reader like
R does, though one can be fashioned very easily. I'll see what I can
do. In the meantime if you can export the data in another format (like
cs... |
Python function translate relative path ../../ into full path | 9,722,210 | 3 | 2012-03-15T14:49:33Z | 9,722,283 | 14 | 2012-03-15T14:53:02Z | [
"python",
"string",
"function",
"path"
] | is there a function that translate relative path ../test.txt into a full path?
example:
the full path is:
```
/Users/paganotti/Documents/Project/simple/work/paga/
```
the relative path is:
```
../test.txt
```
I want build this result:
```
/Users/paganotti/Documents/Project/simple/work/test.txt
```
As you can see... | use this:
```
import os
os.path.abspath('../test.txt')
```
[Documentation](http://docs.python.org/library/os.path.html) |
Python super() behavior not dependable | 9,722,343 | 29 | 2012-03-15T14:56:57Z | 9,722,678 | 42 | 2012-03-15T15:15:24Z | [
"python",
"inheritance",
"superclass",
"super"
] | For some reason, the `super()` method is not always behaving as expected, opting to return:
```
TypeError('super(type, obj): obj must be an instance or subtype of type)'
```
I understand what the error *means*. I do not understand why it is coming up as an error. Here's the snippet of code that is breaking. All objec... | Are you reloading modules somehow in the middle of things? If so, that may explain this error.
`isinstance(self,DBAdminConnection)` may become false after reloading modules because of the changes to memory references, apparently.
Edit: if you're running your web.py app under mod\_wsgi, make sure you're disabling auto... |
Python super() behavior not dependable | 9,722,343 | 29 | 2012-03-15T14:56:57Z | 18,476,192 | 8 | 2013-08-27T21:59:54Z | [
"python",
"inheritance",
"superclass",
"super"
] | For some reason, the `super()` method is not always behaving as expected, opting to return:
```
TypeError('super(type, obj): obj must be an instance or subtype of type)'
```
I understand what the error *means*. I do not understand why it is coming up as an error. Here's the snippet of code that is breaking. All objec... | If you are using reload() as part of your workflow, you apparently need to also use `super(self.__class__, self).__init__` for inheritance initialization.
I suspect you will find this bug coincides with `id(self.__class__) ==id(Retrieval)` failing. |
How do I tell pandas to parse a particular column as a datetime object, but not make it an index? | 9,723,000 | 5 | 2012-03-15T15:33:47Z | 9,739,828 | 7 | 2012-03-16T15:13:30Z | [
"python",
"parsing",
"datetime",
"pandas"
] | I have a csv file where one of the columns is a date/time string. How do I parse it correctly with `pandas`? I don't want to make that column the index. Thanks!
Uri | Pass `dateutil.parser.parse` (or another datetime conversion function) in the `converters` argument to `read_csv` |
What's causing 'unable to connect to data source' for pyodbc? | 9,723,656 | 14 | 2012-03-15T16:09:33Z | 9,754,890 | 7 | 2012-03-18T00:06:54Z | [
"python",
"database",
"tsql",
"database-connection",
"pyodbc"
] | I'm trying to connect to an MSSQL database from python on Linux (SLES).
I have installed pyodbc and Free TDS. From the command line:
```
tsql -H server -p 1433 -U username -P password
```
Connects to the server without a problem, however, from Python:
```
import pyodbc
pyodbc.connect(driver='{FreeTDS}', server='ser... | After hours of going in circles it turns out all I was missing was
TDS\_Version = 8.0
in the DSN in my odbc.ini file.
I had specified it elsewhere, but it needed to be here, too, apparently.
Hope this helps some other poor soul. |
What's causing 'unable to connect to data source' for pyodbc? | 9,723,656 | 14 | 2012-03-15T16:09:33Z | 11,863,041 | 13 | 2012-08-08T10:56:16Z | [
"python",
"database",
"tsql",
"database-connection",
"pyodbc"
] | I'm trying to connect to an MSSQL database from python on Linux (SLES).
I have installed pyodbc and Free TDS. From the command line:
```
tsql -H server -p 1433 -U username -P password
```
Connects to the server without a problem, however, from Python:
```
import pyodbc
pyodbc.connect(driver='{FreeTDS}', server='ser... | I try with:
* MS SQL 2008 Datacenter
* Ubuntu 12.04 TLS (amd64)
* Python 2.7
And this works for me:
Test connection:
```
tsql -H 10.19.4.42 -p 1433 -U DAVIDG -P 123456
```
on /etc/odbcinst.ini add:
```
[ODBC]
Trace = Yes
TraceFile = /tmp/odbc.log
[FreeTDS]
Description = TDS driver (Sybase/MS SQL)
Driver = /usr/l... |
How to make South works in Heroku for a Django app | 9,724,000 | 4 | 2012-03-15T16:29:58Z | 9,724,195 | 10 | 2012-03-15T16:41:44Z | [
"python",
"database",
"django",
"heroku",
"django-south"
] | I am working on Python/Django and I am trying to use South to manage my database. In local environment is working great. The problem comes when I deploy to Heroku. The issue is that when I create a migration with
```
$heroku run manage.py schemamigration mydjangoapp
```
It looks like it works (the shell confirmed it)... | When you run 'heroku run' it connects to an isolated instance of your deployed environment. It does create the migration, however that migration is not contained within your slug. Each time you do a 'git push heroku master' it installs your dependencies and packages your application into a slug. This is more or less a ... |
Python list extension and variable assignment | 9,724,356 | 2 | 2012-03-15T16:49:51Z | 9,724,413 | 8 | 2012-03-15T16:53:29Z | [
"python",
"list",
"variable-assignment",
"extend"
] | I tried to extend a list and was puzzled by having the result return with the value None. What I tried was this:
```
>>> a = [1,2]
>>> b = [3,4]
>>> a = a.extend(b)
>>> print a
None
```
I finally realized that the problem was the redundant assignment to 'a' at the end. So this works:
```
>>> a = [1,2]
>>>... | Because, as you noticed, the return value of `extend` is `None`. This is common in the Python standard library; destructive operations return `None`, i.e. no value, so you won't be tempted to use them as if they were pure functions. Read [Guido's explanation](http://mail.python.org/pipermail/python-dev/2003-October/038... |
PowerShell is slow (much slower than Python) in large Search/Replace operation? | 9,724,521 | 18 | 2012-03-15T16:58:57Z | 9,724,670 | 9 | 2012-03-15T17:07:41Z | [
"python",
"performance",
"powershell",
"replace"
] | I have 265 CSV files with over 4 million total records (lines), and need to do a search and replace in all the CSV files. I have a snippet of my PowerShell code below that does this, but it takes 17 minutes to perform the action:
```
ForEach ($file in Get-ChildItem C:\temp\csv\*.csv)
{
$content = Get-Content -pat... | Give this PowerShell script a try. It should perform much better. Much less use of RAM too as the file is read in a buffered stream.
```
$reader = [IO.File]::OpenText("C:\input.csv")
$writer = New-Object System.IO.StreamWriter("C:\output.csv")
while ($reader.Peek() -ge 0) {
$line = $reader.ReadLine()
$line2 =... |
How does Python referencing work? | 9,724,802 | 5 | 2012-03-15T17:15:49Z | 9,725,094 | 11 | 2012-03-15T17:35:14Z | [
"python",
"reference",
"pass-by-reference",
"pass-by-value"
] | I am confused with Python referencing. Consider the following example:
My task : **To edit each element in the list**
```
d = { 'm': [1,2,3] }
m = d['m']
m = m[1:] # m changes its reference to the new sliced list, edits m but not d (I wanted to change d)
```
Similarly:
```
d = { 'm': [1,2,3] }
m = d['m']
m = m[0]... | In Python a variable is not a box that holds things, it is a name that points to an object. In your code:
* `d = { 'm': [1,2,3] }` --> binds the name `d` to a dictionary
* `m = d['m']` --> binds the name `m` to a list
* `m = m[1:]` --> binds the name `m` to another list
Your third line is not changing `m` itself, but... |
python date of the previous month | 9,724,906 | 39 | 2012-03-15T17:22:00Z | 9,725,091 | 17 | 2012-03-15T17:35:06Z | [
"python",
"date",
"time"
] | I am trying to get the date of the previous month with python.
Here is what i've tried:
```
str( time.strftime('%Y') ) + str( int(time.strftime('%m'))-1 )
```
However, this way is bad for 2 reasons: First it returns 20122 for the February of 2012 (instead of 201202) and secondly it will return 0 instead of 12 on Janu... | You should use [dateutil](http://labix.org/python-dateutil).
With that, you can use relativedelta, it's an improved version of timedelta.
```
>>> import datetime
>>> import dateutil.relativedelta
>>> now = datetime.datetime.now()
>>> print now
2012-03-15 12:33:04.281248
>>> print now + dateutil.relativedelta.relative... |
python date of the previous month | 9,724,906 | 39 | 2012-03-15T17:22:00Z | 9,725,093 | 99 | 2012-03-15T17:35:12Z | [
"python",
"date",
"time"
] | I am trying to get the date of the previous month with python.
Here is what i've tried:
```
str( time.strftime('%Y') ) + str( int(time.strftime('%m'))-1 )
```
However, this way is bad for 2 reasons: First it returns 20122 for the February of 2012 (instead of 201202) and secondly it will return 0 instead of 12 on Janu... | [datetime](http://docs.python.org/library/datetime.html) and the datetime.timedelta classes are your friend.
1. find today.
2. use that to find the first day of this month.
3. use timedelta to backup a single day, to the last day of the previous month.
4. print the YYYYMM string you're looking for.
Like this:
```
>... |
python date of the previous month | 9,724,906 | 39 | 2012-03-15T17:22:00Z | 13,199,525 | 25 | 2012-11-02T16:41:17Z | [
"python",
"date",
"time"
] | I am trying to get the date of the previous month with python.
Here is what i've tried:
```
str( time.strftime('%Y') ) + str( int(time.strftime('%m'))-1 )
```
However, this way is bad for 2 reasons: First it returns 20122 for the February of 2012 (instead of 201202) and secondly it will return 0 instead of 12 on Janu... | ```
from datetime import date, timedelta
first_day_of_current_month = date.today().replace(day=1)
last_day_of_previous_month = first_day_of_current_month - timedelta(days=1)
print "Previous month:", last_day_of_previous_month.month
```
Or:
```
from datetime import date, timedelta
prev = date.today().replace(day=1)... |
Python: extract tuples with max/min n'th element from array of tuples | 9,725,007 | 2 | 2012-03-15T17:28:57Z | 9,725,047 | 7 | 2012-03-15T17:31:47Z | [
"python"
] | In Python I have some data that looks like this:
```
A = [
(-9, [(2, 3), (5, 2), (3,1)]),
(-8, [(3, 4), (5, 6), (7, 6)]),
(-8, [(0, 0), (5, 0), (1, 6)]),
(-9, [(2, 3), (4, 2), (4, 5)]),
]
```
What is the most pythonic way to extract the element or elements that have the maximum value in the first entry? Changing t... | Try a list comprehension:
```
max_value = max(x[0] for x in A)
print [x for x in A if x[0] == max_value]
```
See it working online: [ideone](http://ideone.com/LPCyW) |
method overloading in python | 9,725,968 | 5 | 2012-03-15T18:34:57Z | 9,726,028 | 9 | 2012-03-15T18:38:31Z | [
"python"
] | I need to call unparameterised method `first`, but also parameterized `first`, but it is giving an error.
```
>>> class A:
... def first(self):
... print 'first method'
... def first(self,f):
... print 'first met',f
...
>>> a=A()
>>> a.first()
Traceback (most recent call last):
File "<s... | Your second `first` method is overriding the original `first` method. In Python, it is not possible to create overloaded methods the same way as in Java.
However, you can create methods with optional and/or keyword-based arguments and process those accordingly. Here's an example:
```
class A:
def first(self, f=No... |
Possible math.ceil() bug | 9,726,550 | 5 | 2012-03-15T19:14:06Z | 9,726,578 | 16 | 2012-03-15T19:15:50Z | [
"python"
] | On Windows 7 Python 3.2, the following:
```
print(int(math.ceil(24/10)))
```
gives me '3' as expected.
On Windows Server with Active Python 2.5, it gives me '2'.
What is the issue here and how can I solve it?
Here's my original code:
```
number_of_pages = int(math.ceil(number_of_rows/number_of_rows_per_page))
```... | Python 2.x uses truncating disivion, so the answer to `24/10` is 2. The `ceil` of 2 is still 2.
The fix is to convert one of the operands to float:
```
print(int(math.ceil(24.0/10)))
``` |
Invoking Jython from Python (or Vice Versa) | 9,727,398 | 7 | 2012-03-15T20:10:28Z | 9,828,977 | 11 | 2012-03-22T19:15:20Z | [
"python",
"jython"
] | I'm working on a framework right now, part of which requires Jython. I just added some plotting to it using MatPlotLib, without realizing that MatPlotLib is incompatible with Jython. Since these two parts are pretty isolated, and I would be fine running most of the program in Python and passing a small amount of inform... | I have not used [execnet](http://codespeak.net/execnet) for anything serious, but it seems quite possible that it is a good choice for you. execnet is a Python library for distributed execution across version, platform, and network barriers.
It is not hard to get started. This simple Jython script (that invokes NumPy)... |
List directory tree structure using Python | 9,727,673 | 27 | 2012-03-15T20:29:30Z | 9,728,245 | 13 | 2012-03-15T21:12:33Z | [
"python",
"directory-structure"
] | I know that we can use os.walk() to list all sub-directories or all files in a directory. However, I would like to list the full directory tree content:
* Subdirectory 1:
+ file11
+ file12
+ Sub-sub-directory 11:
- file111
- file112
* Subdirectory 2:
+ file21
+ sub-sub-directory 21
+ sub-sub-direct... | A solution without your indentation:
```
for path, dirs, files in os.walk(path):
print path
for f in files:
print f
```
os.walk already does the top-down, depth-first walk you are looking for.
Ignoring the dirs list prevents the overlapping you mention. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.