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
(Python) algorithm to randomly select a key based on proportionality/weight
2,570,690
8
2010-04-03T08:41:26Z
2,570,801
9
2010-04-03T09:39:46Z
[ "python" ]
I'm a bit at a loss as to how to find a clean algorithm for doing the following: Suppose I have a dict k: ``` >>> k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} ``` I now want to randomly select one of these keys, based on the 'weight' they have in the total (i.e. sum) amount of keys. ``` >>> sum(k.values()) >>...
This should do the trick: ``` >>> k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} >>> import random >>> def weighted_pick(dic): ... total = sum(dic.itervalues()) ... pick = random.randint(0, total-1) ... tmp = 0 ... for key, weight in dic.iteritems(): ... tmp += weight ... if pick < t...
(Python) algorithm to randomly select a key based on proportionality/weight
2,570,690
8
2010-04-03T08:41:26Z
2,570,802
9
2010-04-03T09:40:05Z
[ "python" ]
I'm a bit at a loss as to how to find a clean algorithm for doing the following: Suppose I have a dict k: ``` >>> k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81} ``` I now want to randomly select one of these keys, based on the 'weight' they have in the total (i.e. sum) amount of keys. ``` >>> sum(k.values()) >>...
Here's a weighted choice function, with some code that exercises it. ``` import random def WeightedPick(d): r = random.uniform(0, sum(d.itervalues())) s = 0.0 for k, w in d.iteritems(): s += w if r < s: return k return k def Test(): k = {'A': 68, 'B': 62, 'C': 47, 'D': 16, 'E': 81...
urlencode an array of values
2,571,145
24
2010-04-03T11:41:54Z
2,571,182
9
2010-04-03T12:00:25Z
[ "python", "http" ]
I'm trying to urlencode an dictionary in python with urllib.urlencode. The problem is, I have to encode an array. The result needs to be: ``` criterias%5B%5D=member&criterias%5B%5D=issue #unquoted: criterias[]=member&criterias[]=issue ``` But the result I get is: ``` criterias=%5B%27member%27%2C+%27issue%27%5D #unq...
You can use a list of key-value pairs (tuples): ``` >>> urllib.urlencode([('criterias[]', 'member'), ('criterias[]', 'issue')]) 'criterias%5B%5D=member&criterias%5B%5D=issue' ```
urlencode an array of values
2,571,145
24
2010-04-03T11:41:54Z
10,233,141
40
2012-04-19T17:05:00Z
[ "python", "http" ]
I'm trying to urlencode an dictionary in python with urllib.urlencode. The problem is, I have to encode an array. The result needs to be: ``` criterias%5B%5D=member&criterias%5B%5D=issue #unquoted: criterias[]=member&criterias[]=issue ``` But the result I get is: ``` criterias=%5B%27member%27%2C+%27issue%27%5D #unq...
The solution is far simpler than the ones listed above. ``` >>> import urllib >>> params = {'criterias[]': ['member', 'issue']} >>> >>> print urllib.urlencode(params, True) criterias%5B%5D=member&criterias%5B%5D=issue ``` Note the True. See <http://docs.python.org/library/urllib.html#urllib.urlencode> the doseq vari...
Python beautiful soup arguments
2,571,228
5
2010-04-03T12:22:48Z
2,571,245
7
2010-04-03T12:29:12Z
[ "python", "beautifulsoup" ]
I have this code that fetches some text from a page using BeautifulSoup ``` soup= BeautifulSoup(html) body = soup.find('div' , {'id':'body'}) print body ``` I would like to make this as a reusable function that takes in some htmltext and the tags to match it like the following ``` def parse(html, atrs): soup= Beaut...
``` def parse(html, *atrs): soup= BeautifulSoup(html) body = soup.find(*atrs) return body ``` And then: ``` parse(htmlpage, 'div', {'id':'body'}) ```
Changing models in django results in broken database?
2,571,337
3
2010-04-03T13:20:17Z
2,571,349
9
2010-04-03T13:26:36Z
[ "python", "django", "django-models", "django-admin" ]
I have added and removed fields in my models.py file and then run manage.py syncdb. Usually I have to quit out of the shell and restart it before syncdb does anything. And then even after that, I am getting errors when trying to access the admin pages, it seems that certain new fields that I've added still don't show u...
Django does not perform database migration for you, i.e., if you add new fields, Django won't modify your database schema. You can either: 1. Drop the tables that changed and perform syncdb again. This is reasonnable when you are developing your application and you don't have any real data in your database. 2. Use a ...
Self-referential ReferenceProperty in Google App Engine
2,571,507
2
2010-04-03T14:31:06Z
2,571,576
9
2010-04-03T14:54:28Z
[ "python", "google-app-engine" ]
I'm having a bit of trouble with ReferencePropertys in App Engine (Python). For a bit of fun, I'm trying to model a folder/file system, but having trouble getting folders to reference folders. My first attempt was this: ``` class Folder(db.Model): id = db.StringProperty() name = db.StringProperty() creat...
That's exactly what [SelfReferenceProperty](http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#SelfReferenceProperty) is for.
Using a Unicode format for Python's `time.strftime()`
2,571,515
12
2010-04-03T14:35:31Z
2,571,568
21
2010-04-03T14:51:58Z
[ "python", "unicode" ]
I am trying to call Python's `time.strftime()` function using a Unicode format string: ``` u'%d\u200f/%m\u200f/%Y %H:%M:%S' ``` ([`\u200f`](http://www.fileformat.info/info/unicode/char/200f/index.htm) is the "Right-To-Left Mark" (RLM).) However, I am getting an exception that the RLM character cannot be encoded into...
Many standard library functions still don't support Unicode the way they should. You can use this workaround: ``` fmt = u'%d\u200f/%m\u200f/%Y %H:%M:%S' time.strftime(fmt.encode('utf-8'), <your time here>).decode('utf-8') ```
Python2.6 Decimal to Octal
2,571,840
3
2010-04-03T16:22:48Z
2,571,849
9
2010-04-03T16:25:42Z
[ "python", "decimal", "octal" ]
How can i convert decimal to Octal in Python2.6, for 1 to 100000? I wanna get this converted result as .txt too. Can someone help me?
Use the `oct` function: ``` print oct(9) # prints 011 ```
Python's safest method to store and retrieve passwords from a database
2,572,099
23
2010-04-03T17:44:57Z
2,572,116
30
2010-04-03T17:50:07Z
[ "python", "encryption", "passwords", "password-protection" ]
Looking to store usernames and passwords in a database, and am wondering what the safest way to do so is. I know I have to use a salt somewhere, but am not sure how to generate it securely or how to apply it to encrypt the password. Some sample Python code would be greatly appreciated. Thanks.
Store the password+salt as a hash and the salt. Take a look at how Django does it: [basic docs](https://docs.djangoproject.com/en/1.8/topics/auth/passwords/) and [source](http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/models.py). In the db they store `<type of hash>$<salt>$<hash>` in a single ch...
Python's safest method to store and retrieve passwords from a database
2,572,099
23
2010-04-03T17:44:57Z
10,948,783
12
2012-06-08T12:22:37Z
[ "python", "encryption", "passwords", "password-protection" ]
Looking to store usernames and passwords in a database, and am wondering what the safest way to do so is. I know I have to use a salt somewhere, but am not sure how to generate it securely or how to apply it to encrypt the password. Some sample Python code would be greatly appreciated. Thanks.
I think it is best to use a package dedicated to hashing passwords for this like passlib: <http://packages.python.org/passlib/> for reasons as I explained here: <http://stackoverflow.com/a/10948614/893857>
Python's safest method to store and retrieve passwords from a database
2,572,099
23
2010-04-03T17:44:57Z
18,494,729
8
2013-08-28T17:42:49Z
[ "python", "encryption", "passwords", "password-protection" ]
Looking to store usernames and passwords in a database, and am wondering what the safest way to do so is. I know I have to use a salt somewhere, but am not sure how to generate it securely or how to apply it to encrypt the password. Some sample Python code would be greatly appreciated. Thanks.
I answered this here: <http://stackoverflow.com/a/18488878/1661689>, and so did @Koffie. I don't know how to emphasize enough that the accepted answer is NOT secure. It is better than plain text, and better than an unsalted hash, but it is still **extremely vulnerable** to dictionary and even brute-force attacks. Inst...
Extract the SHA1 hash from a torrent file
2,572,521
17
2010-04-03T20:10:21Z
2,573,715
22
2010-04-04T05:59:06Z
[ "python", "hash", "extract", "sha1", "bittorrent" ]
I've had a look around for the answer to this, but I only seem to be able to find software that does it for you. Does anybody know how to go about doing this in python?
I wrote a piece of python code that verifies the hashes of *downloaded files* against what's in a *.torrent file*. Assuming you want to check a download for corruption you may find this useful. You need the [bencode package](http://pypi.python.org/pypi/BitTorrent-bencode) to use this. Bencode is the serialization form...
Extract the SHA1 hash from a torrent file
2,572,521
17
2010-04-03T20:10:21Z
4,173,411
13
2010-11-13T16:07:30Z
[ "python", "hash", "extract", "sha1", "bittorrent" ]
I've had a look around for the answer to this, but I only seem to be able to find software that does it for you. Does anybody know how to go about doing this in python?
Here how I've extracted HASH value from torrent file: ``` #!/usr/bin/python import sys, os, hashlib, StringIO import bencode def main(): # Open torrent file torrent_file = open(sys.argv[1], "rb") metainfo = bencode.bdecode(torrent_file.read()) info = metainfo['info'] print hashlib.sha1(bencode....
Python lambda returning None instead of empty string
2,572,564
7
2010-04-03T20:27:15Z
2,572,572
8
2010-04-03T20:31:50Z
[ "python", "lambda" ]
I have the following lambda function: ``` f = lambda x: x == None and '' or x ``` It should return an empty string if it receives None as the argument, or the argument if it's not None. For example: ``` >>> f(4) 4 >>> f(None) >>> ``` If I call f(None) instead of getting an empty string I get None. I printed the ty...
The problem in your case that '' is considered as boolean False. bool('') == False. You can use ``` f =lambda x:x if x is not None else '' ```
Python lambda returning None instead of empty string
2,572,564
7
2010-04-03T20:27:15Z
2,572,575
15
2010-04-03T20:31:58Z
[ "python", "lambda" ]
I have the following lambda function: ``` f = lambda x: x == None and '' or x ``` It should return an empty string if it receives None as the argument, or the argument if it's not None. For example: ``` >>> f(4) 4 >>> f(None) >>> ``` If I call f(None) instead of getting an empty string I get None. I printed the ty...
use the if else construct ``` f = lambda x:'' if x is None else x ```
Return a list of imported Python modules used in a script?
2,572,582
17
2010-04-03T20:33:45Z
2,572,623
9
2010-04-03T20:48:25Z
[ "python", "module" ]
I am writing a program that categorizes a list of Python files by which modules they import. As such I need to scan the collection of .py files ad return a list of which modules they import. As an example, if one of the files I import has the following lines: ``` import os import sys, gtk ``` I would like it to retur...
IMO the best way todo this is to use the <http://furius.ca/snakefood/> package. The author has done all of the required work to get not only directly imported modules but it uses the AST to parse the code for runtime dependencies that a more static analysis would miss. Worked up a command example to demonstrate: sfoo...
Numpy ‘smart’ symmetric matrix
2,572,916
46
2010-04-03T22:39:56Z
2,573,982
53
2010-04-04T09:06:56Z
[ "python", "matrix", "numpy" ]
Is there a smart and space-efficient symmetric matrix in numpy which automatically (and transparently) fills the position at `[j][i]` when `[i][j]` is written to? ``` a = numpy.symmetric((3, 3)) a[0][1] = 1 a[1][0] == a[0][1] # True print a # [[0 1 0], [1 0 0], [0 0 0]] assert numpy.all(a == a.T) # for any symmetric ...
If you can afford to symmetrize the matrix just before doing calculations, the following should be reasonably fast: ``` def symmetrize(a): return a + a.T - numpy.diag(a.diagonal()) ``` This works under reasonable assumptions (such as not doing both `a[0, 1] = 42` and the contradictory `a[1, 0] = 123` before runni...
Numpy ‘smart’ symmetric matrix
2,572,916
46
2010-04-03T22:39:56Z
9,455,669
12
2012-02-26T18:06:50Z
[ "python", "matrix", "numpy" ]
Is there a smart and space-efficient symmetric matrix in numpy which automatically (and transparently) fills the position at `[j][i]` when `[i][j]` is written to? ``` a = numpy.symmetric((3, 3)) a[0][1] = 1 a[1][0] == a[0][1] # True print a # [[0 1 0], [1 0 0], [0 0 0]] assert numpy.all(a == a.T) # for any symmetric ...
The more general issue of optimal treatment of symmetric matrices in numpy bugged me too. After looking into it, I think the answer is probably that numpy is somewhat constrained by the memory layout supportd by the underlying BLAS routines for symmetric matrices. While some BLAS routines do exploit symmetry to speed...
What is the best interface from Python 3.1.1 to R?
2,573,132
12
2010-04-04T00:25:43Z
2,661,971
20
2010-04-18T10:52:37Z
[ "python", "interface", "python-3.x" ]
I am using Python 3.1.1 on Mac OS X 10.6.2 and need an interface to R. When browsing the internet I found out about RPy. Is this the right choice? Currently, a program in Python computes a distance matrix and, stores it in a file. I invoke R separately in an interactive way and read in the matrix for cluster analysis....
**edit:** Rewrite to summarize the edits that accumulated over time. The current rpy2 release (2.3.x series) has full support for Python 3.3, while no claim is made about Python 3.0, 3.1, or 3.2. At the time of writing the next rpy2 release (under development, 2.4.x series) is only supporting Python 3.3. History of P...
Python progression path - From apprentice to guru
2,573,135
659
2010-04-04T00:28:33Z
2,573,141
23
2010-04-04T00:32:10Z
[ "python" ]
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutio...
Google just recently released an online Python class ("class" as in "a course of study"). <http://code.google.com/edu/languages/google-python-class/> I know this doesn't answer your full question, but I think it's a great place to start!
Python progression path - From apprentice to guru
2,573,135
659
2010-04-04T00:28:33Z
2,573,229
108
2010-04-04T01:16:40Z
[ "python" ]
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutio...
One good way to further your Python knowledge is to **dig into the source code of the libraries, platforms, and frameworks you use already.** For example if you're building a site on [Django](http://www.djangoproject.com/), many questions that might stump you can be answered by looking at how Django implements the fea...
Python progression path - From apprentice to guru
2,573,135
659
2010-04-04T00:28:33Z
2,573,269
20
2010-04-04T01:38:56Z
[ "python" ]
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutio...
Download [Twisted](http://twistedmatrix.com/trac/wiki/Downloads) and look at the source code. They employ some pretty advanced techniques.
Python progression path - From apprentice to guru
2,573,135
659
2010-04-04T00:28:33Z
2,573,362
10
2010-04-04T02:32:21Z
[ "python" ]
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutio...
I learned python first by myself over a summer just by doing the tutorial on the python site (sadly, I don't seem to be able to find that anymore, so I can't post a link). Later, python was taught to me in one of my first year courses at university. In the summer that followed, I practiced with [PythonChallenge](http:...
Python progression path - From apprentice to guru
2,573,135
659
2010-04-04T00:28:33Z
2,573,526
59
2010-04-04T04:06:11Z
[ "python" ]
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutio...
**Understand Introspection** * write a `dir()` equivalent * write a `type()` equivalent * figure out how to ["monkey-patch"](http://en.wikipedia.org/wiki/Monkey_patch) * use the `dis` module to see how various language constructs work Doing these things will * give you some good theoretical knowledge about how pytho...
Python progression path - From apprentice to guru
2,573,135
659
2010-04-04T00:28:33Z
2,573,531
12
2010-04-04T04:08:54Z
[ "python" ]
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutio...
**Thoroughly Understand All Data Types and Structures** For every type and structure, write a series of demo programs that exercise every aspect of the type or data structure. If you do this, it might be worthwhile to blog notes on each one... it might be useful to lots of people!
Python progression path - From apprentice to guru
2,573,135
659
2010-04-04T00:28:33Z
2,573,761
7
2010-04-04T06:39:57Z
[ "python" ]
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutio...
Have you seen the book "[Bioinformatics Programming using Python](http://oreilly.com/catalog/9780596154516/)"? Looks like you're an exact member of its focus group.
Python progression path - From apprentice to guru
2,573,135
659
2010-04-04T00:28:33Z
2,573,965
92
2010-04-04T08:58:31Z
[ "python" ]
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutio...
**Understand (more deeply) Python's data types and their roles with regards to memory mgmt** As some of you in the community are aware, [I teach Python courses](http://cyberwebconsulting.com), the most popular ones being the comprehensive Intro+Intermediate course as well as an "advanced" course which introduces a var...
Python progression path - From apprentice to guru
2,573,135
659
2010-04-04T00:28:33Z
2,575,917
67
2010-04-04T21:14:21Z
[ "python" ]
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutio...
Check out Peter Norvig's essay on becoming a master programmer in 10 years: <http://norvig.com/21-days.html>. I'd wager it holds true for any language.
Python progression path - From apprentice to guru
2,573,135
659
2010-04-04T00:28:33Z
2,576,226
41
2010-04-04T23:14:34Z
[ "python" ]
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutio...
I'll give you the simplest and most effective piece of advice I think anybody could give you: **code**. You can only be better at using a language (which implies understanding it) by *coding*. You have to actively enjoy coding, be inspired, ask questions, and find answers by yourself. Got a an hour to spare? Write co...
Python progression path - From apprentice to guru
2,573,135
659
2010-04-04T00:28:33Z
2,576,240
471
2010-04-04T23:19:53Z
[ "python" ]
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutio...
I thought the process of Python mastery went something like: 1. Discover [list comprehensions](http://en.wikipedia.org/wiki/List_comprehension#Python) 2. Discover [generators](http://en.wikipedia.org/wiki/Python_syntax_and_semantics#Generators) 3. Incorporate [map, reduce, filter, iter, range, xrange](http://docs.pyth...
Python progression path - From apprentice to guru
2,573,135
659
2010-04-04T00:28:33Z
4,147,969
24
2010-11-10T18:56:11Z
[ "python" ]
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutio...
If you're in and using python for science (which it seems you are) part of that will be learning and understanding scientific libraries, for me these would be * numpy * scipy * matplotlib * mayavi/mlab * chaco * Cython knowing how to use the right libraries and vectorize your code is essential for scientific computin...
Python progression path - From apprentice to guru
2,573,135
659
2010-04-04T00:28:33Z
4,162,150
48
2010-11-12T06:22:54Z
[ "python" ]
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutio...
``` def apprentice(): read(diveintopython) experiment(interpreter) read(python_tutorial) experiment(interpreter, modules/files) watch(pycon) def master(): refer(python-essential-reference) refer(PEPs/language reference) experiment() read(good_python_code) # Eg. twisted, other libraries write(basic_...
Python progression path - From apprentice to guru
2,573,135
659
2010-04-04T00:28:33Z
6,043,780
10
2011-05-18T11:15:08Z
[ "python" ]
I've been learning, working, and playing with Python for a year and a half now. As a biologist slowly making the turn to bio-informatics, this language has been at the very core of all the major contributions I have made in the lab. I more or less fell in love with the way Python permits me to express beautiful solutio...
## Learning algorithms/maths/file IO/Pythonic optimisation This won't get you guru-hood but to start out, try working through the [Project Euler problems](http://projecteuler.net/) The first 50 or so shouldn't tax you if you have decent high-school mathematics and know how to Google. When you solve one you get into th...
Python: unable to inherit from a C extension
2,573,519
6
2010-04-04T04:02:30Z
2,573,536
8
2010-04-04T04:13:55Z
[ "python", "inheritance" ]
I am trying to add a few extra methods to a matrix type from the pysparse library. Apart from that I want the new class to behave exactly like the original, so I chose to implement the changes using inheritance. However, when I try ``` from pysparse import spmatrix class ll_mat(spmatrix.ll_mat): pass ``` this re...
`ll_mat` is documented to be a [function](http://pysparse.sourceforge.net/spmatrix.html#spmatrix-module-functions) -- not the type itself. The idiom is known as "factory function" -- it allows a "creator callable" to return different actual underlying types depending on its arguments. You could try to generate an obje...
Django - urls.py - Filenames with a hash/pound (#) sign?
2,573,803
2
2010-04-04T07:04:51Z
2,573,814
8
2010-04-04T07:15:17Z
[ "python", "regex", "django" ]
I'm using django and realized that when the filename that the user wants to access (let's say a photo) has the pound sign, the entry in the url.py does not match. Any ideas? ``` url(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': MEDIA_ROOT}, ``` it just says: ``` "/home/user/projec...
This isn't really Django's fault - the pound (#) sign in a URL means to load the specified anchor on the page. You need to encode the pound sign in your URL to get the browser to request the full image path: ``` /home/user/project/static/upload/images/hello%23world.jpg ``` In a Django template you can use the [urlenc...
Creating Signed URLs for Amazon CloudFront
2,573,919
18
2010-04-04T08:31:37Z
6,624,431
31
2011-07-08T12:30:39Z
[ "python", "cdn", "amazon-cloudfront" ]
Short version: How do I make signed URLs "on-demand" to mimic Nginx's X-Accel-Redirect behavior (i.e. protecting downloads) with Amazon CloudFront/S3 using Python. I've got a Django server up and running with an Nginx front-end. I've been getting hammered with requests to it and recently had to install it as a [Tornad...
[Amazon CloudFront Signed URLs](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-signed-urls-overview.html) work differently than Amazon S3 signed URLs. CloudFront uses RSA signatures based on a separate CloudFront keypair which you have to set up in your Amazon Account Credentials page...
Creating Signed URLs for Amazon CloudFront
2,573,919
18
2010-04-04T08:31:37Z
16,145,598
11
2013-04-22T11:04:55Z
[ "python", "cdn", "amazon-cloudfront" ]
Short version: How do I make signed URLs "on-demand" to mimic Nginx's X-Accel-Redirect behavior (i.e. protecting downloads) with Amazon CloudFront/S3 using Python. I've got a Django server up and running with an Nginx front-end. I've been getting hammered with requests to it and recently had to install it as a [Tornad...
As many have commented already, the [initially accepted answer](http://stackoverflow.com/a/2628984/45773) doesn't apply to [Amazon CloudFront](http://aws.amazon.com/cloudfront/) in fact, insofar [Serving Private Content through CloudFront](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/PrivateContent...
Sorting a list of dot sparated numbers, like software versions
2,574,080
30
2010-04-04T09:51:57Z
2,574,090
44
2010-04-04T09:56:31Z
[ "python" ]
I have a list containing version strings, such as things: ``` versions_list = ["1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"] ``` I would like to sort it, so the result would be something like this: ``` versions_list = ["1.0.0", "1.0.2", "1.0.12", "1.1.2", "1.3.3"] ``` The order of precendece for the digits should o...
Split each version string to compare it as a list of integers: ``` versions_list.sort(key=lambda s: map(int, s.split('.'))) ``` Gives, for your list: ``` ['1.0.0', '1.0.2', '1.0.12', '1.1.2', '1.3.3'] ``` In Python3 `map` no longer returns a `list`, So we need to [wrap it in a `list` call](http://stackoverflow.com/...
Sorting a list of dot sparated numbers, like software versions
2,574,080
30
2010-04-04T09:51:57Z
2,574,230
65
2010-04-04T11:16:22Z
[ "python" ]
I have a list containing version strings, such as things: ``` versions_list = ["1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"] ``` I would like to sort it, so the result would be something like this: ``` versions_list = ["1.0.0", "1.0.2", "1.0.12", "1.1.2", "1.3.3"] ``` The order of precendece for the digits should o...
You can also use `distutils.version` module of standard library: ``` from distutils.version import StrictVersion versions = ["1.1.2", "1.0.0", "1.3.3", "1.0.12", "1.0.2"] versions.sort(key=StrictVersion) ``` Gives you: ``` ['1.0.0', '1.0.2', '1.0.12', '1.1.2', '1.3.3'] ``` It can also handle versions with pre-relea...
sqlalchemy dynamic mapping
2,574,105
10
2010-04-04T10:03:19Z
2,575,016
24
2010-04-04T16:07:08Z
[ "python", "sqlalchemy" ]
I have the following problem: I have the class: ``` class Word(object): def __init__(self): self.id = None self.columns = {} def __str__(self): return "(%s, %s)" % (str(self.id), str(self.columns)) ``` self.columns is a dict which will hold (columnName:columnValue) values. The name ...
It seems that you can just use the attributes directly instead of using the `columns` `dict`. Consider the following setup: ``` from sqlalchemy import Table, Column, Integer, Unicode, MetaData, create_engine from sqlalchemy.orm import mapper, create_session class Word(object): pass wordColumns = ['english', 'ko...
How to use Django's filesizeformat
2,574,540
3
2010-04-04T13:40:59Z
2,574,550
7
2010-04-04T13:43:41Z
[ "python", "django" ]
I have a small app I'm working on where I'm trying to use Django's built in filesizeformat. Currently, the format looks like this: `{{ value|filesizeformat }}`. I understand I need to define this in my view.py file but, I can't seem to figure out how to do that. I've tried to use the syntax below: ``` def filesizeform...
`filesizeformat` is a **built-in** filter, you do not need to implement it yourself. You should provide the value into the template, for example: ``` {% for page in pages %} <li>page.name {{page.size|filesizeformat}}</li> {% endfor %} ``` Now when you render the template from the view provide a `pages` argument w...
Getting a default value on index out of range in Python
2,574,636
41
2010-04-04T14:10:17Z
2,574,650
48
2010-04-04T14:13:56Z
[ "python", "list", "syntax", "default-value" ]
``` a=['123','2',4] b=a[4] or 'sss' print b ``` I want to get a default value when the list index is out of range (here: `'sss'`). How can I do this?
In the Python spirit of "ask for forgiveness, not permission", here's one way: ``` try: b = a[4] except IndexError: b = 'sss' ```
Getting a default value on index out of range in Python
2,574,636
41
2010-04-04T14:10:17Z
2,574,659
37
2010-04-04T14:15:45Z
[ "python", "list", "syntax", "default-value" ]
``` a=['123','2',4] b=a[4] or 'sss' print b ``` I want to get a default value when the list index is out of range (here: `'sss'`). How can I do this?
In the non-Python spirit of "ask for permission, not forgiveness", here's another way: ``` b = a[4] if len(a) > 4 else 'sss' ```
Getting a default value on index out of range in Python
2,574,636
41
2010-04-04T14:10:17Z
15,138,904
8
2013-02-28T15:08:26Z
[ "python", "list", "syntax", "default-value" ]
``` a=['123','2',4] b=a[4] or 'sss' print b ``` I want to get a default value when the list index is out of range (here: `'sss'`). How can I do this?
You could create your own list-class: ``` class MyList(list): def get(self, index, default=None): return self[index] if len(self) > index else default ``` You can use it like this: ``` >>> l = MyList(['a', 'b', 'c']) >>> l.get(1) 'b' >>> l.get(9, 'no') 'no' ```
Getting a default value on index out of range in Python
2,574,636
41
2010-04-04T14:10:17Z
22,685,248
7
2014-03-27T10:47:00Z
[ "python", "list", "syntax", "default-value" ]
``` a=['123','2',4] b=a[4] or 'sss' print b ``` I want to get a default value when the list index is out of range (here: `'sss'`). How can I do this?
In the Python spirit of beautiful is better than ugly Code golf method, using slice and unpacking (not sure if this was valid 4 years ago, but it is in python 2.7 + 3.3) ``` b,=a[4:] or 'sss', ``` Nicer than a wrapper function or try-catch IMHO, but intimidating for beginners. Personally I find tuple unpacking to be...
python sax error "junk after document element"
2,574,894
6
2010-04-04T15:22:07Z
2,574,913
11
2010-04-04T15:28:25Z
[ "python", "sax" ]
I use python sax to parse xml file. The xml file is actually a combination of multiple xml files. It looks like as follows: ``` <row name="abc" age="40" body="blalalala..." creationdate="03/10/10" /> <row name="bcd" age="50" body="blalalala..." creationdate="03/10/09" /> ``` My python code is in the following. It sho...
``` xmldata = ''' <row name="abc" age="40" body="blalalala..." creationdate="03/10/10" /> <row name="bcd" age="50" body="blalalala..." creationdate="03/10/09" /> ''' ``` Add a wrapper tag around the data. I've used ElementTree since it's so simpler, but you'd be able to do the same on any parser: ``` from xml.etree i...
Simulating Key Press event using Python for Linux
2,575,528
11
2010-04-04T18:57:49Z
19,457,610
8
2013-10-18T19:27:00Z
[ "python", "linux", "key", "keypress", "simulate" ]
I am writing a script to automate running a particular model. When the model fails, it waits for a user input (Enter key). I can detect when the model has failed, but I am not able to use python (on linux) to simulate a key press event. Windows has the SendKeys library to do this but I was wondering if there is a simil...
Have a look at this <https://github.com/SavinaRoja/PyUserInput> its cross-platform control for mouse and keyboard in python Keyboard control works on X11(linux) and Windows systems. But no mac support(when i wrote this answer). ``` from pykeyboard import PyKeyboard k = PyKeyboard() # To Create an Alt+Tab combo k.pre...
What does printing an empty line do?
2,575,584
5
2010-04-04T19:22:44Z
2,575,593
10
2010-04-04T19:24:59Z
[ "python" ]
I know this question may well be the silliest question you've heard today, but to me it is a big question at this stage of my programming learning. Why is the second empty line needed in this Python code? What does that line do? ``` print 'Content-Type: text/plain' print '' print 'Hello, world!' ```
It prints an empty line, just as you have said. It will leave a blank line in the output. The print statement prints its arguments, and then a newline, so this prints just a newline. You could accomplish the same thing with just: ``` print ```
Why Python language does not have a writeln() method?
2,575,619
11
2010-04-04T19:33:58Z
2,575,631
17
2010-04-04T19:36:29Z
[ "python", "syntax", "history", "language-design" ]
If we need to write a new line to a file we have to code: ``` file_output.write('Fooo line \n') ``` Are there any reasons why Python does not have a `writeln()` method?
In Python 2, use: ``` print >>file_output, 'Fooo line ' ``` In Python 3, use: ``` print('Fooo line ', file=file_output) ```
Why Python language does not have a writeln() method?
2,575,619
11
2010-04-04T19:33:58Z
2,575,708
7
2010-04-04T20:02:33Z
[ "python", "syntax", "history", "language-design" ]
If we need to write a new line to a file we have to code: ``` file_output.write('Fooo line \n') ``` Are there any reasons why Python does not have a `writeln()` method?
It was omitted to provide a symmetric interface of the `file` methods and because a `writeln()` would make no sense: * `read()` matches `write()`: they both operate on raw data * `readlines()` matches `writelines()`: they both operate on lines including their EOLs * `readline()` is rarely used; an iterator does the sa...
What's an easy and fast way to put returned XML data into a dict?
2,575,672
2
2010-04-04T19:48:51Z
2,575,786
8
2010-04-04T20:29:56Z
[ "python", "xml", "dictionary", "xml-parsing" ]
I'm trying to take the data returned from: ``` http://ipinfodb.com/ip_query.php?ip=74.125.45.100&timezone=true ``` Into a dict in a fast and easy way. What's the best way to do this? Thanks.
Using `xml` from the standard Python library: ``` import xml.etree.ElementTree as xee contents='''\ <?xml version="1.0" encoding="UTF-8"?> <Response> <Ip>74.125.45.100</Ip> <Status>OK</Status> <CountryCode>US</CountryCode> <CountryName>United States</CountryName> <RegionCode>06</RegionCode> <RegionName>Cal...
Django url tag multiple parameters
2,575,737
4
2010-04-04T20:11:46Z
2,575,829
11
2010-04-04T20:47:44Z
[ "python", "django", "django-urls" ]
I have two similar codes. The first one works as expected. ``` urlpatterns = patterns('', (r'^(?P<n1>\d)/test/', test), (r'', test2), {% url testapp.views.test n1=5 %} ``` But adding the second parameter makes the result return empty string. ``` urlpatterns = patterns(''...
Try ``` {% url testapp.views.test n1=5,n2=2 %} ``` without the space between the arguments **Update:** As of [Django 1.9](https://docs.djangoproject.com/en/1.10/ref/templates/builtins/#url) (and maybe earlier) the correct way is to omit the comma and separate arguments using spaces: ``` {% url testapp.views.test n1...
Python lookup hostname from IP with 1 second timeout
2,575,760
33
2010-04-04T20:20:27Z
2,575,779
49
2010-04-04T20:28:02Z
[ "python", "dns", "hostname", "nameservers" ]
How can I look up a hostname given an IP address? Furthermore, how can I specify a timeout in case no such reverse DNS entry exists? Trying to keep things as fast as possible. Or is there a better way? Thank you!
``` >>> import socket >>> socket.gethostbyaddr("69.59.196.211") ('stackoverflow.com', ['211.196.59.69.in-addr.arpa'], ['69.59.196.211']) ``` For implementing the timeout on the function, [this stackoverflow thread](http://stackoverflow.com/questions/492519/timeout-on-a-python-function-call) has answers on that.
Python lookup hostname from IP with 1 second timeout
2,575,760
33
2010-04-04T20:20:27Z
2,575,785
9
2010-04-04T20:29:55Z
[ "python", "dns", "hostname", "nameservers" ]
How can I look up a hostname given an IP address? Furthermore, how can I specify a timeout in case no such reverse DNS entry exists? Trying to keep things as fast as possible. Or is there a better way? Thank you!
What you're trying to accomplish is called Reverse DNS lookup. ``` socket.gethostbyaddr("IP") # => (hostname, alias-list, IP) ``` <http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr> However, for the timeout part I have read about people running into problems with this. I would ...
Using Python tuples as vectors
2,576,296
4
2010-04-04T23:39:43Z
2,576,311
9
2010-04-04T23:45:36Z
[ "python", "tuples" ]
I need to represent immutable vectors in Python ("vectors" as in linear algebra, not as in programming). The tuple seems like an obvious choice. The trouble is when I need to implement things like addition and scalar multiplication. If `a` and `b` are vectors, and `c` is a number, the best I can think of is this: ```...
[NumPy](http://numpy.scipy.org/) supports various algebraic operations with its arrays.
Using Python tuples as vectors
2,576,296
4
2010-04-04T23:39:43Z
2,576,404
9
2010-04-05T00:20:54Z
[ "python", "tuples" ]
I need to represent immutable vectors in Python ("vectors" as in linear algebra, not as in programming). The tuple seems like an obvious choice. The trouble is when I need to implement things like addition and scalar multiplication. If `a` and `b` are vectors, and `c` is a number, the best I can think of is this: ```...
Immutable types are pretty rare in Python and third-party extensions thereof; the OP rightly claims "there are enough uses for linear algebra that it doesn't seem likely I have to roll my own" -- but all the existing types I know that do linear algebra are **mutable**! So, as the OP is adamant on immutability, there *i...
Using Python tuples as vectors
2,576,296
4
2010-04-04T23:39:43Z
2,577,527
7
2010-04-05T08:34:52Z
[ "python", "tuples" ]
I need to represent immutable vectors in Python ("vectors" as in linear algebra, not as in programming). The tuple seems like an obvious choice. The trouble is when I need to implement things like addition and scalar multiplication. If `a` and `b` are vectors, and `c` is a number, the best I can think of is this: ```...
By inheriting from tuple, you can make a nice Vector class pretty easily. Here's enough code to provide addition of vectors, and multiplication of a vector by a scalar. It gives you arbitrary length vectors, and can work with complex numbers, ints, or floats. ``` class Vector(tuple): def __add__(self, a): ...
Using Python How can I read the bits in a byte?
2,576,712
20
2010-04-05T02:57:27Z
2,576,713
14
2010-04-05T02:58:18Z
[ "python", "byte", "bits" ]
I have a file where the first byte contains encoded information. In Matlab I can read the byte bit by bit with var=fread(file,8, 'ubit1') then retrieve each bit by var(1),var(2), etc. Is there any equivalent bit reader in python?
The smallest unit you'll be able to work with is a byte. To work at the bit level you need to use [bitwise operators](http://wiki.python.org/moin/BitwiseOperators). ``` x = 3 #Check if the 1st bit is set: x&1 != 0 #Returns True #Check if the 2nd bit is set: x&2 != 0 #Returns True #Check if the 3rd bit is set: x&4 !=...
Using Python How can I read the bits in a byte?
2,576,712
20
2010-04-05T02:57:27Z
2,576,790
10
2010-04-05T03:30:10Z
[ "python", "byte", "bits" ]
I have a file where the first byte contains encoded information. In Matlab I can read the byte bit by bit with var=fread(file,8, 'ubit1') then retrieve each bit by var(1),var(2), etc. Is there any equivalent bit reader in python?
You won't be able to read each bit one by one - you have to read it byte by byte. You can easily extract the bits out, though: ``` f = open("myfile", 'rb') # read one byte byte = f.read(1) # convert the byte to an integer representation byte = ord(byte) # now convert to string of 1s and 0s byte = bin(byte)[2:].rjust(8...
Using Python How can I read the bits in a byte?
2,576,712
20
2010-04-05T02:57:27Z
2,577,487
18
2010-04-05T08:22:42Z
[ "python", "byte", "bits" ]
I have a file where the first byte contains encoded information. In Matlab I can read the byte bit by bit with var=fread(file,8, 'ubit1') then retrieve each bit by var(1),var(2), etc. Is there any equivalent bit reader in python?
Read the bits from a file, low bits first. ``` def bits(f): bytes = (ord(b) for b in f.read()) for b in bytes: for i in xrange(8): yield (b >> i) & 1 for b in bits(open('binary-file.bin', 'r')): print b ```
Python's preferred comparison operators
2,576,826
23
2010-04-05T03:48:18Z
2,576,847
40
2010-04-05T03:54:25Z
[ "python", "comparison" ]
Is it preferred to do: ``` if x is y: return True ``` or ``` if x == y return True ``` Same thing for "is not"
`x is y` is different than `x == y`. `x is y` is true if and only if `id(x) == id(y)` -- that is, `x` and `y` have to be one and the same object (with the same `id`s). For all built-in Python objects (like strings, lists, dicts, functions, etc.), if `x is y`, then `x == y` is also True. However, this is not guarantee...
Python's preferred comparison operators
2,576,826
23
2010-04-05T03:48:18Z
2,577,494
15
2010-04-05T08:25:02Z
[ "python", "comparison" ]
Is it preferred to do: ``` if x is y: return True ``` or ``` if x == y return True ``` Same thing for "is not"
`x is y` compares the identities of the two objects, and is asking *'are `x` and `y` different names for the same object?'* It is equivalent to `id(x) == id(y)`. `x == y` uses the equality operator and asks the looser question *'are `x` and `y` equal?'* For user defined types it is equivalent to `x.__eq__(y)`. The `_...
Python's preferred comparison operators
2,576,826
23
2010-04-05T03:48:18Z
2,577,589
9
2010-04-05T08:55:52Z
[ "python", "comparison" ]
Is it preferred to do: ``` if x is y: return True ``` or ``` if x == y return True ``` Same thing for "is not"
* **`==`** and **`!=`** are object *value* comparison operators * **`is`** and **`is not`** are object *identity* comparison operators as others have already said, **`is`** (and **`is not`**) are only when you actually *care* that a pair of variables are referring to exactly the same object. in most cases, you really ...
Python newbie: trying to create a script that opens a file and replaces words
2,577,671
4
2010-04-05T09:25:10Z
2,577,694
7
2010-04-05T09:31:28Z
[ "python", "file-manipulation" ]
im trying to create a script that opens a file and replace every 'hola' with 'hello'. ``` f=open("kk.txt","w") for line in f: if "hola" in line: line=line.replace('hola','hello') f.close() ``` But im getting this error: > Traceback (most recent call last): > File "prueba.py", line 3, in > for line in f: ...
``` open('test.txt', 'w').write(open('test.txt', 'r').read().replace('hola', 'hello')) ``` Or if you want to properly close the file: ``` with open('test.txt', 'r') as src: src_text = src.read() with open('test.txt', 'w') as dst: dst.write(src_text.replace('hola', 'hello')) ```
Best DataMining Database
2,577,967
14
2010-04-05T10:59:47Z
2,577,979
12
2010-04-05T11:04:21Z
[ "python", "database", "nosql", "data-mining" ]
I am an occasional Python programer who only have worked so far with MYSQL or SQLITE databases. I am the computer person for everything in a small company and I have been started a new project where I think it is about time to try new databases. Sales department makes a CSV dump every week and I need to make a small s...
You probably do need a full relational DBMS, if not right now, very soon. If you start now while your problems and data are simple and straightforward then when they become complex and difficult you will have plenty of experience with at least one DBMS to help you. You probably don't need MySQL on all desktops, you mig...
Best DataMining Database
2,577,967
14
2010-04-05T10:59:47Z
2,582,847
15
2010-04-06T05:33:43Z
[ "python", "database", "nosql", "data-mining" ]
I am an occasional Python programer who only have worked so far with MYSQL or SQLITE databases. I am the computer person for everything in a small company and I have been started a new project where I think it is about time to try new databases. Sales department makes a CSV dump every week and I need to make a small s...
## Quick Summary * You need enough memory(RAM) to solve your problem efficiently. I think you should upgrade memory?? When reading the excellent [High Scalability](http://highscalability.com/) Blog you will notice that for big sites to solve there problem efficiently they store the complete problem set in memory. * Yo...
Python 2.5.2: trying to open files recursively
2,578,022
6
2010-04-05T11:14:21Z
2,578,059
10
2010-04-05T11:21:02Z
[ "python" ]
The script below should open all the files inside the folder 'pruebaba' recursively but I get this error: > Traceback (most recent call last): > File > "/home/tirengarfio/Desktop/prueba.py", > line 8, in > f = open(file,'r') IOError: [Errno 21] Is a directory This is the hierarchy: ``` pruebaba folder1 folde...
Use [`os.walk`](http://docs.python.org/library/os#os.walk). It recursively walks into directory and subdirectories, and already gives you separate variables for files and directories. ``` import re import os from __future__ import with_statement PATH = "/home/tirengarfio/Desktop/pruebaba" for path, dirs, files in os...
Why is the destructor called when the CPython garbage collector is disabled?
2,578,098
6
2010-04-05T11:28:14Z
2,578,109
9
2010-04-05T11:31:07Z
[ "python", "garbage-collection", "cpython" ]
I'm trying to understand the internals of the CPython garbage collector, specifically when the destructor is called. So far, the behavior is intuitive, but the following case trips me up: 1. Disable the GC. 2. Create an object, then remove a reference to it. 3. The object is destroyed and the **\_\_*del*\_\_** method ...
Python has both *reference counting* garbage collection and *cyclic* garbage collection, and it's the latter that the `gc` module controls. Reference counting can't be disabled, and hence still happens when the cyclic garbage collector is switched off. Since there are no references left to your object after `ref = Non...
PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django
2,578,540
20
2010-04-05T13:18:44Z
2,578,635
29
2010-04-05T13:38:37Z
[ "python", "django", "cakephp", "web-frameworks", "yii" ]
I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Although ...
This is a very subjective question but personally I'd recommend Django. Python is a very nice language to use and the Django framework is small, easy to use, well documented and also has a pretty active community. This choice was made partly because of my dislike for PHP though, so take the recommendation with a pinch...
PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django
2,578,540
20
2010-04-05T13:18:44Z
2,578,670
26
2010-04-05T13:44:39Z
[ "python", "django", "cakephp", "web-frameworks", "yii" ]
I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Although ...
Most of the frameworks out there nowadays are fast enough to serve whatever needs you will have. It really depends on in which environment you feel most comfortable. Though there are nuances here and there, MVC frameworks share a lot of the same principles, so whichever you choose to use is really a matter of which you...
PHP Frameworks (CodeIgniter, Yii, CakePHP) vs. Django
2,578,540
20
2010-04-05T13:18:44Z
2,579,251
13
2010-04-05T15:38:18Z
[ "python", "django", "cakephp", "web-frameworks", "yii" ]
I have to develop a site which has to accomodate around 2000 users a day and speed is a criterion for it. Moreover, the site is a user oriented one where the user will be able to log in and check his profile, register for specific events he/she wants to participate in. The site is to be hosted on a VPS server.Although ...
I've worked with CakePHP and Django and I really recommend Django. I don't know too much about CodeIgniter, but I remember ruling it out when I was evaluating frameworks myself about a year ago. CakePHP seemed much more developed at the time. First of all, the Django community is much bigger and has spent a lot of tim...
How can I plot NaN values as a special color with imshow in matplotlib?
2,578,752
45
2010-04-05T14:03:56Z
2,578,873
45
2010-04-05T14:30:10Z
[ "python", "matplotlib", null ]
I am trying to use imshow in matplotlib to plot data as a heatmap, but some of the values are NaNs. I'd like the NaNs to be rendered as a special color not found in the colormap. example: ``` import numpy as np import matplotlib.pyplot as plt f = plt.figure() ax = f.add_subplot(111) a = np.arange(25).reshape((5,5)).a...
Hrm, it appears I can use a masked array to do this: ``` masked_array = np.ma.array (a, mask=np.isnan(a)) cmap = matplotlib.cm.jet cmap.set_bad('white',1.) ax.imshow(masked_array, interpolation='nearest', cmap=cmap) ``` This should suffice, though I'm still open to suggestions. :]
What is the best way to convert a zope DateTime object into Python datetime object?
2,578,770
8
2010-04-05T14:07:42Z
2,578,836
7
2010-04-05T14:20:21Z
[ "python", "zope" ]
I need to convert a zope 2 DateTime object into a Python datetime object. What is the best way to do that? Thanks, Erika
``` modernthingy = datetime.datetime.fromtimestamp(zopethingy.timeTime()) ``` The `datetime` instance is timezone-naive; if you need to support timezones (as Zope2's `DateTime` does), I recommend third-party extension package [pytz](http://pytz.sourceforge.net/).
What is the best way to convert a zope DateTime object into Python datetime object?
2,578,770
8
2010-04-05T14:07:42Z
2,579,381
10
2010-04-05T15:59:40Z
[ "python", "zope" ]
I need to convert a zope 2 DateTime object into a Python datetime object. What is the best way to do that? Thanks, Erika
Newer DateTime implementations (2.11 and up) have a `asdatetime` method that returns a python datetime.datetime instance: ``` modernthingy = zopethingy.asdatetime() ```
How to Convert DD to DMS in Python
2,579,535
8
2010-04-05T16:32:40Z
2,580,236
10
2010-04-05T18:32:02Z
[ "python" ]
How Do you Convert Decimal Degrees to Degrees Minutes Secands In Python? Is there a Formula already written?
This is exactly what `divmod` was invented for: ``` >>> def decdeg2dms(dd): ... mnt,sec = divmod(dd*3600,60) ... deg,mnt = divmod(mnt,60) ... return deg,mnt,sec >>> dd = 45 + 30.0/60 + 1.0/3600 >>> print dd 45.5002777778 >>> decdeg2dms(dd) (45.0, 30.0, 1.0) ```
Do you use the get/set pattern (in Python)?
2,579,840
49
2010-04-05T17:26:20Z
2,579,864
34
2010-04-05T17:31:13Z
[ "python", "getter-setter" ]
Using get/set seems to be a common practice in Java (for various reasons), but I hardly see Python code that uses this. Why do you use or avoid get/set methods in Python?
Cool link: [Python is not Java](http://dirtsimple.org/2004/12/python-is-not-java.html) :) > In Java, you have to use getters and setters because using public fields gives you no opportunity to go back and change your mind later to using getters and setters. So in Java, you might as well get the chore out of the way up...
Do you use the get/set pattern (in Python)?
2,579,840
49
2010-04-05T17:26:20Z
2,579,867
11
2010-04-05T17:31:27Z
[ "python", "getter-setter" ]
Using get/set seems to be a common practice in Java (for various reasons), but I hardly see Python code that uses this. Why do you use or avoid get/set methods in Python?
No, it's unpythonic. The generally accepted way is to use normal data attribute and replace the ones that need more complex get/set logic with properties.
Do you use the get/set pattern (in Python)?
2,579,840
49
2010-04-05T17:26:20Z
2,579,994
17
2010-04-05T17:54:29Z
[ "python", "getter-setter" ]
Using get/set seems to be a common practice in Java (for various reasons), but I hardly see Python code that uses this. Why do you use or avoid get/set methods in Python?
Here is what Guido van Rossum says about that in [*Masterminds of Programming*](http://rads.stackoverflow.com/amzn/click/0596515170) > **What do you mean by "fighting the language"?** > > **Guido:** That usually means that they're > trying to continue their habits that > worked well with a different language. > > [......
Do you use the get/set pattern (in Python)?
2,579,840
49
2010-04-05T17:26:20Z
2,580,114
72
2010-04-05T18:16:52Z
[ "python", "getter-setter" ]
Using get/set seems to be a common practice in Java (for various reasons), but I hardly see Python code that uses this. Why do you use or avoid get/set methods in Python?
In python, you can just access the attribute directly because it is public: ``` class MyClass(object): def __init__(self): self.my_attribute = 0 my_object = MyClass() my_object.my_attribute = 1 # etc. ``` If you want to do something on access or mutation of the attribute, you can use [properties](http...
How do "and" and "or" work when combined in one statement?
2,579,959
3
2010-04-05T17:47:39Z
2,579,972
7
2010-04-05T17:50:25Z
[ "python", "boolean-logic", "if-statement" ]
For some reason this function confused me: ``` def protocol(port): return port == "443" and "https://" or "http://" ``` Can somebody explain the order of what's happening behind the scenes to make this work the way it does. I understood it as this until I tried it: Either A) ``` def protocol(port): if port...
`and` returns the right operand if the left is true. `or` returns the right operand if the left is false. Otherwise they both return the left operand. They are said to **coalesce**.
How do "and" and "or" work when combined in one statement?
2,579,959
3
2010-04-05T17:47:39Z
2,579,973
20
2010-04-05T17:50:41Z
[ "python", "boolean-logic", "if-statement" ]
For some reason this function confused me: ``` def protocol(port): return port == "443" and "https://" or "http://" ``` Can somebody explain the order of what's happening behind the scenes to make this work the way it does. I understood it as this until I tried it: Either A) ``` def protocol(port): if port...
It's an old-ish idiom; inserting parentheses to show priority, ``` (port == "443" and "https://") or "http://" ``` `x and y` returns `y` if `x` is truish, `x` if `x` is falsish; `a or b`, vice versa, returns `a` if it's truish, otherwise `b`. So if `port == "443"` is true, this returns the RHS of the `and`, i.e., `"...
Does Python support short-circuiting?
2,580,136
166
2010-04-05T18:19:55Z
2,580,142
150
2010-04-05T18:20:26Z
[ "python", "short-circuiting" ]
Does Python support short-circuiting in boolean expressions?
Yep, both `and` and `or` operators short-circuit -- see [the docs](http://docs.python.org/library/stdtypes.html?highlight=short%20circuit#boolean-operations-and-or-not).
Does Python support short-circuiting?
2,580,136
166
2010-04-05T18:19:55Z
14,892,812
86
2013-02-15T10:34:36Z
[ "python", "short-circuiting" ]
Does Python support short-circuiting in boolean expressions?
### Short-circuiting behavior in operator `and`, `or`: One can observe the [Python's short-circuiting behavior](http://cis.poly.edu/cs1114/pyLecturettes/short-circuit-eval.html) of `and`, `or` operators in my following example: ``` >>> def fun(): ... print "Yes" ... return 1 ... >>> fun() Yes 1 >>> 1 or fun(...
Does Python support short-circuiting?
2,580,136
166
2010-04-05T18:19:55Z
17,888,874
30
2013-07-26T18:52:32Z
[ "python", "short-circuiting" ]
Does Python support short-circuiting in boolean expressions?
Yes. Try the following in your python interpreter: and ``` >>>False and 3/0 False >>>True and 3/0 ZeroDivisionError: integer division or modulo by zero ``` or ``` >>>True or 3/0 True >>>False or 3/0 ZeroDivisionError: integer division or modulo by zero ```
Database on the fly with scripting languages
2,580,497
19
2010-04-05T19:10:17Z
2,580,543
55
2010-04-05T19:15:58Z
[ "python", "sql", "database", "sqlite3", "sqlalchemy" ]
I have a set of .csv files that I want to process. It would be far easier to process it with SQL queries. I wonder if there is some way to load a .csv file and use SQL language to look into it with a scripting language like python or ruby. Loading it with something similar to ActiveRecord would be awesome. The problem...
There's [`sqlite3`](http://docs.python.org/library/sqlite3), included into python. With it you can create a database (**on memory**) and add rows to it, and perform SQL queries. If you want neat ActiveRecord-like functionality you should add an external ORM, like [sqlalchemy](http://sqlalchemy.org). That's a separate ...
Disable autocomplete on textfield in Django?
2,580,955
11
2010-04-05T20:23:48Z
2,581,040
19
2010-04-05T20:39:30Z
[ "python", "django", "forms", "autocomplete" ]
Does anyone know how you can turn off autocompletion on a textfield in Django? For example, a form that I generate from my model has an input field for a credit card number. It is bad practice to leave autocompletion on. When making the form by hand, I'd add a autocomplete="off" statement, but how do you do it in Djan...
In your form, specify the widget you want to use for the field, and add an `attrs` dictionary on that widget. For example (straight from the [django documentation](http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs)): ``` class CommentForm(forms.Form): name = forms.CharField( ...
Disable autocomplete on textfield in Django?
2,580,955
11
2010-04-05T20:23:48Z
3,672,334
17
2010-09-08T22:19:32Z
[ "python", "django", "forms", "autocomplete" ]
Does anyone know how you can turn off autocompletion on a textfield in Django? For example, a form that I generate from my model has an input field for a credit card number. It is bad practice to leave autocompletion on. When making the form by hand, I'd add a autocomplete="off" statement, but how do you do it in Djan...
Add the autocomplete="off" to the form tag, so you don't have to change the django.form instance. `<form action="." method="post" autocomplete="off"> {{ form }} </form>`
Django TestCase testing order
2,581,005
16
2010-04-05T20:34:26Z
2,581,056
9
2010-04-05T20:43:40Z
[ "python", "django", "unit-testing" ]
If there are several methods in the test class, I found that the order to execute is alphabetical. But I want to customize the order of execution. How to define the execution order? For example: testTestA will be loaded first than testTestB. ``` class Test(TestCase): def setUp(self): ... def testTest...
As far as I know, there is no way to order tests other than rename them. Could you explain why you need to run test cases in the specific order? In unit testing it usually considered as bad practice since it means that your cases are not independent.
Django TestCase testing order
2,581,005
16
2010-04-05T20:34:26Z
2,581,160
33
2010-04-05T21:01:29Z
[ "python", "django", "unit-testing" ]
If there are several methods in the test class, I found that the order to execute is alphabetical. But I want to customize the order of execution. How to define the execution order? For example: testTestA will be loaded first than testTestB. ``` class Test(TestCase): def setUp(self): ... def testTest...
A tenet of unit-testing is that each test should be independent of all others. If in your case the code in testTestA must come before testTestB, then you could combine both into one test: ``` def testTestA_and_TestB(self): # test code from testTestA ... # test code from testTestB ``` or, perhaps better wo...
Can Cython compile to an EXE?
2,581,784
37
2010-04-05T23:34:34Z
2,581,826
28
2010-04-05T23:47:51Z
[ "python", "compilation", "cython" ]
I know what Cythons purpose is. It's to write compilable C extensions in a Python-like language in order to produce speedups in your code. What I would like to know (and can't seem to find using my google-fu) is if Cython can somehow compile into an executable format since it already seems to break python code down int...
In principal it appears to be possible to do something like what you want, according to the [Embedding Pyrex HOWTO](http://www.freenet.org.nz/python/embeddingpyrex/). (Pyrex is effectively a previous generation of Cython.) Hmm... that name suggests a better search than I first tried: "embedding cython" leads to [this ...
Can Cython compile to an EXE?
2,581,784
37
2010-04-05T23:34:34Z
2,743,448
31
2010-04-30T09:12:40Z
[ "python", "compilation", "cython" ]
I know what Cythons purpose is. It's to write compilable C extensions in a Python-like language in order to produce speedups in your code. What I would like to know (and can't seem to find using my google-fu) is if Cython can somehow compile into an executable format since it already seems to break python code down int...
[Here's the wiki page on embedding cython](https://github.com/cython/cython/wiki/EmbeddingCython) Assuming you installed python to `C:\Python31` and you want to use Microsoft Compiler. `smalltest1.py` - is the file you want to compile. `test.exe` - name of the executable. You need to set the environmental variables...
Python subprocess: callback when cmd exits
2,581,817
32
2010-04-05T23:45:06Z
2,581,943
33
2010-04-06T00:27:04Z
[ "python", "callback", "subprocess", "exit" ]
I'm currently launching a programme using `subprocess.Popen(cmd, shell=TRUE)` I'm fairly new to Python, but it 'feels' like there ought to be some api that lets me do something similar to: ``` subprocess.Popen(cmd, shell=TRUE, postexec_fn=function_to_call_on_exit) ``` I am doing this so that `function_to_call_on_ex...
You're right - there is no nice API for this. You're also right on your second point - it's trivially easy to design a function that does this for you using threading. ``` import threading import subprocess def popenAndCall(onExit, popenArgs): """ Runs the given args in a subprocess.Popen, and then calls the ...
Python beginner confused by a complex line of code
2,581,965
4
2010-04-06T00:34:51Z
2,582,004
11
2010-04-06T00:44:55Z
[ "python", "list-comprehension" ]
I understand the gist of the code, that it forms permutations; however, I was wondering if someone could explain exactly what is going on in the return statement. ``` def perm(l): sz = len(l) print (l) if sz <= 1: print ('sz <= 1') return [l] return [p[:i]+[l[0]]+p[i:] for i in range(sz...
This `return` is returning a list comprehension whose items are made by inserting the first item of `l` into each position of `p`, from the first to the last -- `p` in turn is a list of lists, obtained by a recursive call to `perm` which excludes the first item of `l` (and thus permutes all *other* items in all possibl...
finding and replacing elements in a list (python)
2,582,138
88
2010-04-06T01:30:18Z
2,582,163
216
2010-04-06T01:37:11Z
[ "python", "list", "replace" ]
I have to search through a list and replace all occurrences of one element with another. So far my attempts in code are getting me nowhere, what is the best way to do this? For example, suppose my list has the following integers ``` >>> a = [1,2,3,4,5,1,2,3,4,5,1] ``` and I need to replace all occurrences of the num...
Try using a [list comprehension](http://docs.python.org/tutorial/datastructures.html#list-comprehensions) and the [ternary operator](http://en.wikipedia.org/wiki/Ternary_operation#Python). ``` >>> a=[1,2,3,1,3,2,1,1] >>> [4 if x==1 else x for x in a] [4, 2, 3, 4, 3, 2, 4, 4] ```
finding and replacing elements in a list (python)
2,582,138
88
2010-04-06T01:30:18Z
2,582,183
98
2010-04-06T01:41:33Z
[ "python", "list", "replace" ]
I have to search through a list and replace all occurrences of one element with another. So far my attempts in code are getting me nowhere, what is the best way to do this? For example, suppose my list has the following integers ``` >>> a = [1,2,3,4,5,1,2,3,4,5,1] ``` and I need to replace all occurrences of the num...
``` >>> a=[1,2,3,4,5,1,2,3,4,5,1] >>> for n,i in enumerate(a): ... if i==1: ... a[n]=10 ... >>> a [10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10] ```
finding and replacing elements in a list (python)
2,582,138
88
2010-04-06T01:30:18Z
2,582,567
13
2010-04-06T03:57:54Z
[ "python", "list", "replace" ]
I have to search through a list and replace all occurrences of one element with another. So far my attempts in code are getting me nowhere, what is the best way to do this? For example, suppose my list has the following integers ``` >>> a = [1,2,3,4,5,1,2,3,4,5,1] ``` and I need to replace all occurrences of the num...
List comprehension works well--and looping through with enumerate can save you some memory (b/c the operation's essentially be doing in place). There's also functional programming...see usage of [map](http://docs.python.org/library/functions.html#map): ``` >>> a = [1,2,3,2,3,4,3,5,6,6,5,4,5,4,3,4,3,2,1] >>> m...
Python Mechanize select a form with no name
2,582,580
27
2010-04-06T04:01:24Z
2,582,592
47
2010-04-06T04:06:03Z
[ "python", "html", "forms", "mechanize" ]
I am attempting to have mechanize select a form from a page, but the form in question has no "name" attribute in the html. What should I do? when I try to use ``` br.select_form(name = "") ``` I get errors that no form is declared with that name, and the function requires a name input. There is only one form on the p...
Try: ``` br.select_form(nr=0) ``` to select the first form In Mechanize [source](https://github.com/jjlee/mechanize/blob/b1d786906946f0193051920a7c716b339bd7bf95/mechanize/_mechanize.py#L462), ``` def select_form(self, name=None, predicate=None, <b>nr=None</b>): """ ... nr, if supplied, is the sequence ...
Tuple unpacking: dummy variable vs index
2,582,803
13
2010-04-06T05:24:56Z
2,582,826
10
2010-04-06T05:29:34Z
[ "coding-style", "python" ]
What is the usual/clearest way to write this in Python? ``` value, _ = func_returning_a_tuple() ``` or: ``` value = func_returning_a_tuple()[0] ```
`value = func_returning_a_tuple()[0]` seems clearer and also can be generalized. What if the function was returning a tuple with more than 2 values? What if the program logic is interested in the 4th element of an umpteen tuple? What if the size of the returned tuple varies? None of these questions affects the su...
Tuple unpacking: dummy variable vs index
2,582,803
13
2010-04-06T05:24:56Z
2,583,088
10
2010-04-06T06:38:59Z
[ "coding-style", "python" ]
What is the usual/clearest way to write this in Python? ``` value, _ = func_returning_a_tuple() ``` or: ``` value = func_returning_a_tuple()[0] ```
If you'd appreciate a handy way to do this in python3.x, check out the python enhancement proposal (PEP) 3132 on this [page of What's New](http://docs.python.org/py3k/whatsnew/index.html) in Python: Extended Iterable Unpacking. You can now write things like `a, b, *rest = some_sequence`. And even `*rest, a = stuff`. T...