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 |
|---|---|---|---|---|---|---|---|---|---|
Hashing arrays in Python | 7,027,199 | 18 | 2011-08-11T13:59:48Z | 7,027,308 | 21 | 2011-08-11T14:06:21Z | [
"python",
"arrays",
"hash"
] | Is it possible to hash `lists`?
For example, I know that hashes of tuples are possible:
```
>>> hash((1,2,3,4,5,6))
-319527650
```
But is it possible to hash a `list`?
```
>>> hash([1,2,3,4,5,6])
hash_value
```
**Possible Solution:**
[Very in depth explanation to the hashing of lists, here.](http://mail.python.or... | Just try it:
```
>>> hash((1,2,3))
2528502973977326415
>>> hash([1,2,3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> hash(frozenset((1,2,3)))
-7699079583225461316
>>> hash(set((1,2,3)))
Traceback (most recent call last):
File "<stdin>", line 1, in <... |
Hashing arrays in Python | 7,027,199 | 18 | 2011-08-11T13:59:48Z | 13,621,192 | 8 | 2012-11-29T07:56:53Z | [
"python",
"arrays",
"hash"
] | Is it possible to hash `lists`?
For example, I know that hashes of tuples are possible:
```
>>> hash((1,2,3,4,5,6))
-319527650
```
But is it possible to hash a `list`?
```
>>> hash([1,2,3,4,5,6])
hash_value
```
**Possible Solution:**
[Very in depth explanation to the hashing of lists, here.](http://mail.python.or... | If you really need to use a list as a dictionary key, try converting it to a string first.
`my_list = str(my_list)` |
Getting corresponding module from function | 7,027,848 | 8 | 2011-08-11T14:41:01Z | 7,027,899 | 8 | 2011-08-11T14:44:17Z | [
"python"
] | I want to modify a module xyz and its functions like that:
```
def modify(fun):
modulename = fun.__module__ # this is string. ok, but not enough
import xyz
modify(xzy.test)
```
My problem is how to access the namespace of `xzy` inside `modify`. Sometimes
```
globals()[fun.__module__]
```
works. But then I get ... | You want to get the module object from its name? Look it up in the `sys.modules` dictionary that contains all currently loaded modules:
```
import sys
def modify(func):
module = sys.modules[func.__module__]
``` |
Django ORM queries fail to select new objects | 7,028,091 | 5 | 2011-08-11T14:55:44Z | 7,028,362 | 9 | 2011-08-11T15:12:30Z | [
"python",
"mysql",
"django",
"orm"
] | **Setup:**
* Python script **A** inserts data to a DB every round 15 minutes
* Python script **B** queries for the last 5 entries every few minutes
Both use django's ORM, same MySQL DB and the same DB user account (same `settings.py` file)
**The Problem:**
**B** is able to fetch only entries inserted before it was... | If you're reusing same Manager object, you have to keep in mind [it's caching](https://docs.djangoproject.com/en/1.3/topics/db/queries/#caching-and-querysets). To deal with that you have to manually update.
This will return same results in every iteration:
```
while True:
same_every_time = AClass.objects.all().ord... |
How to parse multiple dates from a block of text in Python (or another language) | 7,028,689 | 15 | 2011-08-11T15:33:48Z | 7,029,553 | 14 | 2011-08-11T16:32:10Z | [
"python",
"parsing",
"python-dateutil"
] | I have a string that has several date values in it, and I want to parse them all out. The string is natural language, so the best thing I've found so far is [dateutil](http://labix.org/python-dateutil).
Unfortunately, if a string has multiple date values in it, dateutil throws an error:
```
>>> s = "I like peas on 20... | Looking at it, the least hacky way would be to modify dateutil [parser](http://bazaar.launchpad.net/~niemeyer/dateutil/trunk/view/head:/dateutil/parser.py) to have a fuzzy-multiple option.
`parser._parse` takes your string, tokenizes it with `_timelex` and then compares the tokens with data defined in `parserinfo`.
[... |
Why a procedure is so much faster when put into a function? | 7,028,770 | 8 | 2011-08-11T15:39:14Z | 7,028,818 | 14 | 2011-08-11T15:42:41Z | [
"python",
"performance",
"local-variables"
] | Here is what I did, I created 2 procedures, one in a function and one in the python file itself. The one on the python file itself run almost 2 times slower even if it's exactly the same. WHY ?
Bellow is an example with 2 procedures that are just loops on P element
I have the following python file :
```
from time im... | The only significant difference is that the version in the function is only updating the local variable for that function, whereas the version not in a function is updating a *global* variable `k`.
As mentioned [here](http://wiki.python.org/moin/PythonSpeed/PerformanceTips#Local_Variables):
> The final speedup availa... |
List append in loop question | 7,028,842 | 3 | 2011-08-11T15:44:16Z | 7,028,887 | 8 | 2011-08-11T15:46:36Z | [
"python",
"python-3.x"
] | How can i modify this code to make 3 lists with 5 elements in each instead of as it is now; 3 lists with 5/10/15 elements?
```
import random
y = []
def autoSolve():
for i in range(5):
z = random.randrange(1, 10)
y.append(z)
print(y, end="")
for i in range(3):
print("number", i + 1,)
... | Move `y = []` into the autoSolve method, so that it's reset on every call.
```
def autoSolve():
y = []
for i in range(5):
z = random.randrange(1, 10)
y.append(z)
print(y, end="")
``` |
What is the Problem with iteritems() in OrderedDict() in python? | 7,029,264 | 2 | 2011-08-11T16:12:08Z | 7,029,309 | 7 | 2011-08-11T16:14:48Z | [
"python",
"python-2.6"
] | Here is my OrderedDict dictionary:
```
>>> dic = OrderedDict([('16-17,1,5,BUY,BUY,-6,9', 10), ('19-20,1,1,BUY,BUY,-1,1',1)])
>>> dic
OrderedDict([('16-17,1,5,BUY,BUY,-6,9', 10), ('19-20,1,1,BUY,BUY,-1,1', 11)])
>>> for k,v in dic.iteritems():
... print k
... k1 = k.split(',')
... print k1
... ... | Because `append` returns nothing.
`print` prints the return value of `k1.append(v)`, but there is no return value from `k1.append(v)` |
Differences between numpy.random and random.random in Python | 7,029,993 | 38 | 2011-08-11T17:05:54Z | 7,030,595 | 60 | 2011-08-11T17:56:07Z | [
"python",
"random",
"random-seed"
] | I have a big script in Python. I inspired myself in other people's code so I ended up using the `numpy.random` module for some things (for example for creating an array of random numbers taken from a binomial distribution) and in other places I use the module `random.random`.
Can someone please tell me the major diffe... | You have made many correct observations already!
Unless you'd like to seed both of the random generators, it's probably simpler in the long run to choose one generator or the other.
For `numpy.random.seed()`, the main difficulty is that it is not thread-safe - that is, it's not safe to use if you have [many different... |
Python: Is it reasonable to use None as a dictionary key? | 7,030,029 | 27 | 2011-08-11T17:09:49Z | 7,030,068 | 25 | 2011-08-11T17:12:38Z | [
"python",
"dictionary",
"key"
] | None seems to work as a dictionary key, but I am wondering if that will just lead to trouble later. For example, this works:
```
>>> x={'a':1, 'b':2, None:3}
>>> x
{'a': 1, None: 3, 'b': 2}
>>> x[None]
3
```
The actual data I am working with is educational standards. Every standard is associated with a content area. ... | Any hashable value is a valid Python Dictionary Key. For this reason, None is a perfectly valid candidate. There's no confusion when looking for non-existent keys - the presence of None as a key would not affect the ability to check for whether another key was present. Ex:
```
>>> d = {1: 'a', 2: 'b', None: 'c'}
>>> 1... |
Setting an axis in matplotlib | 7,030,807 | 12 | 2011-08-11T18:13:35Z | 7,030,984 | 17 | 2011-08-11T18:29:38Z | [
"python",
"matplotlib"
] | I'm producing a graph in matplotlib and I would like to set the x-axis between 0-10000 but I do not want to change the y axis I want the graph to do that on it's own. Right now both axis are automatically generated.
Here's an example:
```
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis(... | This seems to work fine for me:
```
import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
# print plt.xlim()
plt.xlim(0, 10000)
# or
# plt.xlim(xmin=0, xmax=10000)
``` |
How do I get the opposite (negation) of a Boolean in Python? | 7,030,831 | 15 | 2011-08-11T18:15:35Z | 7,030,846 | 33 | 2011-08-11T18:16:19Z | [
"python",
"boolean"
] | For the following sample:
```
def fuctionName(int, bool):
if int in range(...):
if bool == True:
return False
else:
return True
```
Is there any way to skip the second if-statement? Just to tell the computer to return the opposite of the boolean `bool`? | You can just use:
```
return not bool
``` |
Returning millisecond representation of datetime in python | 7,031,031 | 8 | 2011-08-11T18:34:11Z | 7,031,075 | 14 | 2011-08-11T18:38:11Z | [
"python",
"google-app-engine"
] | Using Python, I'm storing a date & time as datetime.datetime into GAE. Is there a way to get the value of the date time in milliseconds as opposed to the fully formatted string version?
Based on the docs for datetime.datetime, I don't see any native methods on the date time class that does this.
<http://docs.python.or... | To get the seconds since the epoch:
```
date_time_secs = time.mktime(datetimeobj.timetuple())
```
or for the whole thing in miliseconds
```
date_time_milis = time.mktime(datetimeobj.timetuple()) * 1000 + datetimeobj.microsecond / 1000
```
or similar. |
TypeError: 'str' does not support the buffer interface | 7,031,699 | 5 | 2011-08-11T19:30:01Z | 9,856,199 | 14 | 2012-03-24T22:29:07Z | [
"python"
] | i post from my original code,
```
crystal = open('vmises.dat','r')
crystalincrement = pickle.load(crystal)
crystaldir = pickle.load(crystal)
crystalface = pickle.load(crystal)
crystal.close()
```
Error is,
```
crystalincrement = pickle.load(crystal)
```
TypeError: 'str' does not support the buffer interface
i us... | The real answer should be open the file in binary mode in windows.
open('data.txt', 'rb') |
Creating unique list of objects from multiple lists | 7,031,736 | 3 | 2011-08-11T19:32:27Z | 7,031,847 | 7 | 2011-08-11T19:40:40Z | [
"python",
"performance"
] | I have defined a custom object with multiple fields.
For example say I have a Student object, which consists of a name, ID, and age. To compare two students and determine whether they are the same student or not, I implemented a `__ eq__` method that will return whether the age, name, and ID of the two students match ... | ```
from itertools import chain
myset = set(chain(iterable1, iterable2, iterable3, iterable4))
```
You get unique items, and you only iterate over each iterable once. `chain` makes one long iterable from a series of iterables. If you need it sorted, `sorted(myset)` will give you a sorted list.
Your `Student` class ne... |
Python, run application with parameters | 7,032,212 | 6 | 2011-08-11T20:12:40Z | 7,032,765 | 14 | 2011-08-11T20:59:49Z | [
"python",
"python-3.x",
"command-line-arguments"
] | I need to run an application (binary file) and pass arguments using a Python code. Some arguments represent strings got during Python file processing.
```
for i in range ( len ( files ) ) :
subprocess.call(["test.exe", files[i]]) //How to pass the argument files[i]
```
Thanks...
**Updated question:**
---
Maybe... | ```
args = ['test. exe']
subprocess.call(args, '-f') //Error
```
should be:
```
args = ['test.exe', '-f']
subprocess.call(args)
```
The command line argument should all be inside a single list for the first parameter of subprocess.call. The second argument to call is bufsize, which is supposed to be an integer (hen... |
Why does Python's urllib2.urlopen() raise an HTTPError for successful status codes? | 7,032,890 | 17 | 2011-08-11T21:11:18Z | 7,033,063 | 14 | 2011-08-11T21:26:23Z | [
"python",
"urllib2",
"http-status-codes"
] | According to [the urllib2 documentation](http://docs.python.org/howto/urllib2.html#httperror),
> Because the default handlers handle redirects (codes in the 300 range), and codes in the 100-299 range indicate success, you will usually only see error codes in the 400-599 range.
And yet the following code
```
request ... | You can write a custom `Handler` class for use with `urllib2` to prevent specific error codes from being raised as `HTTError`. Here's one I've used before:
```
class BetterHTTPErrorProcessor(urllib2.BaseHandler):
# a substitute/supplement to urllib2.HTTPErrorProcessor
# that doesn't raise exceptions on status ... |
How to preserve line breaks when generating python docs using sphinx | 7,033,239 | 30 | 2011-08-11T21:41:28Z | 7,033,646 | 23 | 2011-08-11T22:22:58Z | [
"python",
"python-sphinx"
] | I am using Sphinx for generating docs for a python project.
The output html is not preserving the line breaks which are present in the docstring.
Example:
Code
```
def testMethod(arg1,arg2):
"""
This is a test method
Arguments:
arg1: arg1 description
arg2: arg2 description
Returns:
None
... | In general in restructured text use
```
| Vertical bars
| like this
```
to keep line breaks |
How to preserve line breaks when generating python docs using sphinx | 7,033,239 | 30 | 2011-08-11T21:41:28Z | 9,664,844 | 14 | 2012-03-12T09:52:05Z | [
"python",
"python-sphinx"
] | I am using Sphinx for generating docs for a python project.
The output html is not preserving the line breaks which are present in the docstring.
Example:
Code
```
def testMethod(arg1,arg2):
"""
This is a test method
Arguments:
arg1: arg1 description
arg2: arg2 description
Returns:
None
... | If you add the following to your main .rst file:
```
.. |br| raw:: html
<br />
```
Then in your markup you can add in `|br|` to create linebreaks just for HTML.
```
I want to break this line here: |br| after the break.
```
From: <http://docutils.sourceforge.net/FAQ.html#how-to-indicate-a-line-break-or-a-signifi... |
How to preserve line breaks when generating python docs using sphinx | 7,033,239 | 30 | 2011-08-11T21:41:28Z | 29,513,834 | 7 | 2015-04-08T11:52:13Z | [
"python",
"python-sphinx"
] | I am using Sphinx for generating docs for a python project.
The output html is not preserving the line breaks which are present in the docstring.
Example:
Code
```
def testMethod(arg1,arg2):
"""
This is a test method
Arguments:
arg1: arg1 description
arg2: arg2 description
Returns:
None
... | This answer comes late, but maybe it'll still be useful to others.
You could use `reStructuredText` in your docstrings. This would look something like
```
:param arg1: arg1 description
:type arg1: str
:param arg2: arg2 description
:type arg2: str
```
From the looks of your example however it seems you're using the G... |
Difference between a[:] = b and a = b[:]? (Python) | 7,033,499 | 7 | 2011-08-11T22:07:21Z | 7,033,513 | 8 | 2011-08-11T22:08:41Z | [
"python",
"sequence",
"slice"
] | I was asked this for a coding test and didn't know the answer. Anyone have any ideas? | `[:]` is the slice operator.
When it's on the left side, it overwrites the contents of the list without creating a new reference.
When it's on the right side, it creates a copy of the list with the same contents. |
Nodejs: Where or How to write complicated business logic? | 7,033,844 | 26 | 2011-08-11T22:44:43Z | 7,048,882 | 21 | 2011-08-13T05:54:59Z | [
"java",
"python",
"node.js"
] | Recently I got introduced to node.js and cool packages like express and jade. I have few questions consistently knocking my door:
If I pick node.js to build my next website, I will be using JavaScript to write my server-side complicated logic? but I don't think you can compare JavaScript with Java or Python to write s... | Not quite sure what most of these folks are talking about.
A "vast ocean of libraries" is something the community is actively working on. Check this: <http://search.npmjs.org/#/_analytics> -- there were 8 packages published *yesterday*
Its not going to solve your software design for you. As for where and how to write... |
PYTHON get files from command line | 7,033,987 | 20 | 2011-08-11T23:07:13Z | 7,033,998 | 17 | 2011-08-11T23:08:22Z | [
"python",
"input",
"command"
] | How do you get a file name from command line when you run a Python code? Like if your code opens a file and reads the line, but the file varies whenever you run it, how to you say:
```
python code.py input.txt
```
so the code analyzes "input.txt"? What would you have to do in the actual Python code? I know, this is a... | ```
import sys
filename = sys.argv[-1]
```
This will get the last argument on the command line. If no arguments are passed, it will be the script name itself, as `sys.argv[0]` is the name of the running program. |
PYTHON get files from command line | 7,033,987 | 20 | 2011-08-11T23:07:13Z | 7,034,031 | 29 | 2011-08-11T23:13:51Z | [
"python",
"input",
"command"
] | How do you get a file name from command line when you run a Python code? Like if your code opens a file and reads the line, but the file varies whenever you run it, how to you say:
```
python code.py input.txt
```
so the code analyzes "input.txt"? What would you have to do in the actual Python code? I know, this is a... | A great option is the `fileinput` module, which will grab any or all filenames from the command line, and then give the contents to your script as though they were one big file.
```
import fileinput
for line in fileinput.input():
process(line)
```
More information [here](http://docs.python.org/library/fileinput.h... |
PYTHON get files from command line | 7,033,987 | 20 | 2011-08-11T23:07:13Z | 7,034,155 | 7 | 2011-08-11T23:35:25Z | [
"python",
"input",
"command"
] | How do you get a file name from command line when you run a Python code? Like if your code opens a file and reads the line, but the file varies whenever you run it, how to you say:
```
python code.py input.txt
```
so the code analyzes "input.txt"? What would you have to do in the actual Python code? I know, this is a... | Command line parameters are available as a list via the [sys](http://docs.python.org/library/sys.html) module's [argv](http://docs.python.org/library/sys.html?highlight=sys.argv#sys.argv) list. The first element in the list is the name of the program (`sys.argv[0]`). The remaining elements are the command line paramete... |
TypeError: 'NoneType' object is unsubscriptable | 7,034,024 | 5 | 2011-08-11T23:12:24Z | 7,034,048 | 7 | 2011-08-11T23:16:06Z | [
"python"
] | I have a python program that produces an error:
```
def update_ranges(phonemelist) :
""" updating the rows and columns of the list of input phonemes"""
# make a copy of the list as we're going to modify it (optional)
phonlist = phonemelist[:]
# we don't need the row titles, they just complicate things
... | It isn't a problem with this part of code. It means either
```
phonlist
```
or
```
phonlist[next_row]
```
is not a `list`(or an subscritable type), a `None`. Look for where you creating the list.
**Edit:**
```
curr_low, curr_high = phonlist[curr_row][curr_col]
next_low, next_high = phonlist[next_row][next_col]
``... |
TypeError: 'NoneType' object is unsubscriptable | 7,034,024 | 5 | 2011-08-11T23:12:24Z | 9,474,010 | 9 | 2012-02-27T23:25:24Z | [
"python"
] | I have a python program that produces an error:
```
def update_ranges(phonemelist) :
""" updating the rows and columns of the list of input phonemes"""
# make a copy of the list as we're going to modify it (optional)
phonlist = phonemelist[:]
# we don't need the row titles, they just complicate things
... | This is the error that Python returns when you try to access a subscripted (indexed) value from the `None` value (Python's `null` equivalent):
```
>>> a = None
>>> a[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not subscriptable
``` |
Adding attributes to instancemethods in Python | 7,034,063 | 27 | 2011-08-11T23:17:58Z | 7,034,094 | 29 | 2011-08-11T23:23:30Z | [
"python",
"instance-method"
] | I bumped into this behaviour when trying to get class-decorators and method-decorators to play nicely together. Essentially, the method decorators would flag some of the methods as special with some dummy value, and the class decorator would come by after and fill in the value later. This is a simplified example
```
>... | For attribute lookup, Python is automatically using the real function attached to the instance method for you.
For attribute setting, it is not.
They are two separate operations depending on which side of the statement you're on, even though they both use the `.` operator.
When you access an instance method's `__fun... |
Non greedy parsing with pyparsing | 7,037,451 | 5 | 2011-08-12T08:27:14Z | 7,038,319 | 7 | 2011-08-12T09:43:19Z | [
"python",
"parsing",
"grammar",
"pyparsing"
] | I'm trying to parse a line with pyparsing. This line is composed of a number of (key, values). What I'd like to get is a list of (key, values). A simple example:
```
ids = 12 fields = name
```
should result in something like: `[('ids', '12'), ('fields', 'name')]`
A more complex example:
```
ids = 12, 13, 14 fields ... | The first problem lies in this line:
```
val = ~key_equal + P.Word(P.alphanums+', ')
```
It suggests that the part matches any alphanumeric sequence, followed by the literal `', '`, but instead it matches any sequence of alphanumeric characters, `','` and `' '`.
What you'd want instead is:
```
val = ~key_equal + P.... |
Dude, where is my Django installation? | 7,037,468 | 61 | 2011-08-12T08:29:04Z | 7,037,485 | 13 | 2011-08-12T08:30:43Z | [
"python",
"django",
"path",
"installation"
] | I use Django but I need to find the default templates and applications.
I don't know where it's installed.
How can I find that ? | ```
$ python
>>> import django
>>> django.__file__
'/usr/local/lib/python2.7/site-packages/django/__init__.pyc'
``` |
Dude, where is my Django installation? | 7,037,468 | 61 | 2011-08-12T08:29:04Z | 7,037,502 | 97 | 2011-08-12T08:31:37Z | [
"python",
"django",
"path",
"installation"
] | I use Django but I need to find the default templates and applications.
I don't know where it's installed.
How can I find that ? | in the CLI you can do this:
```
>>> import django
>>> django
<module 'django' from '/usr/local/lib/python2.6/dist-packages/django/__init__.pyc'>
``` |
Dude, where is my Django installation? | 7,037,468 | 61 | 2011-08-12T08:29:04Z | 12,974,642 | 7 | 2012-10-19T12:49:15Z | [
"python",
"django",
"path",
"installation"
] | I use Django but I need to find the default templates and applications.
I don't know where it's installed.
How can I find that ? | The current top [answer](http://stackoverflow.com/a/7037502/466771) doesn't work, at least on linux.
From the Django [tutorial](https://docs.djangoproject.com/en/1.4/intro/tutorial02/#customize-the-admin-look-and-feel):
> If you have difficulty finding where the Django source files are
> located on your system, run t... |
numpy, named columns | 7,037,938 | 9 | 2011-08-12T09:09:32Z | 7,038,659 | 9 | 2011-08-12T10:13:40Z | [
"python",
"numpy"
] | Simple question about *numpy*:
I load 100 values to a vector `a`. From this vector, I want to create an array `A` with 2 columns, where one column has name "C1" and second one "C2", one has type `int32` and another `int64`. An example:
```
a = range(100)
A = array(a).reshape( len(a)/2, 2)
# A.dtype = ...?
```
How to... | Numpy structured arrays have named columns:
```
import numpy as np
a=range(100)
A = np.array(zip(*[iter(a)]*2),dtype=[('C1','int32'),('C2','int64')])
print(A.dtype)
# [('C1', '<i4'), ('C2', '<i8')]
```
You can access the columns by name like this:
```
print(A['C1'])
# [ 0 2 4 6 8 10 12 14 16 18 20 22 24 26 28 3... |
Python: testing for None, testing for boolean value | 7,038,681 | 10 | 2011-08-12T10:16:18Z | 7,038,719 | 7 | 2011-08-12T10:20:01Z | [
"python"
] | Is there any low-level, implementation-related difference (performance-ish) between these approaches..?
```
# check if string is empty
# the preferred way it seems [1]
if string:
print string
else:
print "It's empty."
# versus [2]
if string is '':
# or [3]
if string == '':
```
For example, when testing for ... | Never use `is` for (value) equality testing. Only use it to test for object identity. It may work for the example `if string is ''`, but this is implementation dependent, and you can't rely on it.
```
>>> a = "hi"
>>> a is "hi"
True
>>> a = "hi there!"
>>> a is "hi there!"
False
```
Other than that, use whatever conv... |
numpy.argmax: how to get the index corresponding to the *last* occurrence, in case of multiple occurrences of the maximum values | 7,038,975 | 4 | 2011-08-12T10:44:21Z | 7,039,059 | 7 | 2011-08-12T10:51:35Z | [
"python",
"arrays",
"list",
"numpy",
"indexing"
] | I have an array of numbers, and the maximum value might occurrence more than once.
Is it possible to find the index of the last occurrence of the maximum value by using something like numpy.argmax?
Or, even better, is it possible to get a list of indices of all the occurrences of the maximum value in the array? | ```
import numpy as np
a = np.array((1,2,3,2,3,2,1,3))
occurences = np.where(a == a.max())
# occurences == array([2, 4, 7])
``` |
'Waiting' animation in command prompt (Python) | 7,039,114 | 4 | 2011-08-12T10:56:32Z | 7,039,175 | 11 | 2011-08-12T11:02:52Z | [
"python",
"animation",
"command"
] | I have a Python script which takes a long time to run. I'd quite like to have the command line output to have a little 'waiting' animation, much like the swirly circle we get in browsers for AJAX requests. Something like an output of a '\', then this is replaced by a '|', then '/', then '-', '|', etc, like the text is ... | Use `\r` and print-without-newline (that is, suffix with a comma):
```
animation = "|/-\\"
idx = 0
while thing_not_complete():
print animation[idx % len(animation)] + "\r",
idx += 1
time.sleep(0.1)
``` |
This application does not exist (app_id=xxx) | 7,039,200 | 24 | 2011-08-12T11:04:55Z | 7,039,537 | 12 | 2011-08-12T11:38:31Z | [
"python",
"google-app-engine"
] | I was unable to upload to an AppEngine as `appcfg` was telling me :
> This application does not exist (app\_id=u'xxx').
I was only a developer on the AppEngine, so as I was just testing I created a new AppEngine where I was the owner but I still get the same message on a newly created AppEngine. | You have to log in in your gae account and create an application before you upload it, and your app\_id has to have the same name as you app. You can't just upload it.
So go [here](https://appengine.google.com/), create your app, for example "example\_app" and set the app\_id=example\_app and everything should work :) |
This application does not exist (app_id=xxx) | 7,039,200 | 24 | 2011-08-12T11:04:55Z | 7,624,944 | 42 | 2011-10-02T06:25:14Z | [
"python",
"google-app-engine"
] | I was unable to upload to an AppEngine as `appcfg` was telling me :
> This application does not exist (app\_id=u'xxx').
I was only a developer on the AppEngine, so as I was just testing I created a new AppEngine where I was the owner but I still get the same message on a newly created AppEngine. | The fix I found was to add the parameter `--no_cookies`:
```
appcfg.py update --no_cookies MyProjectDirectory/
```
This can happen when you upload AppEngine applications from different Google accounts on the same computer. |
Translate Perl to Python: do this or die | 7,039,274 | 8 | 2011-08-12T11:12:54Z | 7,039,310 | 11 | 2011-08-12T11:16:52Z | [
"python",
"perl"
] | I am moving a Perl (of which I have very little knowledge) script to python.
```
$path = $ENV{ 'SOME_NAME' } || die " SOME_NAME ENV VARIABLE NOT FOUND\n";
```
I can (hopefully) see what this line does, either set the variable 'path' to the environment variable 'SOME\_NAME' or failing that then print an error message ... | ```
try:
path = os.environ['SOME_NAME']
var2 = os.environ['VAR2']
var3 = os.environ['VAR3']
var4 = os.environ['VAR4']
except KeyError,e:
print "Not found: ", e
```
You can put more than one statement into a try block. |
Python - "\" character | 7,039,931 | 3 | 2011-08-12T12:16:29Z | 7,039,941 | 11 | 2011-08-12T12:17:44Z | [
"python"
] | I'm newbie in Python. I'm trying to insert in a string a `"\"` character, but if i declare it like this, it takes `\"` as a `"` character.
I also tried to declare, e.g. `fname='\\'`
but it does not work.
What I mean to do is to add to a path `e:\\Others\Contacts` the string `\<filename>`.
May anyone help me? | ```
backslash = '\\'
```
You can also use raw [string literals](http://docs.python.org/reference/lexical_analysis.html#string-literals). Note that there's no way to have a backslash at the end of a raw string literal though.
```
path = r'e:\Others\Contacts'
```
However, instead of fiddling with backslashes, you shou... |
Calling the "source" command from subprocess.Popen | 7,040,592 | 13 | 2011-08-12T13:13:11Z | 7,040,659 | 14 | 2011-08-12T13:18:52Z | [
"python",
"unix",
"popen"
] | I have a .sh script that I call with `source the_script.sh`. Calling this regularly is fine. However, I am trying to call it from my python script, through `subprocess.Popen`.
Calling it from Popen, I am getting the following errors in the following two scenario calls:
```
foo = subprocess.Popen("source the_script.sh... | `source` is not an executable command, it's a shell builtin.
The most usual case for using `source` is to run a shell script that changes the environment and to retain that environment in the current shell. That's exactly how virtualenv works to modify the default python environment.
Creating a sub-process and using ... |
Calling the "source" command from subprocess.Popen | 7,040,592 | 13 | 2011-08-12T13:13:11Z | 12,708,396 | 16 | 2012-10-03T12:24:11Z | [
"python",
"unix",
"popen"
] | I have a .sh script that I call with `source the_script.sh`. Calling this regularly is fine. However, I am trying to call it from my python script, through `subprocess.Popen`.
Calling it from Popen, I am getting the following errors in the following two scenario calls:
```
foo = subprocess.Popen("source the_script.sh... | You could just run the command in a subshell and use the results to update the current environment.
```
def shell_source(script):
"""Sometime you want to emulate the action of "source" in bash,
settings some environment variables. Here is a way to do it."""
import subprocess, os
pipe = subprocess.Popen... |
Execute python from php | 7,041,104 | 4 | 2011-08-12T13:55:13Z | 7,041,154 | 7 | 2011-08-12T13:59:10Z | [
"php",
"python"
] | Say you have a class like this:
```
class MyClass:
def __init__(self, var1):
self.var = var1
....
```
This class, in python, works only when you assign a value:
```
x = MyClass("Hi")
```
So basically, my question is whether I can send a variable from php to execute a python class, and return its out... | First of all, create a file containing the python-script you want to execute, including (or loading) the class and `x = MyClass("Hi")`
Now, use the following line to get the result:
```
$result = exec('python yourscript.py');
``` |
PIL's colour space conversion YCbCr -> RGB | 7,041,172 | 9 | 2011-08-12T14:00:15Z | 7,042,835 | 7 | 2011-08-12T15:54:54Z | [
"python",
"c",
"python-imaging-library",
"rgb",
"yuv"
] | The algorithm used by PIL v1.1.7 gives me 'washed out' looking results. When I convert the same source data using ffmpeg it looks normal. Using mplayer gives identical results to ffmpeg (probably they use the same library underneath). This leads me to believe PIL may be stuffing up their colour space conversions. The c... | If you look at Wikipedia's definitions, you can see that there are two conflicting definitions for YCbCr. The [ITU-R BT.601](http://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion) definition compresses the values to the range 16-235 to provide footroom and headroom, while the [JPEG](http://en.wikipedia.org/wiki/YC... |
Any reason NOT to always use keyword arguments? | 7,041,752 | 47 | 2011-08-12T14:40:49Z | 7,041,812 | 11 | 2011-08-12T14:45:49Z | [
"coding-style",
"python"
] | Before jumping into python, I had started with some Objective-C / Cocoa books. As I recall, most functions required keyword arguments to be explicitly stated. Until recently I forgot all about this, and just used positional arguments in Python. But lately, I've ran into a few bugs which resulted from improper positions... | Well, there are a few reasons why I would not do that.
If all your arguments are keyword arguments, it increases noise in the code and it might remove clarity about which arguments are required and which ones are optionnal.
Also, if I have to use your code, I might want to kill you !! (Just kidding), but having to ty... |
Any reason NOT to always use keyword arguments? | 7,041,752 | 47 | 2011-08-12T14:40:49Z | 7,041,991 | 46 | 2011-08-12T14:58:02Z | [
"coding-style",
"python"
] | Before jumping into python, I had started with some Objective-C / Cocoa books. As I recall, most functions required keyword arguments to be explicitly stated. Until recently I forgot all about this, and just used positional arguments in Python. But lately, I've ran into a few bugs which resulted from improper positions... | There isn't any reason not to use keyword arguments apart from the clarity and readability of the code. The choice of whether to use keywords should be based on whether the keyword adds additional useful information when reading the code or not.
I follow the following general rule:
1. If it is hard to infer the funct... |
Any reason NOT to always use keyword arguments? | 7,041,752 | 47 | 2011-08-12T14:40:49Z | 7,042,432 | 15 | 2011-08-12T15:26:55Z | [
"coding-style",
"python"
] | Before jumping into python, I had started with some Objective-C / Cocoa books. As I recall, most functions required keyword arguments to be explicitly stated. Until recently I forgot all about this, and just used positional arguments in Python. But lately, I've ran into a few bugs which resulted from improper positions... | If your consideration is to improve readability of function calls, why not simply declare functions as normal, e.g.
```
def test(x, y):
print "x:", x
print "y:", y
```
And simply call functions by declaring the names explicitly, like so:
```
test(y=4, x=1)
```
Which obviously gives you the output:
```
x: 1... |
Django: Auto-generating a list of files in a directory | 7,042,031 | 4 | 2011-08-12T15:01:09Z | 7,042,875 | 9 | 2011-08-12T15:57:51Z | [
"python",
"django",
"image",
"list"
] | I use an image gallery app on my website. At present I drop image files in a directory, and write img html tags for each image manually. Is it possible to make django create a list of files in the directory automatically, and send the json output to the gallery app, so that I can make javascript to generate `<img>` ele... | here's a bit of code for you:
views.py
```
import os
def gallery(request):
path="C:\\somedirectory" # insert the path to your directory
img_list =os.listdir(path)
return render_to_response('gallery.html', {'images': img_list})
```
gallery.html
```
{% for image in images %}
<img src='/static/{{i... |
How do I properly override __setattr__ and __getattribute__ on new-style classes in Python? | 7,042,152 | 24 | 2011-08-12T15:10:14Z | 7,042,247 | 22 | 2011-08-12T15:15:32Z | [
"python",
"inheritance",
"override",
"setattr"
] | I want to override my Python class's `__getattribute__` and `__setattr__` methods. My use case is the usual one: I have a few special names that I want to handle, and I want the default behavior for anything else. For `__getattribute__`, it seems that I can request the default behavior simply by raising `AttributeError... | It's
```
super(ABCImmutable, self).__setattr__(name, value)
```
in Python 2, or
```
super().__setattr__(name, value)
```
in Python 3.
Also, raising `AttributeError` is **not** how you fall back to the default behavior for `__getattribute__`. You fall back to the default with
```
return super(ABCImmutable, self)._... |
Advanced string formatting - Python | 7,042,695 | 2 | 2011-08-12T15:46:24Z | 7,042,809 | 10 | 2011-08-12T15:53:03Z | [
"python",
"string",
"string-formatting"
] | here is a quick example of what I'm trying to do
```
box = {
'colour': 'Red',
'dimensions': {
'width': '100px',
'height': '333px',
}
}
print "The box is %(colour)s, wide %(dimensions.width) and high %(dimensions.height)" %box
```
Is this possible with the standard library?
If not, what ... | ```
>>> box = {
'colour': 'Red',
'dimensions': {
'width': '100px',
'height': '333px',
}
}
>>> print "The box is {colour}, wide {dimensions[width]} and high {dimensions[height]}".format(**box)
The box is Red, wide 100px and high 333px
``` |
An efficient way of making a large random bytearray | 7,044,044 | 16 | 2011-08-12T17:32:07Z | 7,044,536 | 26 | 2011-08-12T18:18:30Z | [
"python",
"random",
"bytearray"
] | I need to create a large bytearry of a specific size but the size is not known prior to run time. The bytes need to be fairly random. The bytearray size may be as small as a few KBs but as large as a several MB. I do not want to iterate byte-by-byte. This is too slow -- I need performance similar to numpy.random. Howev... | The os module provides `urandom`, even on Windows:
```
bytearray(os.urandom(1000000))
```
This seems to perform as quickly as you need, in fact, I get better timings than your numpy (though our machines could be wildly different):
```
timeit.timeit(lambda:bytearray(os.urandom(1000000)), number=10)
0.0554857286941
``... |
Python interpreted code optimisation | 7,044,515 | 18 | 2011-08-12T18:16:53Z | 7,044,599 | 26 | 2011-08-12T18:23:01Z | [
"python",
"optimization",
"interpreter"
] | Consider the following code snippet:
```
dict [name] = 0
dict [name] += 1
dict [name] += 1
```
Does the python interpreter automatically recognise the repeated references to the dictionary value and use a cached local reference instead?, somewhat akin to the aliasing optimisations of C/C++, becoming something like so... | You can run it through the disassembler to find out:
```
import dis
def test():
name = 'test'
tdict = {}
tdict[name] = 0
tdict[name] += 1
tdict[name] += 1
dis.dis(test)
```
Running this we get:
```
13 0 LOAD_CONST 1 ('test')
3 STORE_FAST 0 (n... |
Python interpreted code optimisation | 7,044,515 | 18 | 2011-08-12T18:16:53Z | 7,044,686 | 8 | 2011-08-12T18:30:25Z | [
"python",
"optimization",
"interpreter"
] | Consider the following code snippet:
```
dict [name] = 0
dict [name] += 1
dict [name] += 1
```
Does the python interpreter automatically recognise the repeated references to the dictionary value and use a cached local reference instead?, somewhat akin to the aliasing optimisations of C/C++, becoming something like so... | That type of optimization isn't possible simply by inspecting the code. Your name `dict` could refer not to a native dictionary, but a user-defined object that implements `__setitem__`, and that method has to be called three times. At runtime, a sophisticated implementation could note the actual value of the name, and ... |
How do I read a jpg or png from the windows clipboard in python and vice versa? | 7,045,264 | 5 | 2011-08-12T19:19:56Z | 7,045,677 | 10 | 2011-08-12T20:01:27Z | [
"python",
"pywin32"
] | I have an image (jpg, png, etc.) in the windows clipboard. I'd like to save it to a file. win32clipboard would seem to be the answer, but every example I can find deals with text.
copy an image to the clipboard, then
```
import win32clipboard
win32clipboard.OpenClipboard()
data = win32clipboard.GetClipboardData()
wit... | I would just use [Pillow](https://pillow.readthedocs.org/):
```
from PIL import ImageGrab
im = ImageGrab.grabclipboard()
im.save('somefile.png','PNG')
``` |
automatically position text box in matplotlib | 7,045,729 | 19 | 2011-08-12T20:06:55Z | 7,045,788 | 20 | 2011-08-12T20:13:48Z | [
"python",
"textbox",
"matplotlib"
] | Is there a way of telling pyplot.text() a location like you can with pyplot.legend()?
Something like the legend argument would be excellent:
```
plt.legend(loc="upper left")
```
I am trying to label subplots with different axes using letters (e.g. "A","B"). I figure there's got to be a better way than manually estim... | Just use `annotate` and specify axis coordinates. For example, "upper left" would be:
```
plt.annotate('Something', xy=(0.05, 0.95), xycoords='axes fraction')
```
You could also get fancier and specify a constant offset in points:
```
plt.annotate('Something', xy=(0, 1), xytext=(12, -12), va='top'
xycoo... |
automatically position text box in matplotlib | 7,045,729 | 19 | 2011-08-12T20:06:55Z | 33,417,697 | 8 | 2015-10-29T14:59:34Z | [
"python",
"textbox",
"matplotlib"
] | Is there a way of telling pyplot.text() a location like you can with pyplot.legend()?
Something like the legend argument would be excellent:
```
plt.legend(loc="upper left")
```
I am trying to label subplots with different axes using letters (e.g. "A","B"). I figure there's got to be a better way than manually estim... | I'm not sure if this was available when I originally posted the question but using the loc parameter can now actually be used. Below is an example:
```
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnchoredText
# make some data
x = np.arange(10)
y = x
# set up figure and axes
f,... |
Python list filtering with arguments | 7,045,754 | 10 | 2011-08-12T20:09:37Z | 7,045,793 | 25 | 2011-08-12T20:14:11Z | [
"python",
"list",
"filter",
"functional-programming"
] | Is there a way in python to call filter on a list where the filtering function has a number of arguments bound during the call. For example is there a way to do something like this:
```
>> def foo(a,b,c):
return a < b and b < c
>> myList = (1,2,3,4,5,6)
>> filter(foo(a=1,c=4),myList)
>> (2,3)
```
This is to say... | One approach is to use `lambda`:
```
>>> def foo(a, b, c):
... return a < b and b < c
...
>>> myTuple = (1, 2, 3, 4, 5, 6)
>>> filter(lambda x: foo(1, x, 4), myTuple)
(2, 3)
```
Another is to use [`partial`](http://docs.python.org/library/functools.html#functools.partial):
```
>>> from functools import partial
... |
Python list filtering with arguments | 7,045,754 | 10 | 2011-08-12T20:09:37Z | 7,045,809 | 10 | 2011-08-12T20:15:51Z | [
"python",
"list",
"filter",
"functional-programming"
] | Is there a way in python to call filter on a list where the filtering function has a number of arguments bound during the call. For example is there a way to do something like this:
```
>> def foo(a,b,c):
return a < b and b < c
>> myList = (1,2,3,4,5,6)
>> filter(foo(a=1,c=4),myList)
>> (2,3)
```
This is to say... | You can create a closure for this purpose:
```
def makefilter(a, c):
def myfilter(x):
return a < x < c
return myfilter
filter14 = makefilter(1, 4)
myList = [1, 2, 3, 4, 5, 6]
filter(filter14, myList)
>>> [2, 3]
``` |
Creating a matrix of options using itertools | 7,046,178 | 7 | 2011-08-12T20:51:10Z | 7,046,341 | 8 | 2011-08-12T21:06:42Z | [
"python",
"itertools"
] | I am trying to produce a matrix of True and False values, which shows all the permutations for a given number of choices. So for 5 choices you would have the following output.
```
F F F F F
T F F F F
T T F F F
T T T F F
...
F T F F F
...
```
I have been looking at using itertool's permutations and combinations, but t... | Use [itertools.product](http://docs.python.org/library/itertools.html#itertools.product):
```
itertools.product([False,True],repeat=5)
```
example of `itertools.product([False,True],repeat=2)`:
```
(False, False)
(False, True)
(True, False)
(True, True)
``` |
python when to use copy.copy | 7,046,971 | 4 | 2011-08-12T22:26:51Z | 7,047,061 | 15 | 2011-08-12T22:39:15Z | [
"python"
] | I think I'm starting to understand python, but I still have trouble with a basic question. When to use `copy.copy`?
```
>>>a=5
>>>b=a
>>>a=6
>>>print b
5
```
Ok makes sense. But in what circumstances does saying `b=a` form some kind of 'link' between a and b such that modifying a would then modify b? This is what I d... | Basically, `b = a` points `b` to wherever `a` points, and nothing else.
What you're asking about is mutable types. Numbers, strings, tuples, frozensets, booleans, `None`, are immutable. Lists, dictionaries, sets, bytearrays, are mutable.
If I make a mutable type, like a `list`:
```
>>> a = [1, 2] # create an object... |
JSON serialize Django Queryset with values being called. Is there anything wrong with my approach? | 7,047,297 | 7 | 2011-08-12T23:15:41Z | 7,173,752 | 13 | 2011-08-24T10:12:33Z | [
"python",
"django",
"json"
] | Here is the problem: Django's serializer doesn't support dictionaries and simplejson doesn't support Django Querysets. See [JSON Serializing Django Models with simplejson](http://stackoverflow.com/questions/2249792/json-serializing-django-models-with-simplejson)
I was wondering if there is anything wrong with my solut... | Your solution is totally valid and very clean in my own opinion.
If you need a list of lists (instead of a list of dictionaries) you can use too:
```
from django.utils import simplejson
people = People.objects.all().values_list('name', 'id')
simplejson.dumps(list(people))
```
Sometimes when the json output is very ... |
Using frequent itemset mining to build association rules? | 7,047,555 | 15 | 2011-08-13T00:01:34Z | 7,049,664 | 18 | 2011-08-13T09:38:59Z | [
"python",
"machine-learning",
"data-mining"
] | I am new to this area as well as the terminology so please feel free to suggest if I go wrong somewhere. I have two datasets like this:
### Dataset 1:
```
A B C 0 E
A 0 C 0 0
A 0 C D E
A 0 C 0 E
```
The way I interpret this is at some point in time, (A,B,C,E) occurred together and so did (A,C), (A,C,D,E) etc.
### D... | Some theoretical facts about association rules:
* Association rules is a type of undirected data mining that finds patterns in the data where the target is not specified beforehand. Whether the patterns make sense is left to human interpretation.
* The goal of association rules is to detect relationships or associatio... |
Unexpected mathematical output | 7,048,031 | 2 | 2011-08-13T01:49:26Z | 7,048,043 | 12 | 2011-08-13T01:53:49Z | [
"python"
] | I am trying to count my eggs in an exercise in Learning Python the Hard Way. The formula for counting the eggs is:
```
print (3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
```
and the suggested answer is `7`.
I am getting `6.75` and have no idea why, I think I am putting it in correctly but I could be wrong. The way it is shown... | In python 2.x, the `/` operator did integer division. In python 3, the result of the `/` is a `float` regardless of the input types. Use the `//` operator to perform integer division. |
Running python through fastCGI for nginx | 7,048,057 | 8 | 2011-08-13T01:56:51Z | 7,048,194 | 17 | 2011-08-13T02:36:43Z | [
"php",
"python",
"nginx",
"fastcgi"
] | I am looking to run standalone python scripts through fcgi for use with nginx, but I have no idea where to start with spawning the processes. Currently, I have PHP successfully with nginx+fcgi, but I'm unsure if/how I can do the same with python. Any suggestions on where to start? | See the [python docs section on FCGI](http://docs.python.org/howto/webservers.html#setting-up-fastcgi). Basically, with Python, you use the WSGI interface on top of an fcgi server which talks to the web server (the fcgi client).
See [Python + FastCGI](http://stackoverflow.com/questions/2440651/python-fastcgi) for a co... |
How do I properly write to FIFOs in Python? | 7,048,095 | 12 | 2011-08-13T02:08:12Z | 7,048,187 | 8 | 2011-08-13T02:34:44Z | [
"python",
"linux",
"fifo",
"mkfifo"
] | Something very strange is happening when I open FIFOs (named pipes) in Python for writing. Consider what happens when I try to open a FIFO for writing in a interactive interpreter:
```
>>> fifo_write = open('fifo', 'w')
```
The above line blocks until I open another interpreter and type the following:
```
>>> fifo_r... | `read()` doesn't return until it reaches EOF. |
How can I parse multiple (unknown) date formats in python? | 7,048,828 | 9 | 2011-08-13T05:43:30Z | 7,048,905 | 11 | 2011-08-13T06:00:44Z | [
"python",
"parsing",
"date"
] | I have a bunch of excel documents I am extracting dates from. I am trying to convert these to a standard format so I can put them in a database. Is there a function I can throw these strings at and get a standard format back? Here is a small sample of my data:
The good thing is I know it is always Month/Day
```
10/02... | The third-party module [dateutil](http://labix.org/python-dateutil) has a function `parse` that operates similarly to PHP's `strtotime`: you don't need to specify a particular date format, it just tries a bunch of its own. |
How can I parse multiple (unknown) date formats in python? | 7,048,828 | 9 | 2011-08-13T05:43:30Z | 7,048,911 | 9 | 2011-08-13T06:01:38Z | [
"python",
"parsing",
"date"
] | I have a bunch of excel documents I am extracting dates from. I am trying to convert these to a standard format so I can put them in a database. Is there a function I can throw these strings at and get a standard format back? Here is a small sample of my data:
The good thing is I know it is always Month/Day
```
10/02... | If you don't want to install a third-party module like dateutil:
```
import re
from datetime import datetime
dates = ['10/02/09', '07/22/09', '09-08-2008', '9/9/2008', '11/4/2010', ' 03-07-2009', '09/01/2010']
reobj = re.compile(
r"""\s* # optional whitespace
(\d+) # Month
[-/] # separator
(\d+... |
How can I parse multiple (unknown) date formats in python? | 7,048,828 | 9 | 2011-08-13T05:43:30Z | 7,048,967 | 14 | 2011-08-13T06:19:10Z | [
"python",
"parsing",
"date"
] | I have a bunch of excel documents I am extracting dates from. I am trying to convert these to a standard format so I can put them in a database. Is there a function I can throw these strings at and get a standard format back? Here is a small sample of my data:
The good thing is I know it is always Month/Day
```
10/02... | ```
import re
ss = '''10/02/09
07/22/09
09-08-2008
9/9/2008
11/4/2010
03-07-2009
09/01/2010'''
regx = re.compile('[-/]')
for xd in ss.splitlines():
m,d,y = regx.split(xd)
print xd,' ','/'.join((m.zfill(2),d.zfill(2),'20'+y.zfill(2) if len(y)==2 else y))
```
result
```
10/02/09 10/02/2009
07/22/09 ... |
How to retrieve from python dict where key is only partially known? | 7,049,253 | 9 | 2011-08-13T07:51:49Z | 7,049,297 | 9 | 2011-08-13T08:05:07Z | [
"python",
"dictionary",
"key",
"substring"
] | I have a `dict` that has string-type keys whose exact values I can't know (because they're generated dynamically elsewhere). However, I know that that the key I want contains a particular substring, and that a single key with this substring is definitely in the dict.
What's the best, or "most pythonic" way to retrieve... | There is an option to write the second version with the performance attributes of the first one.
**Use a [generator expression](http://www.python.org/dev/peps/pep-0289/) instead of list comprehension:**
```
value = next(v for (k,v) in some_dict.iteritems() if 'substring' in k)
```
The expression inside the parenthes... |
Flask-principal tutorial (auth + authr) | 7,050,137 | 24 | 2011-08-13T11:28:37Z | 9,781,669 | 42 | 2012-03-20T05:14:42Z | [
"python",
"authentication",
"authorization",
"flask"
] | Anybody know of a good tutorial about flask-principal? I'm trying to do authentication and authorization (needRole and needIdentity) and I haven't gotten anywhere.
I am almost sure there's no really comprehensive tutorial -- maybe some of you has some time on their hands and would like to post a tutorial-as-answer? I'... | I know this question is kind of old, but a couple of days ago I was looking for the same thing so hopefully this will help someone in the future . . .
A good place to start is on [the github repo for Flask-Principal](https://github.com/mattupstate/flask-principal).
I've had some trouble with Flask-Principal (FP) too.... |
Finding unused Django code to remove | 7,050,380 | 21 | 2011-08-13T12:24:26Z | 7,050,424 | 7 | 2011-08-13T12:31:49Z | [
"python",
"django",
"code-coverage",
"coverage.py"
] | I've started working on a project with loads of unused legacy code in it. I was wondering if it might be possible to use a tool like coverage in combination with a crawler (like the django-test-utils one) to help me locate code which isn't getting hit which we can mark with deprecation warnings. I realise that somethin... | [pylint](http://pypi.python.org/pypi/pylint) is great tool for static code analysis (among others things it will detect unused imports, variables or arguments).
* <http://nedbatchelder.com/blog/200806/pylint.html>
* <http://www.doughellmann.com/articles/pythonmagazine/completely-different/2008-03-linters/index.html> |
Finding unused Django code to remove | 7,050,380 | 21 | 2011-08-13T12:24:26Z | 7,051,950 | 7 | 2011-08-13T16:57:27Z | [
"python",
"django",
"code-coverage",
"coverage.py"
] | I've started working on a project with loads of unused legacy code in it. I was wondering if it might be possible to use a tool like coverage in combination with a crawler (like the django-test-utils one) to help me locate code which isn't getting hit which we can mark with deprecation warnings. I realise that somethin... | You can run the development server under coverage if you use the --noreload switch:
```
coverage run ./manage.py runserver --noreload
``` |
Changing database per view & accessing multiple databases per view | 7,050,579 | 4 | 2011-08-13T13:01:26Z | 7,051,517 | 8 | 2011-08-13T15:50:24Z | [
"python",
"sqlalchemy",
"pylons",
"pyramid"
] | I'm having some problems using SQLAlchemy in Pyramid. Although I can find examples of what I need, they're normally very short and lacking. So I've ended up with patchy code that barely makes any sense. So I'm hoping someone could give a fuller example of what I need to do.
I have 4 databases all with the same schema.... | Configuring and connection for each request seems like a lot of work to me. I would create four session handlers in my model module and just choose from them.
Example:
```
models/__init__.py
DBSession1 = scoped_session(sessionmaker(extension=ZopeTransactionExtension()))
DBSession2 = scoped_session(sessionmaker(ext... |
Prebuilt GVim 7.3. binaries with +python support | 7,050,605 | 6 | 2011-08-13T13:08:18Z | 7,052,076 | 13 | 2011-08-13T17:17:45Z | [
"python",
"vim",
"windows-xp"
] | Apart from compiling GVim, is there anywhere where one can downlod the binaries with +python support already included?
***Edit :: Apologies for forgotting again. I'm looking for Windows binaries.*** | Okey, problem solved.
On *[www.vim.org](http://www.vim.org)* when downloading Vim one must take the *OLE* version, along with the runtimefiles archive. Upon unzipping try for example
***:python print('Whatcha doing Doc?')***
and see what error it will give. You should see something along the lines of ... yadda yadda... |
Why doesn't coverage.py properly measure Django's runserver command? | 7,051,070 | 15 | 2011-08-13T14:36:46Z | 7,051,311 | 18 | 2011-08-13T15:17:32Z | [
"python",
"django",
"coverage.py"
] | I should know the answer to this, but I don't: if you try to measure the coverage of a Django project like this:
```
coverage run manage.py runserver
```
you get coverage measurement that misses all of your actual code. Something early on in the process is stopping the measurement, or all the real work happens in a n... | Do you get the same problem if you run as follows?
```
coverage run manage.py runserver --noreload
```
Without `--noreload`, another process is started behind the scenes. One process runs the server, the other looks for code changes and restarts the server when changes are made. The chances are, you're doing the cove... |
Python: elif or new if? | 7,052,393 | 9 | 2011-08-13T18:17:24Z | 7,052,406 | 15 | 2011-08-13T18:20:13Z | [
"python",
"if-statement"
] | What is better to use:
```
if var in X:
#do_whatever
elif (var in Y):
#do_whatever2
```
or:
```
if var in X:
#do_whatever
if var in Y:
#do_whatever2
```
Assuming var can't be in both X and Y... Is there any rule or common practice? Should I use elif? or a new if? or it doesn't matter??
EDIT: Great ... | It makes a difference in some cases.
See this example:
```
def foo(var):
if var == 5:
var = 6
elif var == 6:
var = 8
else:
var = 10
return var
def bar(var):
if var == 5:
var = 6
if var == 6:
var = 8
if var not in (5, 6):
var = 10
return... |
Django attribute error. 'module' object has no attribute 'rindex' | 7,052,578 | 14 | 2011-08-13T18:50:05Z | 10,429,088 | 14 | 2012-05-03T09:59:07Z | [
"python",
"django"
] | I've just started using django, only on chapter 3 of the online book.
I keep on getting this weird error when I try and access the site.
AttributeError at /test/
'module' object has no attribute 'rindex'
my urls.py is just
```
from django.conf.urls.defaults import *
from mysite import hello
# Uncomment the next two... | You probably need to change
```
from mysite import hello
```
to something like
```
from mysite.hello_file import hello_view
```
And then use:
```
('^test/$',hello_view)
```
Because you need to pass a (view) function, not a file or module. As I think mgalgs was trying to explain, but I think a bit unclear for begi... |
How to truncate the values of a 2D numpy array | 7,052,776 | 5 | 2011-08-13T19:30:57Z | 7,052,877 | 17 | 2011-08-13T19:51:55Z | [
"python",
"numpy"
] | I have a two-dimensional numpy array(uint16), how can I truncate all values above a certain barrier(say 255) to that barrier? The other values must stay the same. Using a nested loop seems to be ineffecient and clumsy. | actually there is a specific method for this, 'clip':
```
import numpy as np
my_array = np.array([[100, 200], [300, 400]],np.uint16)
my_array.clip(0,255) # clip(min, max)
```
output:
```
array([[100, 200],
[255, 255]], dtype=uint16)
``` |
Pythonic shorthand for keys in a dictionary? | 7,053,351 | 5 | 2011-08-13T21:20:17Z | 7,053,357 | 8 | 2011-08-13T21:21:30Z | [
"dictionary",
"python",
"key"
] | Simple question: Is there a shorthand for checking the existence of several keys in a dictionary?
```
'foo' in dct and 'bar' in dct and 'baz' in dct
``` | ```
all(x in dct for x in ('foo','bar','baz'))
``` |
How to trim characters in Python? | 7,053,607 | 2 | 2011-08-13T22:09:35Z | 7,053,624 | 9 | 2011-08-13T22:12:18Z | [
"python",
"string",
"subscript"
] | Very new to Python and have very simple question. I would like to trim the last 3 characters from string. What is the efficient way of doing this?
Example `I am going` becomes `I am go` | You can use `new_str = old_str[:-3]`, that means all from the beginning to three characters before the end. |
Random 'None' output from basic python function | 7,053,652 | 9 | 2011-08-13T22:17:25Z | 7,053,664 | 12 | 2011-08-13T22:20:05Z | [
"python",
"function",
"parameters"
] | I just learned(am learning) how function parameters work in python, and I started experimenting with it for no apparent reason, when this:
```
def jiskya(x, y):
if x > y:
print y
else:
print x
print jiskya(2, 3)
```
gave the ouput:
```
>>>
2
None
```
Where did the 'None' come from? And what... | It's the return value of the function, which you print out. If there is no return statement (or [just a `return` without an argument](http://docs.python.org/reference/simple_stmts.html#return)), an implicit `return None` is added to the end of a function.
You probably want to return the values in the function instead ... |
Using flask/blueprint for some static pages | 7,054,099 | 4 | 2011-08-14T00:08:45Z | 7,056,374 | 11 | 2011-08-14T10:56:25Z | [
"python",
"flask"
] | So I am just a little confused on how to build pages with flask without having to state each view.
How would I make a blue print that would pickup on the pages i want to load?
say these are my example pages
```
templates/
layout.html
section1/
subsection/index.html
subsection2/index.html
section2
... | If you'd like to see an example of `Blueprint` usage, you can have a look at [this answer](http://stackoverflow.com/questions/6957396/url-building-with-flask-and-non-unique-handler-names/6958518#6958518).
About the "template auto-find" part of your question: like the documentation explains, blueprints allows to specif... |
Checking if something exists in items of list variable in Django template | 7,054,189 | 4 | 2011-08-14T00:31:06Z | 7,054,215 | 7 | 2011-08-14T00:36:44Z | [
"python",
"django",
"django-templates"
] | I have a list of sections that I pass to a Django template. The sections have different types. I want to say "if there is a section of this type, display this line" in my template, but having an issue. What I'm basically trying to do is this.
```
{% if s.name == "Social" for s in sections %}
Hello Social!
{% endif... | You can't use list comprehensions in templates:
```
{% for s in sections %}
{% if s.name == 'Social' %}
Hello Social!
{% endif %}
{% endif %}
``` |
Checking if something exists in items of list variable in Django template | 7,054,189 | 4 | 2011-08-14T00:31:06Z | 7,054,244 | 8 | 2011-08-14T00:44:37Z | [
"python",
"django",
"django-templates"
] | I have a list of sections that I pass to a Django template. The sections have different types. I want to say "if there is a section of this type, display this line" in my template, but having an issue. What I'm basically trying to do is this.
```
{% if s.name == "Social" for s in sections %}
Hello Social!
{% endif... | Ideally what you would do is create a list that the template gets as such:
```
l = [s.name for s in sections]
```
And in the template, use:
```
{% if 'Social' in l %}
```
You're trying to put more logic into a template than they are meant to have. Templates should use as little logic as possible, while the logic sh... |
"python" not recognised as a command | 7,054,424 | 40 | 2011-08-14T01:34:59Z | 7,054,429 | 83 | 2011-08-14T01:36:20Z | [
"python",
"windows"
] | I just downloaded and installed Python 2.7.2 to my laptop and I am trying to run some sample programs. My laptop is running Windows XP.
When I open a `cmd` window and type `python` I get:
> 'python' is not recognized as an internal or external command, operable program or batch file.
I am not a Windows person (mostl... | You need to add the python executable path to your Window's PATH variable.
1. From the desktop, right-click My Computer and click Properties.
2. In the System Properties window, click on the Advanced tab.
3. In the Advanced section, click the Environment Variables button.
4. Highlight the Path variable in the Systems ... |
"python" not recognised as a command | 7,054,424 | 40 | 2011-08-14T01:34:59Z | 18,680,061 | 23 | 2013-09-08T03:20:32Z | [
"python",
"windows"
] | I just downloaded and installed Python 2.7.2 to my laptop and I am trying to run some sample programs. My laptop is running Windows XP.
When I open a `cmd` window and type `python` I get:
> 'python' is not recognized as an internal or external command, operable program or batch file.
I am not a Windows person (mostl... | This is because the Python exec is not in the search path of your operating system. In windows, start CMD. Type in
`setx PATH PythonPath`
where PythonPath is usually `C:\Python27` or `C:\Python33` depending on your Python version. After restarting the CMD, you should get see outcomes when typing
Python --version |
"python" not recognised as a command | 7,054,424 | 40 | 2011-08-14T01:34:59Z | 20,458,629 | 15 | 2013-12-08T20:26:43Z | [
"python",
"windows"
] | I just downloaded and installed Python 2.7.2 to my laptop and I am trying to run some sample programs. My laptop is running Windows XP.
When I open a `cmd` window and type `python` I get:
> 'python' is not recognized as an internal or external command, operable program or batch file.
I am not a Windows person (mostl... | Python comes with a [small utility that fixes this](https://github.com/python/cpython/blob/2.7/Tools/scripts/win_add2path.py). From the command line run:
```
c:\python27\tools\scripts\win_add2path.py
```
Make sure you close the command window (with `exit` or the close button) and open it again. |
Print __file__ without file extension | 7,055,963 | 2 | 2011-08-14T09:08:44Z | 7,055,979 | 11 | 2011-08-14T09:13:21Z | [
"python"
] | Is there a better way to print `__file__` without the extension?
```
import os
print os.path.splitext(__file__)[0]
``` | You can use `string.split`, but what's the point? The standard library is giving you the exact tool you need. |
Python wait until data is in sys.stdin | 7,056,306 | 8 | 2011-08-14T10:37:24Z | 7,056,462 | 16 | 2011-08-14T11:15:36Z | [
"python",
"wait"
] | my problem is the following:
My pythons script receives data via sys.stdin, but it needs to wait until new data is available on sys.stdin.
As described in the manpage from python, i use the following code but it totally overloads my cpu.
```
#!/usr/bin/python -u
import sys
while 1:
for line in sys.stdin.readlin... | The following should just work.
```
import sys
for line in sys.stdin:
# whatever
```
Rationale:
The code will iterate over lines in stdin as they come in. If the stream is still open, but there isn't a complete line then the loop will hang until either a newline character is encountered (and the whole line retur... |
How do I get a set of grammar rules from Penn Treebank using python & NLTK? | 7,056,996 | 11 | 2011-08-14T13:13:35Z | 7,418,247 | 12 | 2011-09-14T14:43:19Z | [
"python",
"parsing",
"grammar",
"nltk",
"tagged-corpus"
] | I'm fairly new to NLTK and Python. I've been creating sentence parses using the toy grammars given in the examples but I would like to know if it's possible to use a grammar learned from a portion of the Penn Treebank, say, as opposed to just writing my own or using the toy grammars? (I'm using Python 2.7 on Mac)
Many ... | If you want a grammar that precisely captures the Penn Treebank sample that comes with NLTK, you can do this, assuming you've downloaded the Treebank data for NLTK (see comment below):
```
import nltk
from nltk.corpus import treebank
from nltk.grammar import ContextFreeGrammar, Nonterminal
tbank_productions = set(pro... |
Python dynamic inheritance: How to choose base class upon instance creation? | 7,057,019 | 30 | 2011-08-14T13:19:07Z | 7,057,905 | 18 | 2011-08-14T15:55:43Z | [
"python",
"oop",
"design-patterns",
"inheritance"
] | # Introduction
I have encountered an interesting case in my programming job that requires me to implement a mechanism of dynamic class inheritance in python. What I mean when using the term "dynamic inheritance" is a class that doesn't inherit from any base class in particular, but rather chooses to inherit from one o... | I would favor composition over inheritance here. I think your current inheritance hierarchy seems wrong. Some things, like opening the file with or gzip have little to do with the actual image format and can be easily handled in one place while you want to separate the details of working with a specific format own clas... |
Python dynamic inheritance: How to choose base class upon instance creation? | 7,057,019 | 30 | 2011-08-14T13:19:07Z | 7,058,640 | 8 | 2011-08-14T17:59:53Z | [
"python",
"oop",
"design-patterns",
"inheritance"
] | # Introduction
I have encountered an interesting case in my programming job that requires me to implement a mechanism of dynamic class inheritance in python. What I mean when using the term "dynamic inheritance" is a class that doesn't inherit from any base class in particular, but rather chooses to inherit from one o... | What about defining the `ImageZIP` class on function-level ?
This will enable your `dynamic inheritance`.
```
def image_factory(path):
# ...
if format == ".gz":
image = unpack_gz(path)
format = os.path.splitext(image)[1][1:]
if format == "jpg":
return MakeImageZip(ImageJP... |
Specific reason why python uses triple-quotation marks for comments? | 7,057,450 | 18 | 2011-08-14T14:44:02Z | 7,057,488 | 55 | 2011-08-14T14:50:46Z | [
"python",
"coding-style",
"comments"
] | Why didn't python just use the traditional style of comments like C/C++/Java uses:
```
/**
* Comment lines
* More comment lines
*/
// line comments
// line comments
//
```
Is there a specific reason for this or is it just arbitrary? | Python doesn't use triple quotation marks for comments. Comments use the hash (a.k.a. pound) character:
```
# this is a comment
```
The triple quote thing is a [doc string](http://www.python.org/dev/peps/pep-0257/), and, unlike a comment, is actually available as a real string to the program:
```
>>> def bla():
... ... |
Specific reason why python uses triple-quotation marks for comments? | 7,057,450 | 18 | 2011-08-14T14:44:02Z | 7,057,521 | 12 | 2011-08-14T14:56:34Z | [
"python",
"coding-style",
"comments"
] | Why didn't python just use the traditional style of comments like C/C++/Java uses:
```
/**
* Comment lines
* More comment lines
*/
// line comments
// line comments
//
```
Is there a specific reason for this or is it just arbitrary? | Triple-quotes aren't comments. They're [string literals](http://docs.python.org/reference/lexical_analysis.html#string-literals) that span multiple lines and include those line breaks in the resulting string. This allows you to use
```
somestr = """This is a rather long string containing
several lines of text just as ... |
Specific reason why python uses triple-quotation marks for comments? | 7,057,450 | 18 | 2011-08-14T14:44:02Z | 7,057,988 | 29 | 2011-08-14T16:09:46Z | [
"python",
"coding-style",
"comments"
] | Why didn't python just use the traditional style of comments like C/C++/Java uses:
```
/**
* Comment lines
* More comment lines
*/
// line comments
// line comments
//
```
Is there a specific reason for this or is it just arbitrary? | A number of the answers got many of the points, but don't give the complete view of how things work. To summarize...
`# comment` is how Python does actual comments (similar to bash, and some other languages). Python only has "to the end of the line" comments, it has no explicit multi-line comment wrapper (as opposed t... |
How to parse a numpy array? | 7,057,487 | 5 | 2011-08-14T14:50:31Z | 7,057,515 | 13 | 2011-08-14T14:56:08Z | [
"python",
"numpy"
] | I have Numpy array:
```
[[12 13 14],[15 16 17],[18 19 20]]
```
How do I get this
```
[[12, 13, 14], [15, 16, 17],[18 ,19, 20]]
``` | When you see a numpy array printed without commas, you are just looking at its string representation. If you want it printed with commas, you could convert it to a Python list:
```
In [45]: print(arr)
[[12 13 14]
[15 16 17]
[18 19 20]]
In [46]: arr_list = arr.tolist()
In [47]: print(arr_list)
[[12, 13, 14], [15, 1... |
Why does Python's tuple not have any method? | 7,057,757 | 3 | 2011-08-14T15:34:33Z | 7,057,768 | 13 | 2011-08-14T15:35:55Z | [
"python",
"tuples"
] | Why does Python's tuple not have any method associated with it? e.g. `tuple.append()`, `tuple.remove()`, etc.?
If the contents of tuple are accessed as we access list items, then why does tuple not have list-related methods? | `tuple`s are immutable, you cannot change their content.
**EDIT** - as commented on the question, and I'm not sure came clear from my answer - there are methods for tuples, but not methods that modify them. |
What's the best way to format a phone number in Python? | 7,058,120 | 12 | 2011-08-14T16:33:54Z | 7,058,216 | 15 | 2011-08-14T16:48:36Z | [
"python",
"formatting",
"format",
"standards",
"libs"
] | If all I have is a string of 10 or more digits, how can I format this as a phone number?
Some trivial examples:
```
555-5555
555-555-5555
1-800-555-5555
```
I know those aren't the only ways to format them, and it's very likely I'll leave things out?if I do it myself. Is there a python library or a standard way of f... | Seems like your examples formatted with three digits groups except last, you can write a simple function, uses thousand seperator and adds last digit:
```
>>> def phone_format(n):
... r... |
What's the best way to format a phone number in Python? | 7,058,120 | 12 | 2011-08-14T16:33:54Z | 7,058,880 | 21 | 2011-08-14T18:40:50Z | [
"python",
"formatting",
"format",
"standards",
"libs"
] | If all I have is a string of 10 or more digits, how can I format this as a phone number?
Some trivial examples:
```
555-5555
555-555-5555
1-800-555-5555
```
I know those aren't the only ways to format them, and it's very likely I'll leave things out?if I do it myself. Is there a python library or a standard way of f... | for library: phonenumbers ([pypi](http://pypi.python.org/pypi/phonenumbers), [source](https://github.com/daviddrysdale/python-phonenumbers))
> Python version of Google's common library for parsing, formatting, storing and validating international phone numbers.
The readme is insufficient, but I found the code is well... |
remove all list elements starting with a hash | 7,058,679 | 2 | 2011-08-14T18:06:28Z | 7,058,690 | 9 | 2011-08-14T18:09:27Z | [
"python"
] | i have a list with elements, some of which start with "#". how can i remove those elements?
I tried:
```
content = [x for x in content[][0] if x != "#"]
```
but:
```
content[][0]
```
seems to be not valid. What is the best way to do this? | ```
content = [x for x in content if not x.startswith('#')]
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.