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 do I send attachments using SMTP? | 1,966,073 | 16 | 2009-12-27T14:31:19Z | 1,966,097 | 10 | 2009-12-27T14:39:32Z | [
"python",
"email",
"smtp",
"attachment",
"smtplib"
] | I want to write a program that sends email using Python's [smtplib](http://docs.python.org/library/smtplib.html). I searched through the document and the RFCs, but couldn't find anything related to attachments. Thus, I'm sure there's some higher-level concept I'm missing out on. Can someone clue me in on how attachment... | What you want to check out is the `email` module. It lets you build [MIME](http://en.wikipedia.org/wiki/MIME)-compliant messages that you then send with smtplib. |
How do I send attachments using SMTP? | 1,966,073 | 16 | 2009-12-27T14:31:19Z | 1,966,261 | 17 | 2009-12-27T16:03:46Z | [
"python",
"email",
"smtp",
"attachment",
"smtplib"
] | I want to write a program that sends email using Python's [smtplib](http://docs.python.org/library/smtplib.html). I searched through the document and the RFCs, but couldn't find anything related to attachments. Thus, I'm sure there's some higher-level concept I'm missing out on. Can someone clue me in on how attachment... | Here's an example I snipped out of a work application we did. It creates an HTML email with an Excel attachment.
```
import smtplib,email,email.encoders,email.mime.text,email.mime.base
smtpserver = 'localhost'
to = ['[email protected]']
fromAddr = '[email protected]'
subject = "my subject"
# create html... |
How do I send attachments using SMTP? | 1,966,073 | 16 | 2009-12-27T14:31:19Z | 8,243,031 | 19 | 2011-11-23T13:32:07Z | [
"python",
"email",
"smtp",
"attachment",
"smtplib"
] | I want to write a program that sends email using Python's [smtplib](http://docs.python.org/library/smtplib.html). I searched through the document and the RFCs, but couldn't find anything related to attachments. Thus, I'm sure there's some higher-level concept I'm missing out on. Can someone clue me in on how attachment... | Here is an example of a message with a PDF attachment, a text "body" and sending via Gmail.
```
# Import smtplib for the actual sending function
import smtplib
# For guessing MIME type
import mimetypes
# Import the email modules we'll need
import email
import email.mime.application
# Create a text/plain message
msg... |
Converting NumPy array into Python List structure? | 1,966,207 | 112 | 2009-12-27T15:29:55Z | 1,966,210 | 164 | 2009-12-27T15:31:19Z | [
"python",
"numpy"
] | How do I convert a [NumPy](http://en.wikipedia.org/wiki/NumPy) array to a Python List (for example `[[1,2,3],[4,5,6]]` ), and do it reasonably fast? | Use [`tolist()`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html):
```
import numpy as np
>>> np.array([[1,2,3],[4,5,6]]).tolist()
[[1, 2, 3], [4, 5, 6]]
``` |
Converting NumPy array into Python List structure? | 1,966,207 | 112 | 2009-12-27T15:29:55Z | 1,966,212 | 31 | 2009-12-27T15:32:33Z | [
"python",
"numpy"
] | How do I convert a [NumPy](http://en.wikipedia.org/wiki/NumPy) array to a Python List (for example `[[1,2,3],[4,5,6]]` ), and do it reasonably fast? | NumPy arrays have a [tolist method](http://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.tolist.html?highlight=tolist#numpy.ndarray.tolist):
```
In [1]: arr=np.array([[1,2,3],[4,5,6]])
In [2]: arr.tolist()
Out[2]: [[1, 2, 3], [4, 5, 6]]
``` |
hasNext in Python iterators? | 1,966,591 | 59 | 2009-12-27T18:04:51Z | 1,966,609 | 43 | 2009-12-27T18:08:52Z | [
"python",
"iterator"
] | Haven't Python iterators got a `hasNext` method? | No, there is no such method. The end of iteration is indicated by an exception. See the [documentation](http://docs.python.org/library/stdtypes.html#iterator-types). |
hasNext in Python iterators? | 1,966,591 | 59 | 2009-12-27T18:04:51Z | 1,967,037 | 27 | 2009-12-27T21:02:57Z | [
"python",
"iterator"
] | Haven't Python iterators got a `hasNext` method? | If you really **need** a `has-next` functionality (because you're just faithfully transcribing an algorithm from a reference implementation in Java, say, or because you're writing a prototype that *will* need to be easily transcribed to Java when it's finished), it's easy to obtain it with a little wrapper class. For e... |
hasNext in Python iterators? | 1,966,591 | 59 | 2009-12-27T18:04:51Z | 15,606,960 | 70 | 2013-03-25T03:05:16Z | [
"python",
"iterator"
] | Haven't Python iterators got a `hasNext` method? | There's an alternative to the `StopIteration` by using `next(iterator, default_value)`.
For exapmle:
```
>>> a = iter('hi')
>>> print next(a, None)
h
>>> print next(a, None)
i
>>> print next(a, None)
None
```
So you can detect for `None` or other pre-specified value for end of the iterator if you don't want the exce... |
Tk treeview column sort | 1,966,929 | 7 | 2009-12-27T20:18:33Z | 1,967,793 | 15 | 2009-12-28T02:49:20Z | [
"python",
"sorting",
"treeview",
"tkinter"
] | Is there a way to sort the entries in a [Tk Treeview](http://www.tkdocs.com/tutorial/tree.html) by clicking the column? Surprisingly, I could not find any documentation/tutorial for this. | [patthoyts](http://www.patthoyts.tk/) from `#tcl` pointed out that the TreeView Tk demo program had the sort functionality. Here's the Python equivalent of it:
```
def treeview_sort_column(tv, col, reverse):
l = [(tv.set(k, col), k) for k in tv.get_children('')]
l.sort(reverse=reverse)
# rearrange items i... |
Google App Engine - How do I split code into multiple files? (webapp) | 1,966,974 | 14 | 2009-12-27T20:40:01Z | 1,966,990 | 22 | 2009-12-27T20:45:50Z | [
"python",
"google-app-engine",
"web-applications"
] | I have a question about splitting up a main.py file.
right now, I have everything in my main.py. I have no other .py files. And I always have to scroll long lines of code before reaching the section I wish to edit.
How do I split it up?
(i'm going to have more than 20 pages, so that means the main.py will be HUGE if ... | Splitting the code is no different than splitting code for any Python app - find a bunch of related code that you want to move to another file, move it to that file, and import it into the main handler file.
For example, you could move the Page2 code to page2.py, put
```
import page2
```
at the top of your file, and... |
How can i create a melody? Is there any sound-module? | 1,967,040 | 7 | 2009-12-27T21:04:34Z | 1,968,691 | 7 | 2009-12-28T09:36:38Z | [
"python",
"audio"
] | I am confused because there are a lot of programms. But i am looking something like this. I will type a melody like "a4 c3 h3 a2" etc. and then i want to hear this. Does anybody know what i am looking for?
thanks in advance | computing frequencies from note name is easy. each half-note is 2^(1/12) away from the preceding note, 440 Hz is A4.
if by any chance you are on windows, you may try this piece of code, which plays a song through the PC speaker:
```
import math
import winsound
import time
labels = ['a','a#','b','c','c#','d','d#','e'... |
Python string concatenation Idiom. Need Clarification. | 1,967,723 | 4 | 2009-12-28T02:20:20Z | 1,967,732 | 12 | 2009-12-28T02:27:02Z | [
"python",
"performance",
"idioms"
] | From <http://jaynes.colorado.edu/PythonIdioms.html>
> "Build strings as a list and use
> ''.join at the end. join is a string
> method called on the separator, not
> the list. Calling it from the empty
> string concatenates the pieces with no
> separator, which is a Python quirk and
> rather surprising at first. This ... | Yes. For the examples you chose the importance isn't clear because you only have two very short strings so the append would probably be faster.
But every time you do `a + b` with strings in Python it causes a new allocation and then copies all the bytes from a and b into the new string. If you do this in a loop with l... |
Is it a bad idea to design and develop a python applications backend and then once finished try to apply a GUI to it? | 1,967,888 | 12 | 2009-12-28T03:53:30Z | 1,967,900 | 16 | 2009-12-28T03:59:29Z | [
"python",
"wxpython"
] | Is it better to do it all at once? I'm very new to wxPython and I'm thinking it would be better to write the program in a way familiar to me, then apply the wxPython gui to it after I'm satisfied with the overall design of the app. Any advice? | This is a viable approach. In fact, some programmers use it for the advantages it brings:
* Modular non-GUI code can then be tied in with different GUIs, not just a single library
* It can also be used for a command-line application (or a batch interface to a GUI one)
* It can be reused for a web application
* **And m... |
How to parse/extract data from a mediawiki marked-up article via python | 1,968,132 | 10 | 2009-12-28T05:44:48Z | 1,968,139 | 8 | 2009-12-28T05:47:56Z | [
"python",
"api",
"parsing",
"mediawiki",
"extraction"
] | [Source Mediawiki markup](http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=Foobar&redirects&rvprop=content&format=xml)
Right now I'm using a variety of regexes to "parse" the data in the mediawiki mark-up into lists/dictionaries, so that elements within the article can be used.
This is hardly the ... | ## mwlib - MediaWiki parser and utility library
[pediapress/mwlib](https://github.com/pediapress/mwlib):
> mwlib provides a library for parsing MediaWiki articles and converting them to different output formats. mwlib is used by wikipedia's "Print/export" feature in order to generate PDF documents from wikipedia arti... |
My path to learn Python/Django | 1,969,159 | 14 | 2009-12-28T12:00:29Z | 1,969,182 | 7 | 2009-12-28T12:06:02Z | [
"python",
"django"
] | I began learning Python with Dive into Python(I read some chapters), then I switched to Django using The Django Book and the Django Documentation. I made a simple web app, It worked fine but the code was a total mess.
In order to improve my skills I began reading and coding the projects of Django Practical Projects (I... | From your position, the best way to learn would be trying to make something that you've always wanted to make, but didn't make it before.
I wouldn't worry much about learning CSS/Javascript. You can learn those as need-to-know basis while working on your project. Modern javascript frameworks like jQuery make client si... |
My path to learn Python/Django | 1,969,159 | 14 | 2009-12-28T12:00:29Z | 1,969,193 | 7 | 2009-12-28T12:08:49Z | [
"python",
"django"
] | I began learning Python with Dive into Python(I read some chapters), then I switched to Django using The Django Book and the Django Documentation. I made a simple web app, It worked fine but the code was a total mess.
In order to improve my skills I began reading and coding the projects of Django Practical Projects (I... | Make a project for yourself, try something that is not in the book. This will give you some real life experience, let you make yours the concepts you've learned, stumble on real-life problems. Books are good to begin with, but you've got to jump in at some point.
You could also play with tools that use Python/Django. ... |
My path to learn Python/Django | 1,969,159 | 14 | 2009-12-28T12:00:29Z | 1,969,363 | 8 | 2009-12-28T13:01:21Z | [
"python",
"django"
] | I began learning Python with Dive into Python(I read some chapters), then I switched to Django using The Django Book and the Django Documentation. I made a simple web app, It worked fine but the code was a total mess.
In order to improve my skills I began reading and coding the projects of Django Practical Projects (I... | The best kind of learning is learning by doing. Try to start your project. If possible, choose a small part to deploy first just to keep you motivated. If you get stuck somewhere:
1. Search Google
2. Go back to the reference sites that you have already found
3. Ask SO :-) |
Mapping a range of values to another | 1,969,240 | 25 | 2009-12-28T12:24:01Z | 1,969,274 | 49 | 2009-12-28T12:33:45Z | [
"python",
"algorithm"
] | I am looking for ideas on how to translate one range values to another in Python. I am working on hardware project and am reading data from a sensor that can return a range of values, I am then using that data to drive an actuator that requires a different range of values.
For example lets say that the sensor returns ... | One solution would be:
```
def translate(value, leftMin, leftMax, rightMin, rightMax):
# Figure out how 'wide' each range is
leftSpan = leftMax - leftMin
rightSpan = rightMax - rightMin
# Convert the left range into a 0-1 range (float)
valueScaled = float(value - leftMin) / float(leftSpan)
# ... |
Mapping a range of values to another | 1,969,240 | 25 | 2009-12-28T12:24:01Z | 1,969,296 | 31 | 2009-12-28T12:40:10Z | [
"python",
"algorithm"
] | I am looking for ideas on how to translate one range values to another in Python. I am working on hardware project and am reading data from a sensor that can return a range of values, I am then using that data to drive an actuator that requires a different range of values.
For example lets say that the sensor returns ... | ### Using scipy.interpolate.interp1d
You can also use `scipy.interpolate` package to do such conversions (if you don't mind dependency on SciPy):
```
>>> from scipy.interpolate import interp1d
>>> m = interp1d([1,512],[5,10])
>>> m(256)
array(7.4951076320939336)
```
or to convert it back to normal float from 0-rank ... |
Mapping a range of values to another | 1,969,240 | 25 | 2009-12-28T12:24:01Z | 1,970,037 | 10 | 2009-12-28T15:40:24Z | [
"python",
"algorithm"
] | I am looking for ideas on how to translate one range values to another in Python. I am working on hardware project and am reading data from a sensor that can return a range of values, I am then using that data to drive an actuator that requires a different range of values.
For example lets say that the sensor returns ... | This would actually be a good case for creating a closure, that is write a function that returns a function. Since you probably have many of these values, there is little value in calculating and recalculating these value spans and factors for every value, nor for that matter, in passing those min/max limits around all... |
Django-registration - some activation | 1,970,185 | 5 | 2009-12-28T16:12:45Z | 1,970,231 | 8 | 2009-12-28T16:22:56Z | [
"python",
"django"
] | How can I force resending activation e-mail to user? E.g. when he accidentaly deletes the mail, he clicks in link in my website, and django will send him new activation e-mail. | There's an [admin action](http://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/) for doing that. From the [django-registration docs](http://docs.b-list.org/django-registration/0.8/faq.html#tips-and-tricks):
> **How do I re-send an activation email?**
>
> Assuming youâre using the default backend, a custom ... |
Django: Is there a way to have the "through" model in a ManyToManyField in a different app to the model containing the ManyToManyField? | 1,970,365 | 8 | 2009-12-28T16:50:16Z | 2,000,070 | 16 | 2010-01-04T15:04:46Z | [
"python",
"django",
"django-models",
"django-apps",
"manytomanyfield"
] | Lets say I have two django apps:
* **competitions** - which will handle competition data
* **entries** - which will handle functionality relating to entering competitors into competitions
In the competitions app I have a model which represents a section of a competition:
```
class Division(models.Model):
competi... | It seems like I've found an answer, which works more consistently :)
The [Django documentation on the ForeignKey class](http://docs.djangoproject.com/en/dev/ref/models/fields/#foreignkey) says:
> To refer to models defined in another
> application, you can explicitly
> specify a model with the full
> application labe... |
Integer overflow in numpy arrays | 1,970,680 | 5 | 2009-12-28T17:56:07Z | 1,970,697 | 12 | 2009-12-28T17:58:54Z | [
"python",
"numpy"
] | ```
import numpy as np
a = np.arange(1000000).reshape(1000,1000)
print(a**2)
```
With this code I get this answer. Why do I get negative values?
```
[[ 0 1 4 ..., 994009 996004 998001]
[ 1000000 1002001 1004004 ..., 3988009 3992004 3996001]
[ 4000000 40040... | np.arange returns an array of dtype 'int32' :
```
In [1]: np.arange(1000000).dtype
Out[1]: dtype('int32')
```
Each element of the array is a 32-bit integer. Squaring leads to a result which does not fit in 32-bits. The result is cropped to 32-bits and still interpreted as a 32-bit integer, however, which is why you s... |
Center-/middle-align text with PIL? | 1,970,807 | 18 | 2009-12-28T18:21:20Z | 1,970,930 | 34 | 2009-12-28T18:49:48Z | [
"python",
"python-imaging-library"
] | How would I center-align (and middle-vertical-align) text when using PIL? | Use [`Draw.textsize` method](http://effbot.org/imagingbook/imagedraw.htm#tag-ImageDraw.Draw.textsize) to calculate text size and re-calculate position accordingly.
Here is an example:
```
from PIL import Image, ImageDraw
W, H = (300,200)
msg = "hello"
im = Image.new("RGBA",(W,H),"yellow")
draw = ImageDraw.Draw(im)
... |
Center-/middle-align text with PIL? | 1,970,807 | 18 | 2009-12-28T18:21:20Z | 1,970,942 | 23 | 2009-12-28T18:53:56Z | [
"python",
"python-imaging-library"
] | How would I center-align (and middle-vertical-align) text when using PIL? | Here is some example code which uses textwrap to split a long line into pieces, and then uses the `textsize` method to compute the positions.
```
from PIL import Image, ImageDraw, ImageFont
import textwrap
astr = '''The rain in Spain falls mainly on the plains.'''
para = textwrap.wrap(astr, width=15)
MAX_W, MAX_H = ... |
Python seek on remote file using HTTP | 1,971,240 | 8 | 2009-12-28T19:57:07Z | 1,971,294 | 15 | 2009-12-28T20:08:44Z | [
"python",
"http",
"seek"
] | How do I seek to a particular position on a remote (HTTP) file so I can download only that part?
Lets say the bytes on a remote file were: 1234567890
I wanna seek to 4 and download 3 bytes from there so I would have: 456
and also, how do I check if a remote file exists?
I tried, os.path.isfile() but it returns False... | If you are downloading the remote file through HTTP, you need to set the `Range` header.
Check [in this example](http://code.activestate.com/recipes/83208/) how it can be done. Looks like this:
```
myUrlclass.addheader("Range","bytes=%s-" % (existSize))
```
**EDIT**: [I just found a better implementation](http://74.... |
Haystack / Whoosh Index Generation Error | 1,971,356 | 3 | 2009-12-28T20:21:29Z | 2,683,624 | 8 | 2010-04-21T14:09:43Z | [
"python",
"django",
"django-haystack",
"whoosh"
] | I'm trying to setup haystack with whoosh backend. When i try to gen the index [or any index command for that matter] i receive:
```
TypeError: Item in ``from list'' not a string
```
if i completely remove my search\_indexes.py i get the same error [so i'm guessing it can't find that file at all]
what might cause thi... | I've just encountered the same TypeError message with a completely different stack.
A search on the whole error message brought up two results: this question, and the source code for Python's import.c.
So after a little digging, I find that this particular error is caused when the `__import__` builtin is passed an imp... |
Replace letters in a secret text | 1,971,911 | 3 | 2009-12-28T22:33:25Z | 1,971,938 | 8 | 2009-12-28T22:41:10Z | [
"python",
"string"
] | I want to change every letter in a text to after next following letter. But this program doesnt work. Does anyone know why. Thanks in advance. There is also a minor problem with y and z.
```
import string
letters = string.ascii_lowercase
text=("g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgl... | Strings are **immutable** in python.
So `text.replace` *returns* a string, but doesn't change its original string.
Given that, you shouldn't actually use `text.replace`, since you would have to change the string 24 (or probably 26; see below) times. Rather, you can actually create a translation table to do all the ch... |
Interpolating a scalar field in a 3D space | 1,972,172 | 7 | 2009-12-28T23:46:15Z | 1,972,190 | 7 | 2009-12-28T23:52:49Z | [
"python",
"algorithm",
"interpolation"
] | I have a 3D space (x, y, z) with an additional parameter at each point (energy), giving 4 dimensions of data in total.
I would like to find a set of x, y, z points which correspond to an iso-energy surface found by interpolating between the known points.
The spacial mesh has constant spacing and surrounds the iso-ene... | There are quite a few options here...
In order to get your energy into your mesh, you'll need to use some form of interpolation. [Shepard's method](http://en.wikipedia.org/wiki/Inverse%5Fdistance%5Fweighting) is a common, and reasonably simple, method to implement, and tends to work well if your data distribution is r... |
"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python | 1,972,259 | 42 | 2009-12-29T00:13:07Z | 2,142,016 | 7 | 2010-01-26T19:32:44Z | [
"python",
"windows",
"virtualenv",
"pip",
"mysql-python"
] | I'm trying to install mysql-python in a virtualenv using pip on windows. At first, I was getting the same error [reported here](http://stackoverflow.com/questions/1706989/setting-up-virtualenv-for-django-development-on-windows), but the answer there worked for me too. Now I'm getting this following error:
```
_mysql.c... | Most probably the answer is to install MySQL Developer Build and selecting "C headers\libs" option during configuration. (as reported in this entry: Building MySQLdb for Python on Windows on rationalpie.wordpress.com)
Maybe even better solution is to install a precompiled build: <http://www.technicalbard.com/files/MyS... |
"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python | 1,972,259 | 42 | 2009-12-29T00:13:07Z | 5,685,209 | 15 | 2011-04-16T07:48:27Z | [
"python",
"windows",
"virtualenv",
"pip",
"mysql-python"
] | I'm trying to install mysql-python in a virtualenv using pip on windows. At first, I was getting the same error [reported here](http://stackoverflow.com/questions/1706989/setting-up-virtualenv-for-django-development-on-windows), but the answer there worked for me too. Now I'm getting this following error:
```
_mysql.c... | Update for mysql 5.5 and config-win.h not visible issue
In 5.5 config-win. has actually moved to Connector separate folder in windows. i.e. smth like:
C:\Program Files\MySQL\Connector C 6.0.2\include
To overcome the problem one need not only to download "dev bits" (which actually connects the *connector*) but also t... |
"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python | 1,972,259 | 42 | 2009-12-29T00:13:07Z | 16,619,567 | 50 | 2013-05-18T00:29:25Z | [
"python",
"windows",
"virtualenv",
"pip",
"mysql-python"
] | I'm trying to install mysql-python in a virtualenv using pip on windows. At first, I was getting the same error [reported here](http://stackoverflow.com/questions/1706989/setting-up-virtualenv-for-django-development-on-windows), but the answer there worked for me too. Now I'm getting this following error:
```
_mysql.c... | All I had to do was go over to oracle, and download the MySQL Connector C 6.0.2 and do the typical install.
<http://dev.mysql.com/downloads/connector/c/6.0.html#downloads>
Once that was done, I went into pycharms, and selected the MySQL-python==1.2.4 package to install, and it worked great. No need to update any conf... |
"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python | 1,972,259 | 42 | 2009-12-29T00:13:07Z | 18,141,164 | 19 | 2013-08-09T06:29:01Z | [
"python",
"windows",
"virtualenv",
"pip",
"mysql-python"
] | I'm trying to install mysql-python in a virtualenv using pip on windows. At first, I was getting the same error [reported here](http://stackoverflow.com/questions/1706989/setting-up-virtualenv-for-django-development-on-windows), but the answer there worked for me too. Now I'm getting this following error:
```
_mysql.c... | The accepted solution no longer seems to work for newer versions of mysql-python. The installer no longer provides a `site.cfg` file to edit.
If you are installing mysql-python it'll look for `C:\Program Files (x86)\MySQL\MySQL Connector C 6.0.2\include`. If you have a 64-bit installation of MySQL, you can simply invo... |
"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python | 1,972,259 | 42 | 2009-12-29T00:13:07Z | 19,056,568 | 12 | 2013-09-27T17:19:21Z | [
"python",
"windows",
"virtualenv",
"pip",
"mysql-python"
] | I'm trying to install mysql-python in a virtualenv using pip on windows. At first, I was getting the same error [reported here](http://stackoverflow.com/questions/1706989/setting-up-virtualenv-for-django-development-on-windows), but the answer there worked for me too. Now I'm getting this following error:
```
_mysql.c... | The accepted answer is out of date. Some of the suggestions were already incorporated in the package, and I was still getting the error about missing config-win.h & mysqlclient.lib.
* Install [mysql-connector-c-6.0.2-win32.msi](http://dev.mysql.com/downloads/connector/c/6.0.html#downloads)
> There's a zip file for ... |
What arguments does Python sort function have? | 1,972,672 | 4 | 2009-12-29T02:49:34Z | 1,973,688 | 25 | 2009-12-29T09:17:36Z | [
"python",
"sorting"
] | Is there any other argument except `key`, for example: `value`?
Thanks. | ## Arguments of `sort` and `sorted`
Both `sort` and `sorted` have three keyword arguments: `cmp`, `key` and `reverse`.
```
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list
```
Using `key` and `reverse` ... |
Why does this happen with Python's list.sort? | 1,973,164 | 3 | 2009-12-29T06:09:48Z | 1,973,169 | 7 | 2009-12-29T06:12:36Z | [
"python"
] | Given the code:
```
a=['a','b','c','d']
b=a[::-1]
print b
c=zip(a,b)
print c
c.sort(key=lambda x:x[1])#
print c
```
It prints:
```
['d', 'c', 'b', 'a']
[('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')]
[('d', 'a'), ('c', 'b'), ('b', 'c'), ('a', 'd')]
```
Why does [('a', 'd'), ('b', 'c'), ('c', 'b'), ('d', 'a')] chan... | because x[1] means *second*
use
```
c.sort(key=lambda x:x[0])
``` |
Is there a python-equivalent of the unix "file" utility? | 1,974,724 | 11 | 2009-12-29T13:48:23Z | 1,974,737 | 9 | 2009-12-29T13:51:01Z | [
"python",
"unix"
] | I want to have different behavior in a python script, depending on the type of file. I cannot use the filename extension as it may not be present or misleading. I could call the `file` utility and parse the output, but I would rather use a python builtin for portability.
So is there anything in python that uses heuris... | * [python-magic](http://pypi.python.org/pypi/python-magic/0.1)
* [pymagic](http://pypi.python.org/pypi/pymagic/0.1)
Probably others as well. "magic" is the magic keyword to search for. ;-) |
When should I use a Map instead of a For Loop? | 1,975,250 | 22 | 2009-12-29T15:41:00Z | 1,975,266 | 14 | 2009-12-29T15:44:31Z | [
"python",
"for-loop"
] | This is relating to the following: (In Python Code)
```
for i in object:
doSomething(i)
```
versus
```
map(doSomething, object)
```
Both are easy to understand, and short, but is there any speed difference? Now, if doSomething had a return value we needed to check it would be returned as a list from map, and i... | Map is useful when you want to apply the function to every item of iterable and return a list of the results. This is simpler and more concise than usng a for loop and constructing a list.
For is often more readable for other situations, and in lisp there were lots of iteration constructs that were written basically u... |
When should I use a Map instead of a For Loop? | 1,975,250 | 22 | 2009-12-29T15:41:00Z | 1,975,305 | 7 | 2009-12-29T15:53:42Z | [
"python",
"for-loop"
] | This is relating to the following: (In Python Code)
```
for i in object:
doSomething(i)
```
versus
```
map(doSomething, object)
```
Both are easy to understand, and short, but is there any speed difference? Now, if doSomething had a return value we needed to check it would be returned as a list from map, and i... | just use list comprehensions: they're more pythonic. They're also have syntax similar to generator expressions which makes it easy to switch from one to the other. You don't need to change anything when converting your code to py3k: `map` returns an iterable in py3k and you'll have to adjust your code.
if you don't ca... |
When should I use a Map instead of a For Loop? | 1,975,250 | 22 | 2009-12-29T15:41:00Z | 1,975,588 | 7 | 2009-12-29T16:45:45Z | [
"python",
"for-loop"
] | This is relating to the following: (In Python Code)
```
for i in object:
doSomething(i)
```
versus
```
map(doSomething, object)
```
Both are easy to understand, and short, but is there any speed difference? Now, if doSomething had a return value we needed to check it would be returned as a list from map, and i... | Are you familiar with the timeit module? Below are some timings. -s performs a one-time setup, and then the command is looped and the best time recorded.
```
1> python -m timeit -s "L=[]; M=range(1000)" "for m in M: L.append(m*2)"
1000 loops, best of 3: 432 usec per loop
2> python -m timeit -s "M=range(1000);f=lambda... |
Multiple level template inheritance in Jinja2? | 1,976,651 | 10 | 2009-12-29T20:03:42Z | 1,977,901 | 12 | 2009-12-30T01:05:53Z | [
"python",
"css",
"django",
"django-templates",
"jinja2"
] | I do html/css by trade, and I have been working on and off django projects as a template designer. I'm currently working on a site that uses Jinja2, which I have been using for about 2 weeks. I just found out through reading the documentation that Jinja2 doesn't support multiple level template inheritance, as in you ca... | The way the documentation worded it, it seemed like it didn't support inheritance (n) levels deep.
> Unlike Python Jinja does not support
> multiple inheritance. So you can only
> have one extends tag called per
> rendering.
I didn't know it was just a rule saying 1 extends per template.... I now know, with some help... |
Multiple level template inheritance in Jinja2? | 1,976,651 | 10 | 2009-12-29T20:03:42Z | 16,685,489 | 13 | 2013-05-22T07:05:33Z | [
"python",
"css",
"django",
"django-templates",
"jinja2"
] | I do html/css by trade, and I have been working on and off django projects as a template designer. I'm currently working on a site that uses Jinja2, which I have been using for about 2 weeks. I just found out through reading the documentation that Jinja2 doesn't support multiple level template inheritance, as in you ca... | One of the best way to achieve multiple level of templating using jinja2 is to use 'include'
let say you have '**base\_layout.html**' as your base template
```
<!DOCTYPE html>
<title>Base Layout</title>
<div>
<h1>Base</h1>
.... // write your code here
{% block body %}{% endblock %}
</div>
```
and then you want ... |
Python Module To Detect Linux Distro Version | 1,977,306 | 3 | 2009-12-29T22:22:44Z | 1,977,330 | 14 | 2009-12-29T22:28:32Z | [
"python",
"redhat",
"suse"
] | Is there an existing python module that can be used to detect which distro of Linux and which version of the distro is currently installed.
For example:
* RedHat Enterprise 5
* Fedora 11
* Suse Enterprise 11
* etc....
I can make my own module by parsing various files like /etc/redhat-release but I was wondering if a... | Look up the docs for the platform module: <http://docs.python.org/library/platform.html>
Example:
```
>>> platform.uname()
('Linux', 'localhost', '2.6.31.5-desktop-1mnb', '#1 SMP Fri Oct 23 00:05:22 EDT 2009', 'x86_64', 'AMD Athlon(tm) 64 X2 Dual Core Processor 3600+')
>>> platform.linux_distribution()
('Mandriva Lin... |
How to create module-wide variables in Python? | 1,977,362 | 101 | 2009-12-29T22:34:16Z | 1,978,076 | 117 | 2009-12-30T02:20:57Z | [
"python",
"variables",
"singleton",
"module",
"scope"
] | Is there a way to set up a global variable inside of a module? When I tried to do it the most obvious way as appears below, the Python interpreter said the variable `__DBNAME__` did not exist.
```
...
__DBNAME__ = None
def initDB(name):
if not __DBNAME__:
__DBNAME__ = name
else:
raise RuntimeE... | Here is what is going on.
First, the only global variables Python really has are module-scoped variables. You cannot make a variable that is truly global; all you can do is make a variable in a particular scope. (If you make a variable inside the Python interpreter, and then import other modules, your variable is in t... |
State of Python Packaging: Buildout, Distribute, Distutils, EasyInstall, etc | 1,977,485 | 24 | 2009-12-29T23:06:50Z | 1,977,526 | 9 | 2009-12-29T23:16:36Z | [
"python",
"distutils",
"easy-install",
"buildout",
"distribute"
] | The last time I had to worry about installing Python packages was two years ago working with [Enthought](http://www.enthought.com/), [NumPy](http://numpy.scipy.org/) and [MayaVi2](http://code.enthought.com/projects/mayavi/#Mayavi2). That experience gave me lingering nightmares related to quirky behavior installing & up... | [Distribute](http://packages.python.org/distribute/) is a new fork of `setuptools` (`easy_install`), which should also be considered. Even [Guido recommends it](http://mail.python.org/pipermail/python-dev/2009-October/092678.html).
Buildout is orthogonal to the packaging --- you can [use buildout with distribute](http... |
State of Python Packaging: Buildout, Distribute, Distutils, EasyInstall, etc | 1,977,485 | 24 | 2009-12-29T23:06:50Z | 1,977,552 | 10 | 2009-12-29T23:24:15Z | [
"python",
"distutils",
"easy-install",
"buildout",
"distribute"
] | The last time I had to worry about installing Python packages was two years ago working with [Enthought](http://www.enthought.com/), [NumPy](http://numpy.scipy.org/) and [MayaVi2](http://code.enthought.com/projects/mayavi/#Mayavi2). That experience gave me lingering nightmares related to quirky behavior installing & up... | First of all, regardless of installation tool you decide on, start using `virtualenv --no-site-packages`! That way, python packages are not installed globally and you can easily get back to where you were in old as well as new projects.
Now, your comparison is a little bit apples-to-pears as the tools you list are not... |
State of Python Packaging: Buildout, Distribute, Distutils, EasyInstall, etc | 1,977,485 | 24 | 2009-12-29T23:06:50Z | 1,986,981 | 9 | 2009-12-31T20:26:34Z | [
"python",
"distutils",
"easy-install",
"buildout",
"distribute"
] | The last time I had to worry about installing Python packages was two years ago working with [Enthought](http://www.enthought.com/), [NumPy](http://numpy.scipy.org/) and [MayaVi2](http://code.enthought.com/projects/mayavi/#Mayavi2). That experience gave me lingering nightmares related to quirky behavior installing & up... | I've done quiet a bit of research on this topic(a couple of weeks worth) before settling down on using buildout for all of my projects.
> DistUtils and EasyInstall in addition to Buildout!
The difficulty in creating one place to compare all of these tools is that they're all part of a same tool chain and are used tog... |
change desktop background | 1,977,694 | 15 | 2009-12-30T00:02:26Z | 1,977,831 | 24 | 2009-12-30T00:40:55Z | [
"python",
"background",
"desktop"
] | how can i change desktop background with python
i want to do it in both windows and linux
thanks | On Windows with python2.5 or higher, use ctypes to load user32.dll and call [`SystemParametersInfo()`](http://msdn.microsoft.com/en-us/library/ms724947%28VS.85%29.aspx) with SPI\_SETDESKWALLPAPER action.
For example:
```
import ctypes
SPI_SETDESKWALLPAPER = 20
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWA... |
change desktop background | 1,977,694 | 15 | 2009-12-30T00:02:26Z | 1,978,847 | 8 | 2009-12-30T07:11:42Z | [
"python",
"background",
"desktop"
] | how can i change desktop background with python
i want to do it in both windows and linux
thanks | On a gnome desktop, you usually do this with gconf, either directly calling gconftool or using the gconf python module. The latter is in the link given by unutbu. The first method could be done like this.
```
import commands
command = "gconftool-2 --set /desktop/gnome/background/picture_filename --type string '/path/t... |
change desktop background | 1,977,694 | 15 | 2009-12-30T00:02:26Z | 21,213,504 | 7 | 2014-01-19T05:19:36Z | [
"python",
"background",
"desktop"
] | how can i change desktop background with python
i want to do it in both windows and linux
thanks | I use the following method in one of my initial projects:
```
def set_wallpaper(self,file_loc, first_run):
# Note: There are two common Linux desktop environments where
# I have not been able to set the desktop background from
# command line: KDE, Enlightenment
desktop_env = self.... |
what does '__getnewargs__' do in this code | 1,978,264 | 7 | 2009-12-30T03:29:07Z | 1,978,269 | 8 | 2009-12-30T03:32:03Z | [
"python"
] | ```
class NavigableString(unicode, PageElement):
def __new__(cls, value):
if isinstance(value, unicode):
return unicode.__new__(cls, value)
return unicode.__new__(cls, value, DEFAULT_OUTPUT_ENCODING)
def __getnewargs__(self):#this line
return (NavigableString.__str__(self),... | Try this:
```
x = NavigableString('foop')
y = pickle.dumps(x)
z = pickle.loads(y)
print x, z
```
I.e.: [`__getnewargs__`](https://docs.python.org/2/library/pickle.html#object.__getnewargs__) tells `pickle.dumps` to pickle `x` in such a way that a `pickle.loads` back from that string will use `NavigableString.__new__`... |
How to specify psycopg2 parameter for an array for timestamps (datetimes) | 1,978,586 | 9 | 2009-12-30T05:42:28Z | 1,979,010 | 12 | 2009-12-30T08:04:40Z | [
"python",
"postgresql",
"timestamp",
"psycopg2",
"python-db-api"
] | I'd like to run a PostgreSQL query in Python using psycopg2, which filters by a column of type `timestamp without timezone`. I have a long list of allowed values for the timestamp (rather than a range) and psycopg2 conveniently handles arrays, so I thought that this should work:
```
SELECT somestuff
FROM mytable
WHERE... | Try it like this:
```
SELECT somestuff
FROM mytable
WHERE thetimestamp = ANY (%(times)s::timestamp[])
``` |
What is the difference between isinstance('aaa', basestring) and isinstance('aaa', str)? | 1,979,004 | 91 | 2009-12-30T08:02:53Z | 1,979,017 | 7 | 2009-12-30T08:05:41Z | [
"python",
"built-in-types"
] | ```
a='aaaa'
print isinstance(a, basestring)#true
print isinstance(a, str)#true
``` | All strings are basestrings, but unicode strings are not of type str. Try this instead:
```
>>> a=u'aaaa'
>>> print isinstance(a, basestring)
True
>>> print isinstance(a, str)
False
``` |
What is the difference between isinstance('aaa', basestring) and isinstance('aaa', str)? | 1,979,004 | 91 | 2009-12-30T08:02:53Z | 1,979,107 | 239 | 2009-12-30T08:42:08Z | [
"python",
"built-in-types"
] | ```
a='aaaa'
print isinstance(a, basestring)#true
print isinstance(a, str)#true
``` | In Python versions prior to 3.0 there are two kinds of strings "plain strings" and "unicode strings". Plain strings (`str`) cannot represent characters outside of the Latin alphabet (ignoring details of code pages for simplicity). Unicode strings (`unicode`) can represent characters from any alphabet including some fic... |
how can i escape '\xff\xfe' to a readable string | 1,979,171 | 2 | 2009-12-30T09:03:36Z | 1,979,195 | 11 | 2009-12-30T09:10:36Z | [
"python",
"unicode",
"encoding",
"escaping"
] | i see a string in this code:
```
data[:2] == '\xff\xfe'
```
i don't know what '\xff\xfe' is,
so i want to escape it ,but not successful
```
import cgi
print cgi.escape('\xff\xfe')#print \xff\xfe
```
how can i get it.
thanks | '\xFF' means the byte with the hex value FF. '\xff\xfe' is a byte-order mark: <http://en.wikipedia.org/wiki/Byte%5Forder%5Fmark>
You could also represent it as two separate characters but that probably won't tell you anything useful. |
What does python print() function actually do? | 1,979,234 | 8 | 2009-12-30T09:20:43Z | 1,979,304 | 8 | 2009-12-30T09:40:57Z | [
"python",
"unicode",
"printing",
"python-2.x"
] | I was looking at this [question](http://stackoverflow.com/questions/1979171/how-can-i-escape-xff-xfe-to-a-readable-string) and started wondering what does the `print` actually do.
I have never found out how to use `string.decode()` and `string.encode()` to get an unicode string "out" in the python interactive shell in... | **EDIT:** (Major changes between this edit and the previous one... Note: I'm using Python 2.6.4 on an Ubuntu box.)
Firstly, in my first attempt at an answer, I provided some general information on `print` and `str` which I'm going to leave below for the benefit of anybody having simpler issues with `print` and chancin... |
Py2exe - win32api.pyc ImportError DLL load failed | 1,979,486 | 7 | 2009-12-30T10:32:30Z | 1,980,464 | 29 | 2009-12-30T14:28:00Z | [
"python",
"py2exe"
] | I am trying to use py2exe to distribute a python application I have written. Everything seems to go OK, but when I run it on another machine it fails with the following error:
```
Traceback (most recent call last):
File "application.py", line 12, in <module>
File "win32api.pyc", line 12, in <module>
File "win32a... | I've seen this problem when the package was built on Vista but executed on XP. The problem turned out to be that py2exe mistakenly added `powrprof.dll` and `mswsock.dll` to the package. Windows XP contains its own copies of these files though, and can't load the Vista ones which got installed with your app.
Removing t... |
Loading SQL dump before running Django tests | 1,979,692 | 7 | 2009-12-30T11:27:58Z | 2,589,487 | 7 | 2010-04-07T01:39:22Z | [
"python",
"django",
"django-testing"
] | I have a fairly complex Django project which makes it hard/impossible to use fixtures for loading data.
What I would like to do is to load a database dump from the production database server after all tables has bene created by the testrunner and before the actual tests start running.
I've tried various "magic" in My... | Django supports loading SQL files when doing syncdb, reset, or starting a test runner -- this does exactly what you describe:
<http://docs.djangoproject.com/en/dev/howto/initial-data/#providing-initial-sql-data>
You need to create an "sql" directory in your app directory, and then put a file named "mymodel.sql" in th... |
Python dll Extension Import | 1,979,793 | 3 | 2009-12-30T11:51:49Z | 1,979,911 | 10 | 2009-12-30T12:18:52Z | [
"python",
"dll"
] | I created extensions for my Python and created a `abcPython.dll`. How can I import this dll into my Python scripts?
I get an error message when I try to import it usin the following command
```
>>>import abcPython
>>>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No modu... | Follow [Building C and C++ Extensions on Windows](http://docs.python.org/extending/windows.html#a-cookbook-approach) carefully - in sub-section 7, it says:
> The output file should be called spam.pyd (in Release mode) or spam\_d.pyd (in Debug mode). The **extension .pyd** was chosen to avoid confusion with a system li... |
How to render a doctype with Python's xml.dom.minidom? | 1,980,380 | 6 | 2009-12-30T14:08:28Z | 1,980,552 | 10 | 2009-12-30T14:51:09Z | [
"python",
"xml",
"doctype"
] | I tried:
```
document.doctype = xml.dom.minidom.DocumentType('html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "DTD/xhtml1-strict.dtd"')
```
There is no doctype in the output. How to fix without inserting it by hand? | You shouldn't instantiate classes from `minidom` directly. It's not a supported part of the API, the `ownerDocument`âs won't tie up and you can get some strange misbehaviours. Instead use the proper DOM Level 2 Core methods:
```
>>> imp= minidom.getDOMImplementation('')
>>> dt= imp.createDocumentType('html', '-//W3C... |
Is there any reason to use threading.Lock over multiprocessing.Lock? | 1,980,479 | 7 | 2009-12-30T14:33:21Z | 1,980,929 | 11 | 2009-12-30T16:03:58Z | [
"python",
"multithreading",
"process",
"locking",
"multiprocessing"
] | If a software project supports a version of Python that multiprocessing has been backported to, is there any reason to use `threading.Lock` over `multiprocessing.Lock`? Would a `multiprocessing` lock not be thread safe as well?
For that matter, is there a reason to use *any* synchronization primitives from `threading`... | The threading module's synchronization primitive are lighter and faster than multiprocessing, due to the lack of dealing with shared semaphores, etc. If you are using threads; use threading's locks. Processes should use multiprocessing's locks. |
Loading an image in Python (Error) | 1,981,138 | 3 | 2009-12-30T16:44:29Z | 1,981,148 | 9 | 2009-12-30T16:46:28Z | [
"python",
"image"
] | I want to load an image but I get an error-message.
My code:
```
from PIL import Image
im = Image.open("D:\Python26\PYTHON-PROGRAMME\bild.jpg")
im.show()
```
I get this error:
```
Traceback (most recent call last):
File "D:\Python26\PYTHON-PROGRAMME\00000000000000000", line 2, in <module>
im = Image.open("D:\... | You need to escape the backslashes:
```
im = Image.open("D:\\Python26\\PYTHON-PROGRAMME\\bild.jpg")
``` |
Protection from accidentally misnaming object attributes in Python? | 1,981,208 | 4 | 2009-12-30T16:59:16Z | 1,981,235 | 7 | 2009-12-30T17:04:20Z | [
"python",
"attributes"
] | A friend was "burned" when starting to learn Python, and now sees the language as perhaps fatally flawed.
He was using a library and changed the value of an object's attribute (the class being in the library), but he used the wrong abbreviation for the attribute name. It took him "forever" to figure out what was wrong... | There are code analyzers like [pylint](http://www.logilab.org/857) that will warn you if you add a attribute outside of `__init__`. PyDev has nice support for it. Such errors are very easy to find with a debugger too. |
Protection from accidentally misnaming object attributes in Python? | 1,981,208 | 4 | 2009-12-30T16:59:16Z | 1,981,279 | 11 | 2009-12-30T17:14:56Z | [
"python",
"attributes"
] | A friend was "burned" when starting to learn Python, and now sees the language as perhaps fatally flawed.
He was using a library and changed the value of an object's attribute (the class being in the library), but he used the wrong abbreviation for the attribute name. It took him "forever" to figure out what was wrong... | "changed the value of an object's attribute" Can lead to problems. This is pretty well known. You know it, now, also. That doesn't indict the language. It simply says that you've learned an important lesson in dynamic language programming.
1. Unit testing absolutely discovers this. You are not forced to mock all libra... |
How to tell if Python SQLite database connection or cursor is closed? | 1,981,392 | 7 | 2009-12-30T17:36:54Z | 1,981,584 | 8 | 2009-12-30T18:10:26Z | [
"python",
"sqlite",
"sqlite3",
"database-connection"
] | Let's say that you have the following code:
```
import sqlite3
conn = sqlite3.connect('mydb')
cur = conn.cursor()
# some database actions
cur.close()
conn.close()
# more code below
```
If I try to use the `conn` or `cur` objects later on, how could I tell that they are closed? I cannot find a `.isclosed()` method or... | You could wrap in a `try, except` statement:
```
>>> conn = sqlite3.connect('mydb')
>>> conn.close()
>>> try:
... resultset = conn.execute("SELECT 1 FROM my_table LIMIT 1;")
... except sqlite3.ProgrammingError as e:
... print e
Cannot operate on a closed database.
```
This relies on a [shortcut specific to sqlite... |
What makes pylint think my class is abstract? | 1,981,978 | 5 | 2009-12-30T19:31:38Z | 1,982,807 | 11 | 2009-12-30T22:10:12Z | [
"python",
"pylint"
] | As I understand it, Python (2.5.2) does not have real support for abstract classes. Why is pylint complaining about this class being an "Abstract class not reference?" Will it do this for any class that has `NotImplementedError` thrown?
I have each class in its own file so if this is the case I guess I have no choice ... | FWIW, raising NotImplementedError is enough to make pylint think this is an abstract class (which is absolutely correct). from logilab.org/card/pylintfeatures: W0223: Method %r is abstract in class %r but is not overridden Used when an abstract method (ie raise NotImplementedError) is not overridden in concrete class. ... |
Does Python 3 have LDAP module? | 1,982,442 | 8 | 2009-12-30T20:56:47Z | 17,780,873 | 26 | 2013-07-22T06:00:48Z | [
"python",
"ldap",
"python-3.x"
] | I am porting some Java code to Python and we would like to use Python 3 but I can't find LDAP module for Python 3 in Windows.
This is forcing us to use 2.6 version and it is bothersome as rest of the code is already in 3.0 format. | You may use **[ldap3](https://pypi.python.org/pypi/ldap3)** module (formerly known as **python3-ldap**), it runs on python3 really well and requires no external C dependances. Also it can correctly handle both unicode and byte data in ldap records (in early versions there was a trouble with jpegPhoto field, now everyth... |
Are Python docstrings and comments stored in memory when module is loaded? | 1,983,177 | 6 | 2009-12-30T23:55:57Z | 1,983,281 | 17 | 2009-12-31T00:21:29Z | [
"python",
"comments",
"memory-management",
"docstring"
] | > Are Python docstrings and comments stored in memory when module is loaded?
I've wondered if this is true, because I usually document my code well; may this affect memory usage?
**Usually every Python object has a `__doc__` method. Are those docstrings read from the file, or processed otherwise?**
I've done searche... | By default, docstrings are present in the `.pyc` bytecode file, and are loaded from them (comments are not). If you use `python -OO` (the `-OO` flag stands for "optimize intensely", as opposed to `-O` which stands for "optimize mildly), you get and use `.pyo` files instead of `.pyc` files, and those are optimized by om... |
Python Encapsulate a function to Print to a variable | 1,983,401 | 3 | 2009-12-31T00:56:12Z | 1,983,450 | 7 | 2009-12-31T01:10:43Z | [
"python"
] | If I have a function that contains a lot of print statements:
ie.
```
def funA():
print "Hi"
print "There"
print "Friend"
print "!"
```
What I want to do is something like this
```
def main():
##funA() does not print to screen here
a = getPrint(funA()) ##where getPrint is some made up function/object
... | You can do *almost* exactly what you want, as long as you don't mind a tiny syntax difference:
```
import cStringIO
import sys
def getPrint(thefun, *a, **k):
savstdout = sys.stdout
sys.stdout = cStringIO.StringIO()
try:
thefun(*a, **k)
finally:
v = sys.stdout.getvalue()
sys.stdout = savstdout
re... |
How can I have Google App Engine clear memcache every time a site is deployed? | 1,983,556 | 25 | 2009-12-31T01:45:30Z | 1,983,573 | 21 | 2009-12-31T01:52:13Z | [
"python",
"google-app-engine",
"deployment",
"caching",
"memcached"
] | The title asks it all. The content on the site I'm building wont change very quickly at all and so Memcache could potentially store data for months except for when I put up an update. Is there a way to make it clear the cache every time I deploy the site? I'm using the Python runtime.
### Update 1
~~Using [jldupont](... | Have you tried `flush_all()` function? [Docs here](http://code.google.com/appengine/docs/python/memcache/functions.html). You'll need a bit of logic & state to detect a new deployment or have a special script to perform the flushing.
**Updated**: look at the absolute path of one of your script: this changes on every d... |
How to avoid explicit 'self' in Python? | 1,984,104 | 55 | 2009-12-31T05:50:07Z | 1,984,116 | 7 | 2009-12-31T05:54:33Z | [
"python",
"self"
] | I have been learning Python by following some [pygame tutorials](http://www.pygame.org/wiki/tutorials).
Therein I found extensive use of the keyword *self*, and coming from a primarily Java background, I find that I keep forgetting to type *self*. For example, instead of `self.rect.centerx` I would type `rect.centerx`... | yes, you must always specify `self`, because explicit is better than implicit, according to python philosophy.
You will also find out that the way you program in python is very different from the way you program in java, hence the use of `self` tends to decrease because you don't project everything inside the object. ... |
How to avoid explicit 'self' in Python? | 1,984,104 | 55 | 2009-12-31T05:50:07Z | 1,984,120 | 13 | 2009-12-31T05:56:37Z | [
"python",
"self"
] | I have been learning Python by following some [pygame tutorials](http://www.pygame.org/wiki/tutorials).
Therein I found extensive use of the keyword *self*, and coming from a primarily Java background, I find that I keep forgetting to type *self*. For example, instead of `self.rect.centerx` I would type `rect.centerx`... | Actually `self` is not a keyword, it's just the name conventionally given to the first parameter of instance methods in Python. And that first parameter can't be skipped, as it's the only mechanism a method has of knowing which instance of your class it's being called on. |
How to avoid explicit 'self' in Python? | 1,984,104 | 55 | 2009-12-31T05:50:07Z | 1,984,121 | 61 | 2009-12-31T05:57:29Z | [
"python",
"self"
] | I have been learning Python by following some [pygame tutorials](http://www.pygame.org/wiki/tutorials).
Therein I found extensive use of the keyword *self*, and coming from a primarily Java background, I find that I keep forgetting to type *self*. For example, instead of `self.rect.centerx` I would type `rect.centerx`... | **Python requires specifying self.** The result is there's never any confusion over what's a member and what's not, even without the full class definition visible. This leads to useful properties, such as: you can't add members which accidentally shadow non-members and thereby break code.
One extreme example: you can ... |
How to avoid explicit 'self' in Python? | 1,984,104 | 55 | 2009-12-31T05:50:07Z | 1,984,191 | 11 | 2009-12-31T06:18:24Z | [
"python",
"self"
] | I have been learning Python by following some [pygame tutorials](http://www.pygame.org/wiki/tutorials).
Therein I found extensive use of the keyword *self*, and coming from a primarily Java background, I find that I keep forgetting to type *self*. For example, instead of `self.rect.centerx` I would type `rect.centerx`... | You can use whatever name you want, for example
```
class test(object):
def function(this, variable):
this.variable = variable
```
or even
```
class test(object):
def function(s, variable):
s.variable = variable
```
but you are stuck with using a name for the scope.
I do not recommend you u... |
Purpose of Python's __repr__ | 1,984,162 | 56 | 2009-12-31T06:06:39Z | 1,984,174 | 11 | 2009-12-31T06:11:46Z | [
"python"
] | ```
def __repr__(self):
return '<%s %s (%s:%s) %s>' % (
self.__class__.__name__, self.urlconf_name, self.app_name,
self.namespace, self.regex.pattern)
```
What is the significance/purpose of this method? | This is explained quite well in the [Python documentation](http://docs.python.org/library/functions.html#repr):
> **repr(object)**: Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operat... |
Purpose of Python's __repr__ | 1,984,162 | 56 | 2009-12-31T06:06:39Z | 1,984,177 | 80 | 2009-12-31T06:12:38Z | [
"python"
] | ```
def __repr__(self):
return '<%s %s (%s:%s) %s>' % (
self.__class__.__name__, self.urlconf_name, self.app_name,
self.namespace, self.regex.pattern)
```
What is the significance/purpose of this method? | `__repr__` should return a printable representation of the object, most likely *one* of the ways possible to create this object. See official documentation [here](http://docs.python.org/library/functions.html#repr). `__repr__` is more for developers while `__str__` is for end users.
A simple example:
```
>>> class Po... |
Explaining Python's '__enter__' and '__exit__' | 1,984,325 | 114 | 2009-12-31T07:07:18Z | 1,984,346 | 145 | 2009-12-31T07:13:06Z | [
"python"
] | this is i saw in someone's code:
```
def __enter__(self):
return self
def __exit__(self, type, value, tb):
self.stream.close()
```
---
```
from __future__ import with_statement#for python2.5
class a(object):
def __enter__(self):
print 'sss'
return 'sss111'
def __exi... | Using these magic methods (`__enter__`, `__exit__`) allows you to implement objects which can be used easily with the `with` statement.
The idea is that it makes it easy to build code which needs some 'cleandown' code executed (think of it as a `try-finally` block). [Some more explanation here](http://effbot.org/zone/... |
Cross product of two vectors in Python | 1,984,799 | 11 | 2009-12-31T10:13:41Z | 1,984,817 | 25 | 2009-12-31T10:20:10Z | [
"python"
] | How can I calculate the cross product of two vectors without the use of programming libraries?
E.g given vectors `a = (1, 2, 3)` and `b = (4, 5, 6)` | ```
import numpy as np
a = np.array([1,0,0])
b = np.array([0,1,0])
print np.cross(a,b)
``` |
Cross product of two vectors in Python | 1,984,799 | 11 | 2009-12-31T10:13:41Z | 1,984,823 | 27 | 2009-12-31T10:21:34Z | [
"python"
] | How can I calculate the cross product of two vectors without the use of programming libraries?
E.g given vectors `a = (1, 2, 3)` and `b = (4, 5, 6)` | are you asking about the formula for the cross product? Or how to do indexing and lists in python?
The basic idea is that you access the elements of a and b as a[0], a[1], a[2], etc. (for x, y, z) and that you create a new list with [element\_0, element\_1, ...]. We can also wrap it in a function.
On the vector side,... |
Need init.d script for Python application | 1,984,847 | 2 | 2009-12-31T10:27:59Z | 1,984,855 | 7 | 2009-12-31T10:30:21Z | [
"python",
"ubuntu",
"init.d"
] | I have a python based application which works like a feed aggregator and needs to be part of init.d script so that I could control the execution with start/stop/restart options. Also I want the init.d script to be setup as a cron job (I have example here).
I found one sample here <http://homepage.hispeed.ch/py430/pyth... | You could consider writing a Upstart task for operating systems which use Upstart.
Example:
```
# Start zeya
#
description "Start Zeya music server"
start on startup
task
exec python /home/r00t/code-hacking/serve-music/zeya/src/zeya/zeya.py
--path=/home/r00t/Music
```
Add this to a file, say 'zeya.conf' in /e... |
Using SimpleHTTPServer for unit testing | 1,985,197 | 14 | 2009-12-31T12:14:25Z | 1,985,511 | 11 | 2009-12-31T13:57:26Z | [
"python",
"unit-testing",
"simplehttpserver"
] | I'm writing a Python module that wraps out a certain web service API. It's all REST, so relatively straightforward to implement.
However, I found a problem when it comes to unit testing: as I don't run the services I made this module for, I don't want to hammer them, but at the same time, I need to retrieve data to ru... | Try using a [subclass of TCPServer with `allow_reuse_address` set True](http://docs.python.org/library/socketserver.html#SocketServer.BaseServer.allow_reuse_address):
```
class TestServer(SocketServer.TCPServer):
allow_reuse_address = True
...
httpd = TestServer(("", PORT), handler)
``` |
update django database to reflect changes in existing models | 1,985,383 | 65 | 2009-12-31T13:23:46Z | 1,985,409 | 34 | 2009-12-31T13:28:54Z | [
"python",
"django",
"django-models"
] | I've already defined a model and created its associated database via `manager.py syncdb`. Now that I've added some fields to the model, I tried `syncdb` again, but no output appears. Upon trying to access these new fields from my templates, I get a "No Such Column" exception, leading me to believe that syncdb didn't ac... | Seems like what you need is a migration system. [South](http://south.aeracode.org/) is really nice, working great, has some automation tools to ease your workflow. And has a great [tutorial](http://south.aeracode.org/wiki/Tutorial1).
---
note: syncdb can't update your existing tables. Sometimes it's impossible to dec... |
update django database to reflect changes in existing models | 1,985,383 | 65 | 2009-12-31T13:23:46Z | 1,985,567 | 7 | 2009-12-31T14:12:31Z | [
"python",
"django",
"django-models"
] | I've already defined a model and created its associated database via `manager.py syncdb`. Now that I've added some fields to the model, I tried `syncdb` again, but no output appears. Upon trying to access these new fields from my templates, I get a "No Such Column" exception, leading me to believe that syncdb didn't ac... | Django's syncdb doesn't alter existing tables in the database so you have to do it manually. The way I always do it is:
1. Change the model class first.
2. Then run: manage.py sql myapp.
3. Look at the sql it prints out and see how it represented the change you are going to make.
4. Make the change manually using your... |
update django database to reflect changes in existing models | 1,985,383 | 65 | 2009-12-31T13:23:46Z | 1,989,523 | 7 | 2010-01-01T20:24:37Z | [
"python",
"django",
"django-models"
] | I've already defined a model and created its associated database via `manager.py syncdb`. Now that I've added some fields to the model, I tried `syncdb` again, but no output appears. Upon trying to access these new fields from my templates, I get a "No Such Column" exception, leading me to believe that syncdb didn't ac... | Another tool would be django evolution. No table dropping needed in most cases.
[django evolution](http://code.google.com/p/django-evolution/)
Just install it as any other django app and run:
python manage.py evolve --hint --execute |
update django database to reflect changes in existing models | 1,985,383 | 65 | 2009-12-31T13:23:46Z | 1,992,512 | 132 | 2010-01-02T19:12:43Z | [
"python",
"django",
"django-models"
] | I've already defined a model and created its associated database via `manager.py syncdb`. Now that I've added some fields to the model, I tried `syncdb` again, but no output appears. Upon trying to access these new fields from my templates, I get a "No Such Column" exception, leading me to believe that syncdb didn't ac... | Another option, not requiring additional apps, is to use the built in `manage.py` functions to export your data, clear the database and restore the exported data.
The methods below will update the database tables for your app, but will **completely destroy** any data that existed in those tables. If the changes you ma... |
update django database to reflect changes in existing models | 1,985,383 | 65 | 2009-12-31T13:23:46Z | 27,664,925 | 24 | 2014-12-27T06:17:57Z | [
"python",
"django",
"django-models"
] | I've already defined a model and created its associated database via `manager.py syncdb`. Now that I've added some fields to the model, I tried `syncdb` again, but no output appears. Upon trying to access these new fields from my templates, I get a "No Such Column" exception, leading me to believe that syncdb didn't ac... | As of Django 1.7, you can now do this with native migrations. Just run
```
python manage.py makemigrations <your app name>
python manage.py migrate
``` |
How to make a 3D scatter plot in Python? | 1,985,856 | 27 | 2009-12-31T15:37:06Z | 1,986,020 | 46 | 2009-12-31T16:29:09Z | [
"python",
"3d",
"matplotlib",
"plot",
"scatter-plot"
] | I am currently have a nx3 matrix array. I want plot the three columns as three axis's.
How can I do that?
I have googled and people suggested using **Matlab**, but I am really having a hard time with understanding it. I also need it be a scatter plot.
Can someone teach me? | You can use [matplotlib](http://matplotlib.sourceforge.net/) for this. matplotlib has a [mplot3d](http://matplotlib.sourceforge.net/mpl_toolkits/mplot3d/index.html) module that will do exactly what you want.
```
from matplotlib import pyplot
import pylab
from mpl_toolkits.mplot3d import Axes3D
import random
fig = py... |
Memory requirments for large python list | 1,985,975 | 5 | 2009-12-31T16:15:12Z | 1,986,046 | 10 | 2009-12-31T16:35:36Z | [
"python",
"memory-management",
"32bit-64bit"
] | I was doing a foolish thing like
```
from itertools import *
rows = combinations(range(0, 1140), 17)
all_rows = []
for row in rows:
all_rows.append(row)
```
No surprise I run out of memory address space (32 bit python 3.1)
My question i, how do I calculate how much memory address space I will need for a large lis... | There's a handy function [`sys.getsizeof()`](http://docs.python.org/library/sys.html#sys.getsizeof) (since Python 2.6) that helps with this:
```
>>> import sys
>>> sys.getsizeof(1) # integer
12
>>> sys.getsizeof([]) # empty list
36
>>> sys.getsizeof(()) # empty tuple
28
>>> sys.getsizeof((1,)) # tuple with one eleme... |
Gruberâs URL Regular Expression in Python | 1,986,059 | 4 | 2009-12-31T16:38:01Z | 1,986,151 | 9 | 2009-12-31T16:55:42Z | [
"python",
"regex",
"gruber"
] | How do I rewrite this [new way to recognise](http://alanstorm.com/url_regex_explained) addresses to work in Python?
`\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))` | The [original source](http://daringfireball.net/2009/11/liberal_regex_for_matching_urls) for that states "This pattern should work in most modern regex implementations" and specifically Perl. Python's regex implementation is modern and [similar to Perl's](http://docs.python.org/library/re.html#module-re) but is missing... |
Why doesn't Python have a sign function? | 1,986,152 | 115 | 2009-12-31T16:56:40Z | 1,986,718 | 43 | 2009-12-31T19:12:11Z | [
"python",
"language-design"
] | I can't understand why Python doesn't have a `sign` function. It has an `abs` builtin (which I consider `sign`'s sister), but no `sign`.
In python 2.6 there is even a `copysign` function (in [math](http://docs.python.org/library/math.html#math.copysign)), but no sign. Why bother to write a `copysign(x,y)` when you cou... | "copysign" is defined by IEEE 754, and part of the C99 specification. That's why it's in Python. The function cannot be implemented in full by abs(x) \* sign(y) because of how it's supposed to handle NaN values.
```
>>> import math
>>> math.copysign(1, float("nan"))
1.0
>>> math.copysign(1, float("-nan"))
-1.0
>>> mat... |
Why doesn't Python have a sign function? | 1,986,152 | 115 | 2009-12-31T16:56:40Z | 1,986,776 | 145 | 2009-12-31T19:25:00Z | [
"python",
"language-design"
] | I can't understand why Python doesn't have a `sign` function. It has an `abs` builtin (which I consider `sign`'s sister), but no `sign`.
In python 2.6 there is even a `copysign` function (in [math](http://docs.python.org/library/math.html#math.copysign)), but no sign. Why bother to write a `copysign(x,y)` when you cou... | **EDIT:**
Indeed there was a [patch](http://bugs.python.org/msg58786) which included `sign()` in [math](http://docs.python.org/library/math.html#math.copysign), but it wasn't accepted, because they didn't agree on [what it should return in all the edge cases](http://bugs.python.org/msg59137) (+/-0, +/-nan, etc)
So th... |
Why doesn't Python have a sign function? | 1,986,152 | 115 | 2009-12-31T16:56:40Z | 16,726,462 | 20 | 2013-05-24T01:37:40Z | [
"python",
"language-design"
] | I can't understand why Python doesn't have a `sign` function. It has an `abs` builtin (which I consider `sign`'s sister), but no `sign`.
In python 2.6 there is even a `copysign` function (in [math](http://docs.python.org/library/math.html#math.copysign)), but no sign. Why bother to write a `copysign(x,y)` when you cou... | Another one liner for sign()
```
sign = lambda x: (1, -1)[x<0]
```
If you want it to return 0 for x = 0:
```
sign = lambda x: x and (1, -1)[x<0]
``` |
Why doesn't Python have a sign function? | 1,986,152 | 115 | 2009-12-31T16:56:40Z | 24,035,421 | 13 | 2014-06-04T10:48:09Z | [
"python",
"language-design"
] | I can't understand why Python doesn't have a `sign` function. It has an `abs` builtin (which I consider `sign`'s sister), but no `sign`.
In python 2.6 there is even a `copysign` function (in [math](http://docs.python.org/library/math.html#math.copysign)), but no sign. Why bother to write a `copysign(x,y)` when you cou... | Since `cmp` has been [removed](https://docs.python.org/3.0/whatsnew/3.0.html), you can get the same functionality with
```
def cmp(a, b):
return (a > b) - (a < b)
def sign(a):
return (a > 0) - (a < 0)
```
It works for `float`, `int` and even `Fraction`. In the case of `float`, notice `sign(float("nan"))` is ... |
Data Structures in Python | 1,986,712 | 11 | 2009-12-31T19:10:12Z | 1,986,739 | 14 | 2009-12-31T19:16:30Z | [
"python",
"data-structures"
] | All the books I've read on data structures so far seem to use C/C++, and make heavy use of the "manual" pointer control that they offer. Since Python hides that sort of memory management and garbage collection from the user is it even possible to implement efficient data structures in this language, and is there any re... | For some simple data structures (eg. a stack), you can just use the builtin list to get your job done. With more complex structures (eg. a bloom filter), you'll have to implement them yourself using the primitives the language supports.
You should use the builtins if they serve your purpose really since they're debugg... |
Data Structures in Python | 1,986,712 | 11 | 2009-12-31T19:10:12Z | 1,986,749 | 8 | 2009-12-31T19:18:24Z | [
"python",
"data-structures"
] | All the books I've read on data structures so far seem to use C/C++, and make heavy use of the "manual" pointer control that they offer. Since Python hides that sort of memory management and garbage collection from the user is it even possible to implement efficient data structures in this language, and is there any re... | C/C++ data structure books are only attempting to teach you the underlying principles behind the various structures - they are generally not advising you to actually go out and re-invent the wheel by building your own library of stacks and lists.
Whether you're using Python, C++, C#, Java, whatever, you should always ... |
Data Structures in Python | 1,986,712 | 11 | 2009-12-31T19:10:12Z | 1,987,019 | 16 | 2009-12-31T20:37:01Z | [
"python",
"data-structures"
] | All the books I've read on data structures so far seem to use C/C++, and make heavy use of the "manual" pointer control that they offer. Since Python hides that sort of memory management and garbage collection from the user is it even possible to implement efficient data structures in this language, and is there any re... | Python gives you some powerful, highly optimized data structures, both as built-ins and as part of a few modules in the standard library (`list`s and `dict`s, of course, but also `tuple`s, `set`s, `array`s in module [array](http://docs.python.org/library/array.html?highlight=array#module-array), and some other containe... |
Determining if root logger is set to DEBUG level in Python? | 1,987,468 | 32 | 2009-12-31T23:24:06Z | 1,987,484 | 46 | 2009-12-31T23:31:11Z | [
"python",
"logging",
"decorator"
] | If I set the logging module to DEBUG with a command line parameter like this:
```
if (opt["log"] == "debug"):
logging.basicConfig(level=logging.DEBUG)
```
How can I later tell if the logger was set to DEBUG? I'm writing a decorator that
will time a function if True flag is passed to it, and if no flag is given, it ... | ```
logging.getLogger().getEffectiveLevel()
```
`logging.getLogger()` without arguments gets the root level logger.
<http://docs.python.org/library/logging.html#logging.Logger.getEffectiveLevel> |
Determining if root logger is set to DEBUG level in Python? | 1,987,468 | 32 | 2009-12-31T23:24:06Z | 27,849,836 | 20 | 2015-01-08T21:29:29Z | [
"python",
"logging",
"decorator"
] | If I set the logging module to DEBUG with a command line parameter like this:
```
if (opt["log"] == "debug"):
logging.basicConfig(level=logging.DEBUG)
```
How can I later tell if the logger was set to DEBUG? I'm writing a decorator that
will time a function if True flag is passed to it, and if no flag is given, it ... | Actually, there's one better: use the code `logging.getLogger().isEnabledFor(logging.DEBUG)`. I found it while trying to understand what to do with the result of `getEffectiveLevel()`. :-)
(Below is an image of the code that the logging module itself uses.)
 |
What does this code mean: "print >> sys.stderr" | 1,987,626 | 16 | 2010-01-01T01:00:23Z | 1,987,629 | 21 | 2010-01-01T01:02:29Z | [
"python",
"syntax"
] | ```
print >> sys.stderr, "Error in atexit._run_exitfuncs:"
```
Why print '>>' in front of `sys.stderr`?
Thanks. | This syntax means writes to a file object (`sys.stderr` in this case) instead of standard output. [[Link]](http://docs.python.org/reference/simple_stmts.html#print)
In Python 3.0, `print` becomes a function instead of a statement: [[Link]](http://docs.python.org/library/functions.html#print)
```
print("Error in atexi... |
Print the full numpy array | 1,987,694 | 146 | 2010-01-01T01:51:46Z | 1,987,705 | 34 | 2010-01-01T02:02:41Z | [
"python",
"arrays",
"numpy"
] | When I print a numpy array, I get a truncated representation, but I want the full array.
Is there any way to do this?
**Examples:**
```
>>> numpy.arange(10000)
array([ 0, 1, 2, ..., 9997, 9998, 9999])
>>> numpy.arange(10000).reshape(250,40)
array([[ 0, 1, 2, ..., 37, 38, 39],
[ 40, 41... | This sounds like you're using numpy.
If that's the case, you can add:
```
set_printoptions(threshold=nan)
```
That will disable the corner printing. For more information, see this [NumPy Tutorial](http://www.scipy.org/Tentative_NumPy_Tutorial#head-a476da892560e3bf994ec9b363e169b6467cd5a4). |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.