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 |
|---|---|---|---|---|---|---|---|---|---|
Can str() fail in Python? | 4,857,592 | 4 | 2011-02-01T00:05:16Z | 4,857,603 | 7 | 2011-02-01T00:07:54Z | [
"python"
] | Are there any cases where `str()` throws an exception in Python? | Yes, of course:
```
class A(object):
def __str__(self):
raise Exception
a = A()
str(a)
``` |
Can str() fail in Python? | 4,857,592 | 4 | 2011-02-01T00:05:16Z | 4,857,604 | 13 | 2011-02-01T00:08:15Z | [
"python"
] | Are there any cases where `str()` throws an exception in Python? | Yes, it can fail for custom classes:
```
>>> class C(object):
... def __str__(self):
... return 'oops: ' + oops
...
>>> c = C()
>>> str(c)
NameError: global name 'oops' is not defined
```
It can even fail for some of the built-in classes, such as `unicode`:
```
>>> u = u'\xff'
>>> s = str(u)
UnicodeEncod... |
Main functions, pythonic? | 4,857,899 | 4 | 2011-02-01T01:06:20Z | 4,857,926 | 8 | 2011-02-01T01:10:14Z | [
"python",
"main"
] | I am just getting into Python coding and I'm wondering which is considered more pythonic?
Example A: An obvious main method.
```
#!/usr/bin/env python -tt
import random
def dice_roll(num=1):
for _ in range(num):
print("Rolled a", random.randrange(1,7,1))
def main()
random.seed()
try:
num... | A is better because it allows you to import your module *and* execute the stuff in `main` without having to funk about with things unnecessarily. In fact, that might be a good reason to name it something better than `main` if it really represents an actual function of your module. |
Why does dict have worst case O(n) for so many operations? | 4,857,919 | 3 | 2011-02-01T01:09:08Z | 4,857,937 | 8 | 2011-02-01T01:12:48Z | [
"python"
] | How exactly is dict implemented that it has a linear time lookup for collisions? I would assume that it is implemented as a hashtable backed by a list. I would presume that a better implementation would be O(log(n)) for various operations, using a tree to back the table instead. Is there some magic happening behind the... | Dict is O(1) for most operations, except for operations that touch all elements, such as iteration and copy (in which case, it's obviously O(n)).
See: <http://wiki.python.org/moin/TimeComplexity>
It has O(n) worst case, because you can always contrive a pathological example where all the keys have the same hash value... |
Swapping columns in a numpy array? | 4,857,927 | 25 | 2011-02-01T01:10:42Z | 4,857,981 | 54 | 2011-02-01T01:21:55Z | [
"python",
"numpy"
] | ```
from numpy import *
def swap_columns(my_array, col1, col2):
temp = my_array[:,col1]
my_array[:,col1] = my_array[:,col2]
my_array[:,col2] = temp
```
Then
```
swap_columns(data, 0, 1)
```
Doesn't work. However, calling the code directly
```
temp = my_array[:,0]
my_array[:,0] = my_array[:,1]
my_array[:... | There are two issues here. The first is that the `data` you pass to your function apparently isn't a two-dimensional NumPy array -- at least this is what the error message says.
The second issue is that the code does not do what you expect:
```
my_array = numpy.arange(9).reshape(3, 3)
# array([[0, 1, 2],
# [3,... |
Swapping columns in a numpy array? | 4,857,927 | 25 | 2011-02-01T01:10:42Z | 27,176,146 | 7 | 2014-11-27T17:26:23Z | [
"python",
"numpy"
] | ```
from numpy import *
def swap_columns(my_array, col1, col2):
temp = my_array[:,col1]
my_array[:,col1] = my_array[:,col2]
my_array[:,col2] = temp
```
Then
```
swap_columns(data, 0, 1)
```
Doesn't work. However, calling the code directly
```
temp = my_array[:,0]
my_array[:,0] = my_array[:,1]
my_array[:... | Building up on @Sven's answer:
```
import numpy as np
my_array = np.arange(9).reshape(3, 3)
print my_array
[[0 1 2]
[3 4 5]
[6 7 8]]
def swap_cols(arr, frm, to):
arr[:,[frm, to]] = arr[:,[to, frm]]
swap_cols(my_array, 0, 1)
print my_array
[[1 0 2]
[4 3 5]
[7 6 8]]
def swap_rows(arr, frm, to):
arr[[frm... |
How to list imported modules? | 4,858,100 | 58 | 2011-02-01T01:50:28Z | 4,858,123 | 69 | 2011-02-01T01:54:54Z | [
"python"
] | How to enumerate all imported modules?
E.g. I would like to get ['os', 'sys'] for from this code
```
import os
import sys
``` | ```
import sys
sys.modules.keys()âââ
```
An approximation of getting all imports for the current module only would be to inspect `globals()` for modules:
```
import types
def imports():
for name, val in globals().items():
if isinstance(val, types.ModuleType):
yield val.__name__
```
This... |
How to list imported modules? | 4,858,100 | 58 | 2011-02-01T01:50:28Z | 4,858,169 | 9 | 2011-02-01T02:04:39Z | [
"python"
] | How to enumerate all imported modules?
E.g. I would like to get ['os', 'sys'] for from this code
```
import os
import sys
``` | ```
print [key for key in locals().keys()
if isinstance(locals()[key], type(sys)) and not key.startswith('__')]
``` |
How to list imported modules? | 4,858,100 | 58 | 2011-02-01T01:50:28Z | 19,384,926 | 15 | 2013-10-15T15:17:10Z | [
"python"
] | How to enumerate all imported modules?
E.g. I would like to get ['os', 'sys'] for from this code
```
import os
import sys
``` | Find the intersection of `sys.modules` with `globals`:
```
import sys
modulenames = set(sys.modules)&set(globals())
allmodules = [sys.modules[name] for name in modulenames]
``` |
python 3: class "template" (function that returns a parameterized class) | 4,858,298 | 10 | 2011-02-01T02:28:06Z | 4,858,369 | 7 | 2011-02-01T02:42:43Z | [
"python",
"python-3.x",
"class-design",
"factory-pattern"
] | I am trying to create a function that is passed a parameter `x` and returns a new class `C`. `C` should be a subclass of a fixed base class `A`, with only one addition: a certain class attribute is added and is set to equal `x`.
In other words:
```
class C(A):
C.p = x # x is the parameter passed to the factory func... | First off, note that the term "class factory" is somewhat obsolete in Python. It's used in languages like C++, for a function that returns a dynamically-typed instance of a class. It has a name because it stands out in C++; it's not rare, but it's uncommon enough that it's useful to give the pattern a name. In Python, ... |
Combining a Tokenizer into a Grammar and Parser with NLTK | 4,858,467 | 10 | 2011-02-01T03:06:57Z | 4,860,826 | 10 | 2011-02-01T09:23:24Z | [
"python",
"nlp",
"grammar",
"nltk"
] | I am making my way through the NLTK book and I can't seem to do something that would appear to be a natural first step for building a decent grammar.
My goal is to build a grammar for a particular text corpus.
*(Initial question: Should I even try to start a grammar from scratch or should I start with a predefined gr... | You could run a POS tagger over your text and then adapt your grammar to work on POS tags instead of words.
```
> text = nltk.word_tokenize("A car has a door")
['A', 'car', 'has', 'a', 'door']
> tagged_text = nltk.pos_tag(text)
[('A', 'DT'), ('car', 'NN'), ('has', 'VBZ'), ('a', 'DT'), ('door', 'NN')]
> pos_tags = [p... |
Combining a Tokenizer into a Grammar and Parser with NLTK | 4,858,467 | 10 | 2011-02-01T03:06:57Z | 4,876,291 | 8 | 2011-02-02T15:28:39Z | [
"python",
"nlp",
"grammar",
"nltk"
] | I am making my way through the NLTK book and I can't seem to do something that would appear to be a natural first step for building a decent grammar.
My goal is to build a grammar for a particular text corpus.
*(Initial question: Should I even try to start a grammar from scratch or should I start with a predefined gr... | Parsing is a tricky problem, alot of things can go wrong!
You want (at least) three components here, a tokenizer, a tagger and finally the parser.
First you need to tokenize the running text into a list of tokens. This can be as easy as splitting the input string around whitespace, but if you are parsing more general... |
Combining a Tokenizer into a Grammar and Parser with NLTK | 4,858,467 | 10 | 2011-02-01T03:06:57Z | 11,780,678 | 9 | 2012-08-02T15:18:32Z | [
"python",
"nlp",
"grammar",
"nltk"
] | I am making my way through the NLTK book and I can't seem to do something that would appear to be a natural first step for building a decent grammar.
My goal is to build a grammar for a particular text corpus.
*(Initial question: Should I even try to start a grammar from scratch or should I start with a predefined gr... | I know this is a year later but I wanted to add some thoughts.
I take a lot of different sentences and tag them with parts of speech for a project I'm working on. From there I was doing as StompChicken suggested, pulling the tags from the tuples (word, tag) and using those tags as the "terminals" (the bottom nodes of ... |
Python (and Python C API): __new__ versus __init__ | 4,859,129 | 79 | 2011-02-01T05:07:39Z | 4,859,158 | 22 | 2011-02-01T05:12:44Z | [
"python",
"c",
"python-c-api"
] | The question I'm about to ask seems to be a duplicate of [Python's use of \_\_new\_\_ and \_\_init\_\_?](http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init), but regardless, it's still unclear to me exactly what the practical difference between `__new__` and `__init__` is.
Before you rush to tell me... | `__new__()` can return objects of types other than the class it's bound to. `__init__()` only initializes an existing instance of the class.
```
>>> class C(object):
... def __new__(cls):
... return 5
...
>>> c = C()
>>> print type(c)
<type 'int'>
>>> print c
5
``` |
Python (and Python C API): __new__ versus __init__ | 4,859,129 | 79 | 2011-02-01T05:07:39Z | 4,859,181 | 84 | 2011-02-01T05:16:27Z | [
"python",
"c",
"python-c-api"
] | The question I'm about to ask seems to be a duplicate of [Python's use of \_\_new\_\_ and \_\_init\_\_?](http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init), but regardless, it's still unclear to me exactly what the practical difference between `__new__` and `__init__` is.
Before you rush to tell me... | The difference mainly arises with mutable vs immutable types.
`__new__` accepts a *type* as the first argument, and (usually) returns a new instance of that type. Thus it is suitable for use with both mutable and immutable types.
`__init__` accepts an *instance* as the first argument and modifies the attributes of th... |
Python (and Python C API): __new__ versus __init__ | 4,859,129 | 79 | 2011-02-01T05:07:39Z | 4,859,451 | 29 | 2011-02-01T06:00:22Z | [
"python",
"c",
"python-c-api"
] | The question I'm about to ask seems to be a duplicate of [Python's use of \_\_new\_\_ and \_\_init\_\_?](http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init), but regardless, it's still unclear to me exactly what the practical difference between `__new__` and `__init__` is.
Before you rush to tell me... | There are probably other uses for `__new__` but there's one really obvious one: You can't subclass an immutable type without using `__new__`. So for example, say you wanted to create a subclass of tuple that can contain only integral values between 0 and `size`.
```
class ModularTuple(tuple):
def __new__(cls, tup,... |
Python (and Python C API): __new__ versus __init__ | 4,859,129 | 79 | 2011-02-01T05:07:39Z | 5,143,108 | 11 | 2011-02-28T14:15:48Z | [
"python",
"c",
"python-c-api"
] | The question I'm about to ask seems to be a duplicate of [Python's use of \_\_new\_\_ and \_\_init\_\_?](http://stackoverflow.com/questions/674304/pythons-use-of-new-and-init), but regardless, it's still unclear to me exactly what the practical difference between `__new__` and `__init__` is.
Before you rush to tell me... | Not a complete answer but perhaps something that illustrates the difference.
`__new__` will always get called when an object has to be created. There are some situations where `__init__` will not get called. One example is when you unpickle objects from a pickle file, they will get allocated (`__new__`) but not initia... |
How can I build a polynomial lambda function from an list of coefficients? | 4,859,198 | 2 | 2011-02-01T05:20:13Z | 4,859,257 | 7 | 2011-02-01T05:29:15Z | [
"python",
"function",
"numpy",
"lambda",
"mpmath"
] | I have an list of coefficients that correspond to a polynomial expression, ie: `[1,2,0]` corresponds to `x^2 + 2x + 0`.
I would like to put an arbitrary length array of these coefficients into a lambda function.
Specifically, I am using [mpmath](http://code.google.com/p/mpmath/) and I have a list used for the [polyval... | Do you really need a *lambda* function? Using a "normal" function should be easier:
```
def poly(coeffs):
def calc(x):
result = 0
for c in coeffs:
result = result*x + c
return result
return calc
findroot(poly([1,2,0]))
```
And using that `polyval()` function you mention, something li... |
How to get a random value in python dictionary | 4,859,292 | 61 | 2011-02-01T05:37:05Z | 4,859,322 | 100 | 2011-02-01T05:40:50Z | [
"python",
"random",
"dictionary",
"key"
] | How can I get a random pair from a `dict`? I'm making a game where you need to guess a capital of a country and I need questions to appear randomly.
The `dict` looks like `{'VENEZUELA':'CARACAS'}`
How can I do this? | One way would be:
```
import random
d = {'VENEZUELA':'CARACAS', 'CANADA':'TORONTO'}
random.choice(d.keys())
``` |
How to get a random value in python dictionary | 4,859,292 | 61 | 2011-02-01T05:37:05Z | 21,723,563 | 13 | 2014-02-12T09:22:48Z | [
"python",
"random",
"dictionary",
"key"
] | How can I get a random pair from a `dict`? I'm making a game where you need to guess a capital of a country and I need questions to appear randomly.
The `dict` looks like `{'VENEZUELA':'CARACAS'}`
How can I do this? | If you don't want to use the `random` module, you can also try [popitem()](http://docs.python.org/2/library/stdtypes.html#dict.popitem):
```
>> d = {'a': 1, 'b': 5, 'c': 7}
>>> d.popitem()
('a', 1)
>>> d
{'c': 7, 'b': 5}
>>> d.popitem()
('c', 7)
```
Since the `dict` [doesn't preserve order](http://stackoverflow.com/a... |
How to get a random value in python dictionary | 4,859,292 | 61 | 2011-02-01T05:37:05Z | 32,809,530 | 7 | 2015-09-27T15:25:55Z | [
"python",
"random",
"dictionary",
"key"
] | How can I get a random pair from a `dict`? I'm making a game where you need to guess a capital of a country and I need questions to appear randomly.
The `dict` looks like `{'VENEZUELA':'CARACAS'}`
How can I do this? | I wrote this trying to solve the same problem:
<https://github.com/robtandy/randomdict>
It has O(1) random access to keys, values, and items. |
How to find out the default values of a particular function's argument in another function in Python? | 4,859,993 | 6 | 2011-02-01T07:28:11Z | 4,860,738 | 7 | 2011-02-01T09:14:10Z | [
"python",
"introspection",
"default-parameters"
] | Let's suppose we have a function like this:
```
def myFunction(arg1='a default value'):
pass
```
We can use introspection to find out the names of the arguments that `myFunction()` takes using `myFunction.func_code.co_varnames`, but how to find out the default value of `arg1` (which is `'a default value'` in the ab... | If you define a function `f` like this:
```
>>> def f(a=1, b=True, c="foo"):
... pass
...
```
in Python 2, you can use:
```
>>> f.func_defaults
(1, True, 'foo')
>>> help(f)
Help on function f in module __main__:
f(a=1, b=True, c='foo')
```
whereas in Python 3, it's:
```
>>> f.__defaults__
(1, True, 'foo')
>>> ... |
How to find out the default values of a particular function's argument in another function in Python? | 4,859,993 | 6 | 2011-02-01T07:28:11Z | 4,860,937 | 8 | 2011-02-01T09:36:01Z | [
"python",
"introspection",
"default-parameters"
] | Let's suppose we have a function like this:
```
def myFunction(arg1='a default value'):
pass
```
We can use introspection to find out the names of the arguments that `myFunction()` takes using `myFunction.func_code.co_varnames`, but how to find out the default value of `arg1` (which is `'a default value'` in the ab... | As an alternative to rooting around in the attributes of the function you can use the inspect module for a slightly friendlier interface:
```
import inspect
spec = inspect.getargspec(myFunction)
```
Then spec is an `ArgSpec` object with attributes such as `args` and `defaults`:
```
ArgSpec(args=['arg1'], varargs=Non... |
Placing Custom Images in a Plot Window--as custom data markers or to annotate those markers | 4,860,417 | 22 | 2011-02-01T08:35:44Z | 4,860,777 | 25 | 2011-02-01T09:18:16Z | [
"python",
"matplotlib",
"plot"
] | I have a set of 150x150px png images, and a set of (x, y) coordinates that they correspond to. Is there a way to plot the images on a grid? For example, I'm looking for an R or Python solution to create something like the following:
 | You create a bounding box by instantiating ***AnnotationBbox***--once for each image
that you wish to display; the image and its coordinates are passed to the constructor.
The code is obviously repetitive for the two images, so once that block is put in a function, it's not as long as it seems here.
```
import matplo... |
Placing Custom Images in a Plot Window--as custom data markers or to annotate those markers | 4,860,417 | 22 | 2011-02-01T08:35:44Z | 4,872,190 | 15 | 2011-02-02T08:26:56Z | [
"python",
"matplotlib",
"plot"
] | I have a set of 150x150px png images, and a set of (x, y) coordinates that they correspond to. Is there a way to plot the images on a grid? For example, I'm looking for an R or Python solution to create something like the following:
 | One way to do it in R (2.11.0 and higher):
```
library("png")
# read a sample file (R logo)
img <- readPNG(system.file("img", "Rlogo.png", package="png"))
# img2 <- readPNG(system.file("img", "Rlogo.png", package="png"))
img2 <- readPNG("hand.png", TRUE) # here import a different image
if (exists("rasterImage")) {
... |
I don't know how to make __slots__ work | 4,860,751 | 6 | 2011-02-01T09:15:50Z | 4,860,784 | 8 | 2011-02-01T09:18:39Z | [
"python"
] | How come this code runs for me?
```
class Foo():
__slots__ = []
def __init__(self):
self.should_not_work = "or does it?"
print "This code does not run,",self.should_not_work
Foo()
```
I thought **slots** worked as a restriction. I'm running Python 2.6.6. | The `__slots__` mechanism works for new-style classes. You should inherit from `object`.
Change the class declaration to
```
class Foo(object):
# etc...
``` |
I don't know how to make __slots__ work | 4,860,751 | 6 | 2011-02-01T09:15:50Z | 4,860,866 | 9 | 2011-02-01T09:27:43Z | [
"python"
] | How come this code runs for me?
```
class Foo():
__slots__ = []
def __init__(self):
self.should_not_work = "or does it?"
print "This code does not run,",self.should_not_work
Foo()
```
I thought **slots** worked as a restriction. I'm running Python 2.6.6. | `__slots__` provides a small optimisation of memory use because it can prevent a `__dict__` being allocated to store the instance's attributes. This may be useful if you have a very large number of instances.
The restriction you are talking about is mostly an accidental side effect of the way it is implemented. In par... |
How does one find the currency value in a string? | 4,862,827 | 2 | 2011-02-01T12:55:07Z | 4,862,874 | 13 | 2011-02-01T13:00:45Z | [
"python",
"regex",
"currency"
] | I'm writing a small tool to extract a bunch of values from a string (usually a tweet).
The string could consist of words and numbers along with an amount prefixed by a currency symbol (£,$,⬠etc.) and a number of hashtags (#foo #bar). I'm running on appEngine and using tweepy to bring in the tweets.
The current co... | ```
>>> re.search(ur'([£$â¬])(\d+(?:\.\d{2})?)', s).groups()
(u'\xa3', u'6.50')
```
* `[£$â¬]` matches one currency symbol
* `\d+(?:\.\d{2})` matches one or more digits followed by an optional decimal point followed by exactly two digits
* The `()`'s capture the symbol and amount separately
The problem with your ... |
How to install pywin32 module in windows 7 | 4,863,056 | 19 | 2011-02-01T13:20:26Z | 4,864,271 | 23 | 2011-02-01T15:13:59Z | [
"python",
"c",
"compiler-construction",
"mingw",
"pywin32"
] | I am trying to install pywin32 module. I downloaded it from sourceforge.net. When i run
```
setup.py install
```
It showed "Unable to find vcvarsall.bat". I googled about it and found that I have to install mingW and set path then run
```
python setup.py build --compiler=mingw32
```
but it's showing
```
Can't find... | are you just trying to install it, or are you looking to build from source?
If you just need to install, the easiest way is to use the MSI installers provided here:
<http://sourceforge.net/projects/pywin32/files/pywin32/>
(for updated versions)
make sure you get the correct version (matches Python version, 32bit/64b... |
How to install pywin32 module in windows 7 | 4,863,056 | 19 | 2011-02-01T13:20:26Z | 34,993,224 | 39 | 2016-01-25T12:57:27Z | [
"python",
"c",
"compiler-construction",
"mingw",
"pywin32"
] | I am trying to install pywin32 module. I downloaded it from sourceforge.net. When i run
```
setup.py install
```
It showed "Unable to find vcvarsall.bat". I googled about it and found that I have to install mingW and set path then run
```
python setup.py build --compiler=mingw32
```
but it's showing
```
Can't find... | You can install pywin32 wheel packages from PYPI with PIP by pointing to this package: <https://pypi.python.org/pypi/pypiwin32> No need to worry about first downloading the package, just use pip:
```
pip install pypiwin32
```
Currently I think this is "the easiest" way to get in working :) Hope this helps. |
See class methods in Python console | 4,863,281 | 3 | 2011-02-01T13:42:26Z | 4,863,323 | 8 | 2011-02-01T13:46:00Z | [
"python"
] | If I'm dealing with an object in the Python console, is there a way to see what methods are available for that class? | If by class, you actually meant the instance you have, you can simply use dir:
```
a = list()
print dir(a)
```
If you really meant to see the methods of the class of your object:
```
a = list()
print dir(a.__class__)
```
Note that in that case, both would print the same results, but python being quite dynamic, you ... |
Automatically import models on Django shell launch | 4,863,301 | 19 | 2011-02-01T13:43:56Z | 4,863,340 | 36 | 2011-02-01T13:47:32Z | [
"python",
"django"
] | I'm tired of typing `from account_import.models import ImportFile` every time I open my Django shell. Is there a way to automatically run this command whenever I fire up my shell? | install django-extensions, one of the commands it features (shell\_plus) is providing the context for your models.
<https://github.com/django-extensions/django-extensions>
So, instead of `./manage.py shell` you can use `./manage.py shell_plus` so that everything is imported. |
How can I obtain the model's name or the content type of a Django object? | 4,863,332 | 24 | 2011-02-01T13:46:40Z | 4,863,504 | 35 | 2011-02-01T14:05:19Z | [
"python",
"django",
"django-models",
"content-type"
] | Let's say I am in the save code. How can I obtain the model's name or the content type of the object, and use it?
```
from django.db import models
class Foo(models.Model):
...
def save(self):
I am here....I want to obtain the model_name or the content type of the object
```
This code works, but I hav... | You can get the model name from the object like this:
```
self.__class__.__name__
```
If you prefer the content type, you should be able to get that like this:
```
ContentType.objects.get_for_model(self)
``` |
Make map() return a dictionary | 4,863,406 | 7 | 2011-02-01T13:54:12Z | 4,863,441 | 7 | 2011-02-01T13:57:39Z | [
"python"
] | I have the following function:
```
def heading_positions(self):
return map(
lambda h:
{'{t}.{c}'.format(t=h.table_name,c=h.column_name) : h.position },
self.heading_set.all()
)
```
It gives me output like this:
```
[{'customer.customer_number': 0L}, {'custo... | Why use `map()` then?
```
dict(
('{t}.{c}'.format(t=h.table_name, c=h.column_name), h.position)
for h in self.heading_set.all()
)
```
should work. |
How do I manage third-party Python libraries with Google App Engine? (virtualenv? pip?) | 4,863,557 | 58 | 2011-02-01T14:10:49Z | 4,863,970 | 69 | 2011-02-01T14:48:29Z | [
"python",
"google-app-engine",
"deployment",
"pip",
"egg"
] | What's the best strategy for managing third-party Python libraries with Google App Engine?
Say I want to use Flask, a webapp framework. [A blog entry](http://www.franciscosouza.com/2010/08/flying-with-flask-on-google-app-engine/) says to do this, which doesn't seem right:
```
$ cd /tmp/
$ wget http://pypi.python.org/... | Here's how I do it:
* project
+ .Python
+ bin
+ lib
- python2.5
* site-packages
+ < pip install packages here >
+ include
+ src
- app.yaml
- index.yaml
- main.yaml
- < symlink the pip installed packages in ../lib/python2.5/site-packages
The `project` directory is the top le... |
How do I manage third-party Python libraries with Google App Engine? (virtualenv? pip?) | 4,863,557 | 58 | 2011-02-01T14:10:49Z | 25,564,125 | 41 | 2014-08-29T08:06:44Z | [
"python",
"google-app-engine",
"deployment",
"pip",
"egg"
] | What's the best strategy for managing third-party Python libraries with Google App Engine?
Say I want to use Flask, a webapp framework. [A blog entry](http://www.franciscosouza.com/2010/08/flying-with-flask-on-google-app-engine/) says to do this, which doesn't seem right:
```
$ cd /tmp/
$ wget http://pypi.python.org/... | What about simply:
```
$ pip install -r requirements.txt -t <your_app_directory/lib>
```
Create/edit `<your_app_directory>/appengine_config.py`:
```
"""This file is loaded when starting a new application instance."""
import sys
import os.path
# add `lib` subdirectory to `sys.path`, so our `main` module can load
# t... |
How to subtract dates with python | 4,863,994 | 8 | 2011-02-01T14:51:02Z | 4,864,058 | 20 | 2011-02-01T14:56:39Z | [
"python",
"datetime"
] | Today =
```
today = datetime.datetime.now().strftime("%Y%m%d")
```
90days ago
```
DD = datetime.timedelta(days=-90)
```
How do I get today - DD, or 90days ago? | You should be able to subtract time deltas from datetime objects.
```
today = datetime.datetime.now()
DD = datetime.timedelta(days=90)
earlier = today - DD
earlier_str = earlier.strftime("%Y%m%d")
``` |
How to subtract dates with python | 4,863,994 | 8 | 2011-02-01T14:51:02Z | 4,864,084 | 10 | 2011-02-01T14:58:33Z | [
"python",
"datetime"
] | Today =
```
today = datetime.datetime.now().strftime("%Y%m%d")
```
90days ago
```
DD = datetime.timedelta(days=-90)
```
How do I get today - DD, or 90days ago? | Just subtract a timedelta from a datetime:
```
>>> import datetime
>>> today = datetime.datetime.today()
>>> DD = datetime.timedelta(days=90)
>>> today - DD
datetime.datetime(2010, 11, 3, 9, 56, 20, 924224)
```
(or if you want to use a negative timedelta like you did there, add them:
```
>>> DD = datetime.timedelta(... |
Using python, how to read a file starting at the seventh line ? | 4,864,361 | 8 | 2011-02-01T15:22:05Z | 4,866,330 | 19 | 2011-02-01T18:12:40Z | [
"python",
"file-io"
] | I have a text file structure as:
```
date
downland
user
date data1 date2
201102 foo bar 200 50
201101 foo bar 300 35
```
So first six lines of file are not needed. filename:dnw.txt
```
f = open('dwn.txt', 'rb')
```
How do I "split" this file starting at line 7 to EOF? | ```
with open('dwn.txt') as f:
for i in xrange(6):
f.next()
for line in f:
process(line)
``` |
Retrying tasks with Django-Celery - Django/Celery | 4,864,657 | 18 | 2011-02-01T15:45:58Z | 4,903,502 | 12 | 2011-02-04T22:15:23Z | [
"python",
"django",
"scheduled-tasks",
"celery",
"django-celery"
] | I'm having problems retrying tasks, here is what a test task looks like
```
from celery.decorators import task
@task()
def add(x, y):
if not x or not y:
raise Exception("test error")
return x+y
```
I cannot find any documentation what-so-ever on how to retry decorated tasks, all I found was this:
``... | The task needs to accept keyword arguments, they are used to pass information amongst other about the retry count. I think the code should look like this:
```
from celery.decorators import task
@task()
def add(x, y, **kwargs):
if not x or not y:
try:
raise Exception("test error")
excep... |
Retrying tasks with Django-Celery - Django/Celery | 4,864,657 | 18 | 2011-02-01T15:45:58Z | 15,201,812 | 22 | 2013-03-04T12:39:09Z | [
"python",
"django",
"scheduled-tasks",
"celery",
"django-celery"
] | I'm having problems retrying tasks, here is what a test task looks like
```
from celery.decorators import task
@task()
def add(x, y):
if not x or not y:
raise Exception("test error")
return x+y
```
I cannot find any documentation what-so-ever on how to retry decorated tasks, all I found was this:
``... | You can set your retry parameters in the decorator:
```
@task(default_retry_delay=5 * 60, max_retries=12)
def foo(bar):
try:
...
except Exception, exc:
raise foo.retry(exc=exc)
``` |
How to use PIL with PyPy? | 4,864,674 | 8 | 2011-02-01T15:47:02Z | 4,864,999 | 12 | 2011-02-01T16:15:09Z | [
"python",
"python-imaging-library",
"pypy"
] | I searched a little bit but I couldn't find a tuto to use PIL with PyPy. According to PyPy's blog, PIL is supported.
* I installed PIL with pip in my PYTHONPATH.
* After the download, pip make 2 .pyd files: \_imaging.pyd and \_imagingmath.pyd.
* After the install, I copied %PYTHONPATH%/lib/site-packages/PIL to my PyPy... | I did this:
```
$ /opt/pypy-1.4.1/bin/virtualenv test
$ cd test
$ bin/pip install PIL
...
--------------------------------------------------------------------
PIL 1.1.7 SETUP SUMMARY
--------------------------------------------------------------------
version 1.1.7
platform linux2 2.5.2 (e503e483e9ac, Dec 2... |
How do I test beginner student Python programs that use input() (maybe with unittest?)? | 4,865,195 | 5 | 2011-02-01T16:30:34Z | 4,865,282 | 7 | 2011-02-01T16:39:16Z | [
"python",
"unit-testing",
"testing",
"pyunit"
] | I'm a grader for a beginning programming class using Python. My python-fu is not so strong myself, but I would like to try to automate some of the grading.
Looking online, I like the [PyUnit](http://docs.python.org/py3k/library/unittest.html) testing suite, though it probably is a bit overpowered for what I want.
My ... | Edit: Only proposing this since the example isn't unittest-able (and I'm assuming the beginner students will just be confused by the constraint)
If you are just concerned with the output matching what you are looking for, why not just use some "silly" bash? Something like:
```
echo -e "2\n3" | python test.py | grep -... |
Counting collisions in a Python dictionary | 4,865,325 | 13 | 2011-02-01T16:42:33Z | 4,867,536 | 8 | 2011-02-01T20:21:33Z | [
"python",
"optimization",
"dictionary"
] | my first time posting here, so hope I've asked my question in the right sort of way,
After adding an element to a Python dictionary, is it possible to get Python to tell you if adding that element caused a collision? (And how many locations the collision resolution strategy probed before finding a place to put the ele... | **Short answer:**
You can't simulate using object ids as dict keys by using random integers as dict keys. They have different hash functions.
Collisions do happen. "Having unique thingies means no collisions" is wrong for several values of "thingy".
You shouldn't be worrying about collisions.
**Long answer:**
Some... |
'No write' variable in Python | 4,865,485 | 2 | 2011-02-01T16:55:54Z | 4,865,503 | 13 | 2011-02-01T16:57:21Z | [
"python",
"matlab"
] | In MATLAB you have the ability to return tuples and assign to tuples of values the same as you do so in Python. In MATLAB, if a function returns a value you don't want to assign to anything, you assign it to the special variable `~`. For example, say a function `f()` returns a tuple `(1, 2)`, then:
```
~, b = f()
```
... | A common idiom in Python is to use `_` for this purpose.
However it's not necessarily a good idea because this variable is also used in the interactive interpreter for the last result and assigning to it will stop this useful feature from working.
Also `_` is sometimes used for string translation, e.g. with [`gettext... |
'No write' variable in Python | 4,865,485 | 2 | 2011-02-01T16:55:54Z | 4,865,520 | 10 | 2011-02-01T16:58:57Z | [
"python",
"matlab"
] | In MATLAB you have the ability to return tuples and assign to tuples of values the same as you do so in Python. In MATLAB, if a function returns a value you don't want to assign to anything, you assign it to the special variable `~`. For example, say a function `f()` returns a tuple `(1, 2)`, then:
```
~, b = f()
```
... | Alternatively you can always just return the part of the tuple, you are interested in:
```
b = f()[1]
``` |
Does pyGame do 3d? | 4,865,636 | 20 | 2011-02-01T17:08:43Z | 4,865,751 | 14 | 2011-02-01T17:19:18Z | [
"python",
"3d",
"pygame"
] | I can't seem to find the answer to this question anywhere. I realise that you have to use pyOpenGL or something similar to do openGL stuff, but I was wondering if its possible to do very basic 3d graphics without any other dependencies. | No, Pygame is a wrapper for SDL, which is a 2D api. Pygame doesn't provide any 3D capability and probably never will.
3D libraries for Python include [Panda3D](http://www.panda3d.org/) and [DirectPython](http://directpython11.sourceforge.net/), although they are probably quite complex to use, especially the latter. |
Does pyGame do 3d? | 4,865,636 | 20 | 2011-02-01T17:08:43Z | 4,865,764 | 11 | 2011-02-01T17:20:25Z | [
"python",
"3d",
"pygame"
] | I can't seem to find the answer to this question anywhere. I realise that you have to use pyOpenGL or something similar to do openGL stuff, but I was wondering if its possible to do very basic 3d graphics without any other dependencies. | Well, if you can do 2d you can always do 3d. All 3d really is is skewed 2 dimensional surfaces giving the impression you're looking at something with depth. The real question is can it do it well, and would you even want to. After browsing the pyGame documentation for a while, it looks like it's just an SDL wrapper. SD... |
Deepcopy on nested referenced lists created by list multiplication does not work | 4,865,821 | 3 | 2011-02-01T17:25:13Z | 4,865,847 | 9 | 2011-02-01T17:27:17Z | [
"python",
"list",
"nested",
"multiplication",
"deep-copy"
] | As much as I love Python, the reference and deepcopy stuff sometimes freaks me out.
Why does deepcopy not work here:
```
>>> import copy
>>> a = 2*[2*[0]]
>>> a
[[0, 0], [0, 0]]
>>> b = copy.deepcopy(a)
>>> b[0][0] = 1
>>> b
[[1, 0], [1, 0]] #should be: [[1, 0], [0, 1]]
>>>
```
I am using a numpy array as a work... | It doesn't work because you are creating an array with two references to the same array.
An alternative approach is:
```
[[0]*2 for i in range(2)]
```
Or the more explicit:
```
[[0 for j in range(2)] for i in range(2)]
```
This works because it creates a new array on each iteration.
> Are there any more traps whe... |
Deepcopy on nested referenced lists created by list multiplication does not work | 4,865,821 | 3 | 2011-02-01T17:25:13Z | 4,865,900 | 7 | 2011-02-01T17:32:01Z | [
"python",
"list",
"nested",
"multiplication",
"deep-copy"
] | As much as I love Python, the reference and deepcopy stuff sometimes freaks me out.
Why does deepcopy not work here:
```
>>> import copy
>>> a = 2*[2*[0]]
>>> a
[[0, 0], [0, 0]]
>>> b = copy.deepcopy(a)
>>> b[0][0] = 1
>>> b
[[1, 0], [1, 0]] #should be: [[1, 0], [0, 1]]
>>>
```
I am using a numpy array as a work... | It works exactly as you have expected.
a = 2\*[2\*[0]]
When you multiply `[[0,0]]` with `2 *`, both elements of the new list will point to the SAME `[0,0]` list. `a[0]` and `a[1]` are the same list, because the reference is copied, not the data (which would be impossible). Changing the first element of one of them ch... |
What is the difference between the various ZODB blobstorage layouts? | 4,866,646 | 5 | 2011-02-01T18:46:43Z | 4,866,720 | 7 | 2011-02-01T18:54:03Z | [
"python",
"zope",
"zodb"
] | The ZODB blobstorage directory contains a .layout file with the string 'lawn', 'bushy'.
What is the difference between the various blob storage directory formats? | It is explained here: <http://svn.zope.org/ZODB/trunk/src/ZODB/tests/blob_layout.txt?rev=101802&view=markup>
FTA:
> ======================
>
> # Blob directory layouts
>
> The internal structure of the blob directories is governed by so called
> `layouts`. The current default layout is called `bushy`.
>
> The origina... |
Python PyGILState_{Ensure/Release} causes segfault while returning to C++ from Python code | 4,866,701 | 8 | 2011-02-01T18:52:12Z | 4,870,857 | 8 | 2011-02-02T04:45:59Z | [
"c++",
"python",
"multithreading",
"segmentation-fault",
"gnuradio"
] | **UPDATE** Well, it looks like adding PyEval\_InitThreads() before the call to PyGILState\_Ensure() does the trick. In my haste to figure things out I incorrectly attributed my "hanging" to PyEval\_InitThreads().
However, after reading some Python documentation I am wondering if this is the correct solution.
> It is ... | Python expects a certain amount of initialisation to be done by the main thread before anything attempts to call back in from a subthread.
If the main thread is an application that is embedding Python, then it should call PyEval\_InitThreads() immediately after calling Py\_Initialize().
If the main thread is instead ... |
Python PyGILState_{Ensure/Release} causes segfault while returning to C++ from Python code | 4,866,701 | 8 | 2011-02-01T18:52:12Z | 4,975,906 | 7 | 2011-02-12T02:19:54Z | [
"c++",
"python",
"multithreading",
"segmentation-fault",
"gnuradio"
] | **UPDATE** Well, it looks like adding PyEval\_InitThreads() before the call to PyGILState\_Ensure() does the trick. In my haste to figure things out I incorrectly attributed my "hanging" to PyEval\_InitThreads().
However, after reading some Python documentation I am wondering if this is the correct solution.
> It is ... | I ran into this exact problem as well. The documentation for anything relating to threads in CPython is unfortunately patchy at best.
Essentially, you need to do the following:
In your *main* thread, ***BEFORE*** any other threads are spawned, you need to call `PyEval_InitThreads()`. A good place to do this is right ... |
Django: css referencing media in static files (django dev / 1.3 / static files) | 4,867,037 | 13 | 2011-02-01T19:25:46Z | 4,867,340 | 19 | 2011-02-01T19:57:16Z | [
"python",
"html",
"css",
"django",
"django-1.3"
] | Like any other user of django user I serve static files. I've chosen to use [django-staticfiles](http://pypi.python.org/pypi/django-staticfiles/1.0a2#downloads) to be ready for django 1.3 which will basically integrate it [into the core](http://docs.djangoproject.com/en/dev/howto/static-files/).
My question is pretty ... | You said you had trouble with relative paths, but I don't understand exactly what you meant.
I ran into the same issue, and I've used relative paths to solve it. The only thing to keep in mind is that when deploying the images need to (obviously) remain in the same path relative to the CSS files.
**My setup in a nuts... |
Failed loading english.pickle with nltk.data.load | 4,867,197 | 56 | 2011-02-01T19:43:48Z | 10,852,888 | 120 | 2012-06-01T15:12:26Z | [
"python",
"nltk"
] | ```
import nltk.data
tokenizer = nltk.data.load('nltk:tokenizers/punkt/english.pickle')
```
this is my code
error:
```
> Traceback (most recent call last): File "E:\Program Files\eclipse\Martin
> Project Folder\labs2\src\test.py",
> line 2, in <module>
> tokenizer = nltk.data.load('nltk:tokenizers/punk... | I had this same problem. Go into a python shell and type:
```
>>> import nltk
>>> nltk.download()
```
Then an installation window appears. Go to the 'Models' tab and select 'punkt' from under the 'Identifier' column. Then click Download and it will install the necessary files. Then it should work! |
Failed loading english.pickle with nltk.data.load | 4,867,197 | 56 | 2011-02-01T19:43:48Z | 27,706,667 | 33 | 2014-12-30T13:50:10Z | [
"python",
"nltk"
] | ```
import nltk.data
tokenizer = nltk.data.load('nltk:tokenizers/punkt/english.pickle')
```
this is my code
error:
```
> Traceback (most recent call last): File "E:\Program Files\eclipse\Martin
> Project Folder\labs2\src\test.py",
> line 2, in <module>
> tokenizer = nltk.data.load('nltk:tokenizers/punk... | ```
import nltk
nltk.download('punkt')
from nltk import word_tokenize,sent_tokenize
```
Use tokenizers :) |
Failed loading english.pickle with nltk.data.load | 4,867,197 | 56 | 2011-02-01T19:43:48Z | 31,471,008 | 9 | 2015-07-17T08:00:45Z | [
"python",
"nltk"
] | ```
import nltk.data
tokenizer = nltk.data.load('nltk:tokenizers/punkt/english.pickle')
```
this is my code
error:
```
> Traceback (most recent call last): File "E:\Program Files\eclipse\Martin
> Project Folder\labs2\src\test.py",
> line 2, in <module>
> tokenizer = nltk.data.load('nltk:tokenizers/punk... | This is what worked for me just now:
```
# Do this in a separate python interpreter session, since you only have to do it once
import nltk
nltk.download('punkt')
# Do this in your ipython notebook or analysis script
from nltk.tokenize import word_tokenize
sentences = [
"Mr. Green killed Colonel Mustard in the st... |
Does the 'in' clause used on python dictionaries call the keys() function every time? | 4,867,341 | 5 | 2011-02-01T19:57:20Z | 4,867,389 | 10 | 2011-02-01T20:02:34Z | [
"python",
"optimization",
"dictionary"
] | Let's say I have a
```
dict = {...} #lots of words in dictionary
```
I have to do a
```
for word in ...: #long list of words
if word in dict:
#do something
```
My question is, does the 'if word in dict' call the dict.keys() function every time and hence a lot slower than if I added another variable at t... | no. `foo in mydict` is in fact **a lot faster** than `foo in keys_list`, since `dict`s are hash tables, so finding the element inside it is `O(1)`. While foo in `keys_list` would be `O(n)` (slower as the number of keys grows bigger)
But you could always test yourself:
```
$ python -m timeit -s "x = range(1000)" "15 i... |
I'm looking for gevent for Python 2.7 for windows | 4,867,750 | 6 | 2011-02-01T20:44:12Z | 7,760,010 | 9 | 2011-10-13T20:24:03Z | [
"python",
"gevent",
"greenlets"
] | However gevent depends upon greenlet and the .msi version I found fails to install and the egg for 2.6 refuses to install.
The msi version fails as follows.
```
C:\Windows\system32>easy_install greenlet
install_dir C:\Python27\Lib\site-packages\
Searching for greenlet
Reading http://pypi.python.org/simple/greenlet/
R... | This worked for me:
1. Grab the gevent installer from the [Unofficial Windows Binaries for Python Extension Packages](http://www.lfd.uci.edu/~gohlke/pythonlibs/)
2. Install greenlet from that same site
And if you're on a 64-bit Windows 7 machine and are having trouble installing, [read this too](http://stackoverflow.... |
How can you obtain the OS's argv[0] (not sys.argv[0]) in Python? | 4,867,761 | 9 | 2011-02-01T20:44:52Z | 4,867,889 | 7 | 2011-02-01T21:02:24Z | [
"python"
] | I want to obtain the true value of the operating system's argv[0] in a Python program. Python's sys.argv[0] is not this value: it is the name of the Python script being executed (with some exceptions). What I want is a foo.py that will print "somestring" when executed as
```
exec -a "somestring" python foo.py
```
The... | On Linux you can read the contents of `/proc/self/cmdline`:
```
#!/usr/bin/env python
import sys
print sys.argv[0]
f = open('/proc/self/cmdline', 'rb')
cmdline = f.read()
f.close()
print repr(cmdline.split('\x00'))
```
And the output is:
```
$ bash
$ exec -a "somestring" python foo.py
foo.py
['somestring', 'foo.p... |
How to make Django QuerySet bulk delete() more efficient | 4,867,852 | 20 | 2011-02-01T20:58:03Z | 4,868,356 | 11 | 2011-02-01T21:50:52Z | [
"python",
"django",
"orm"
] | Setup:
Django 1.1.2, MySQL 5.1
Problem:
```
Blob.objects.filter(foo = foo) \
.filter(status = Blob.PLEASE_DELETE) \
.delete()
```
This snippet results in the ORM first generating a `SELECT * from xxx_blob where ...` query, then doing a `DELETE from xxx_blob where id in (BLAH);` where BLAH i... | Not without writing your own custom SQL or managers or something; they are apparently working on it though.
<http://code.djangoproject.com/ticket/9519> |
How to install PIL on Mac OSX 10.5.8 for Google App Engine? | 4,868,185 | 19 | 2011-02-01T21:31:41Z | 5,506,864 | 20 | 2011-03-31T22:02:00Z | [
"python",
"google-app-engine",
"osx",
"python-imaging-library",
"osx-leopard"
] | I need to get PIL installed locally to test GAE's images api in my local environment.
I grabbed the PIL 1.1.6 installer for Mac, and when I go to select the destination (when installing), I get the error:
```
You cannot install PIL 1.1.6 on this volume.
PIL requires System Python 2.5 to install.
```
I have Python 2... | That's quite easy:
1. Install [MacPorts](http://distfiles.macports.org/MacPorts/MacPorts-1.9.2-10.5-Leopard.dmg)
2. Install *Python 2.5* with `sudo port install python25`
3. Install *Pil for Python 2.5* with `sudo port install py25-pil`
4. In the Google App Engine launcher Preferences set `/opt/local/bin/python2.5` as... |
How to pivot data in a csv file? | 4,869,189 | 6 | 2011-02-01T23:29:39Z | 4,869,245 | 23 | 2011-02-01T23:36:35Z | [
"python",
"csv",
"transpose"
] | For example, i would like to transform:
```
Name,Time,Score
Dan,68,20
Suse,42,40
Tracy,50,38
```
Into:
```
Name,Dan,Suse,Tracy
Time,68,42,50
Score,20,40,38
```
EDIT: the original question used the term "transpose" incorrectly. | If the whole file contents fits into memory, you can use
```
import csv
from itertools import izip
a = izip(*csv.reader(open("input.csv", "rb")))
csv.writer(open("output.csv", "wb")).writerows(a)
```
You can basically think of `zip()` and `izip()` as transpose operations:
```
a = [(1, 2, 3),
(4, 5, 6),
(7,... |
Why does Python assignment not return a value? | 4,869,770 | 22 | 2011-02-02T01:07:01Z | 4,869,838 | 26 | 2011-02-02T01:17:17Z | [
"python",
"python-3.x",
"language-design"
] | Why is Python assignment a statement rather than an expression? If it was an expression which returns the value of the right hand side in the assignment, it would have allowed for much less verbose code in some cases. Are there any issues I can't see?
For example:
```
# lst is some sequence
# X is come class
x = X()
... | There are many who feel that having assignments be expressions, especially in languages like Python where *any* value is allowable in a condition (not just values of some boolean type), is error-prone. Presumably Guido is/was among those who feel that way. The classic error is:
```
if x = y: # oops! meant to say ==
``... |
E-Mail Site Admins in Django without using mail_admins() | 4,869,832 | 2 | 2011-02-02T01:16:41Z | 4,869,905 | 8 | 2011-02-02T01:29:15Z | [
"python",
"django"
] | I know this sounds kind of stupid, but as a beginner in Django (and even Python), I just want to know how I can access the email address from the ADMINS tuple, or maybe even access the admin name.
I read that tuples are semantic, kind of like lightweight structs. So if that's the case, I may be able to access those se... | `ADMINS` is a setting. You can access it as follows:
```
from django.conf import settings
settings.ADMINS
```
For example, to get all the email addresses as a list:
```
from django.conf import settings
admin_emails = [v for k,v in settings.ADMINS]
```
The settings docs:
<http://docs.djangoproject.com/en/1.2/topics/... |
Set Hudson Build Description via Web API | 4,870,187 | 5 | 2011-02-02T02:23:48Z | 4,870,426 | 7 | 2011-02-02T03:10:11Z | [
"python",
"hudson",
"hudson-api"
] | I have a Python script that operates on Hudson builds and would love to be able to set the description of a build programmatically.
I can click "Add Description" on a build's page and fill in the form, how can I POST some data to the same URL that form does? | Figured it out, need to POST the following as form data (content type `application/x-www-form-urlencoded`) to
<http://myserver/hudson/job/thebuild/10/submitDescription>
```
{"description": "Some Description for the build"}
```
In code:
```
def set_description(build_url, desc):
req_data = urllib.urlencode({'desc... |
rotating coordinate system via a quaternion | 4,870,393 | 13 | 2011-02-02T03:04:58Z | 4,870,905 | 40 | 2011-02-02T04:55:18Z | [
"python",
"math"
] | We have a gazillion spatial coordinates (x, y and z) representing atoms in 3d space, and I'm constructing a function that will translate these points to a new coordinate system. Shifting the coordinates to an arbitrary origin is simple, but I can't wrap my head around the next step: 3d point rotation calculations. In o... | Using quaternions to represent rotation is not difficult from an algebraic point of view. Personally, I find it hard to reason *visually* about quaternions, but the formulas involved in using them for rotations are quite simple. I'll provide a basic set of reference functions here; see [this page](http://content.gpwiki... |
Django - enforcing ManyToManyField unique items | 4,870,935 | 16 | 2011-02-02T05:00:18Z | 4,871,050 | 8 | 2011-02-02T05:23:55Z | [
"python",
"django",
"django-models"
] | I'm trying to do something simple like this:
```
members = models.ManyToManyField(User,blank=True,null=True,unique=True)
```
but unique isn't allowed. When looking at the table created, it makes foreign keys so uniqueness is implied I imagine.
I want to be able to associate members with this model representing a gro... | > Duplicate users don't appear in the admin utility.
They're not created.
> Does add() fail silently?
Yes.
> Should I just simply check if the user is contained already before adding?
Yes. Or instead of manually counting the users, you could just have the database count for you:
```
mygroup = Group.objects.filter... |
Django - enforcing ManyToManyField unique items | 4,870,935 | 16 | 2011-02-02T05:00:18Z | 4,871,075 | 17 | 2011-02-02T05:26:56Z | [
"python",
"django",
"django-models"
] | I'm trying to do something simple like this:
```
members = models.ManyToManyField(User,blank=True,null=True,unique=True)
```
but unique isn't allowed. When looking at the table created, it makes foreign keys so uniqueness is implied I imagine.
I want to be able to associate members with this model representing a gro... | For one, I wouldn't use `num_members`. Instead, you can check how many members there are with `mygroup.members.count()`. Secondly, adding members more than once doesn't really add them more than once, so you're fine.
A `ManyToManyField` on `Group` for `member` pointing to `User` is implemented with a separate table (s... |
MySQL-python Cannot connect to server | 4,871,147 | 7 | 2011-02-02T05:39:49Z | 4,871,330 | 15 | 2011-02-02T06:17:19Z | [
"python",
"mysql"
] | This is driving me crazy.
I have Python 2.5 and MySQL-python-1.2.3 from the .exe available [here](http://www.lfd.uci.edu/~gohlke/pythonlibs/) installed on Vista.
I have been making `.php` pages over the past few weeks and connected fine in order to test them in my browser.
```
$dbcnx=@mysql_connect("localhost", "roo... | Don't use the windows version (all my relevant experience is on Linux), but I'd be willing to bet it will work if you use `127.0.0.1` in place of `localhost`.
Edit: -- a bit of explanation.
Firstly, check the entries in `mysql`.`user` table, for the `host` field (although by default, you probably have three entries f... |
Python error: AttributeError: 'module' object has no attribute | 4,871,369 | 22 | 2011-02-02T06:22:24Z | 4,871,671 | 21 | 2011-02-02T07:11:40Z | [
"python",
"package"
] | I'm totally new to Python and I know this question was asked many times, but unfortunately it seems that my situation is a bit different...
I have created a package (or so I think). The catalog tree is like this:
```
mydir
lib (__init__.py)
mod1 (__init__.py, mod11.py)
```
In parenthesis there are files in... | When you `import lib`, you're importing the package. The only file to get evaluated and run in this case is the 0 byte `__init__.py` in the lib directory.
If you want access to your function, you can do something like this `from lib.mod1 import mod1` and then run the `mod12` function like so `mod1.mod12()`.
If you wa... |
Python error: AttributeError: 'module' object has no attribute | 4,871,369 | 22 | 2011-02-02T06:22:24Z | 4,871,715 | 16 | 2011-02-02T07:17:26Z | [
"python",
"package"
] | I'm totally new to Python and I know this question was asked many times, but unfortunately it seems that my situation is a bit different...
I have created a package (or so I think). The catalog tree is like this:
```
mydir
lib (__init__.py)
mod1 (__init__.py, mod11.py)
```
In parenthesis there are files in... | More accurately, your `mod1` and `lib` directories are not modules, they are packages. The file `mod11.py` is a module.
Python does not automatically import subpackages or modules. You have to explicitly do it, or "cheat" by adding import statements in the initializers.
```
>>> import lib
>>> dir(lib)
['__builtins__'... |
Experience with using h5py to do analytical work on big data in Python? | 4,871,670 | 46 | 2011-02-02T07:11:38Z | 4,874,742 | 48 | 2011-02-02T12:59:43Z | [
"python",
"scipy",
"sas",
"hdf5",
"h5py"
] | I do a lot of statistical work and use Python as my main language. Some of the data sets I work with though can take 20GB of memory, which makes operating on them using in-memory functions in numpy, scipy, and PyIMSL nearly impossible. The statistical analysis language SAS has a big advantage here in that it can operat... | We use Python in conjunction with h5py, numpy/scipy and boost::python to do data analysis. Our typical datasets have sizes of up to a few hundred GBs.
HDF5 advantages:
* data can be inspected conveniently using the h5view application, h5py/ipython and the h5\* commandline tools
* APIs are available for different plat... |
Where does this come from: -*- coding: utf-8 -*- | 4,872,007 | 61 | 2011-02-02T08:01:23Z | 4,872,242 | 43 | 2011-02-02T08:33:44Z | [
"python",
"file",
"text",
"encoding",
"emacs"
] | Python recognizes the following as instruction which defines file's encoding:
```
# -*- coding: utf-8 -*-
```
I definitely saw this kind of instructions before (`-*- var: value -*-`). Where does it come from? What is the full specification, e.g. can the value include spaces, special symbols, newlines, even `-*-` itse... | This way of specifying the encoding of a Python file comes from [PEP 0263 - Defining Python Source Code Encodings](http://www.python.org/dev/peps/pep-0263/).
It is also recognized by GNU Emacs (see [Python Language Reference, 2.1.4 Encoding declarations](http://www.network-theory.co.uk/docs/pylang/Encodingdeclarations... |
how to Add New column in beginning of CSV file by Python | 4,872,077 | 4 | 2011-02-02T08:10:41Z | 4,873,050 | 11 | 2011-02-02T10:07:41Z | [
"python"
] | I have one csv file in which i have 6 to 8 column.
Ex:
```
ID Test Description file-name module view path1 path2
```
I want to add new column (Node) in the beginning.
Ex:
```
Node ID Test Description file-name module view path1 path2
```
I am new to python please help me out. | It would be fairly easy to do using the `csv` module's `DictReader` and `DictWriter` classes. Here's an example that reads the old file and writes the new one in single pass.
A `DictReader` instance returns each logical line or row of the file as a dictionary whose keys are the field names. You can explicitly specify ... |
List directory file contents in a Django template | 4,872,183 | 7 | 2011-02-02T08:25:01Z | 4,872,325 | 11 | 2011-02-02T08:43:33Z | [
"python",
"django",
"filesystems",
"django-templates",
"repository"
] | I'm just learning Python & Django. (Thanks to everyone who contributes here -- it's been an invaluable resource!)
One seemingly basic thing that I'm having trouble with is rendering a simple list of static files (say the contents of a single repository directory on my server) as a list of downloadable links. Whether t... | Something very much not like that, I reckon.
You'll probably need to create a function of your own inside views.py - see tutorial.
That function will get the file list from os.listdir into a list.
Pass that list in the context to a template and do render\_to\_response with a template you've written - see tutorial.
... |
Find speed of vehicle from images | 4,872,570 | 8 | 2011-02-02T09:17:08Z | 4,875,196 | 10 | 2011-02-02T13:48:49Z | [
"python",
"image-processing",
"opencv",
"performance",
"opticalflow"
] | I am doing a project to find the speed of a vehicle from images. We are taking these images from within the vehicle. We will be marking some object from the 1st image as a reference. Using the properties of the same object in the next image, we must calculate the speed of the moving vehicle. Can anyone help me here??? ... | Knowing the acquisition frequency, you must now find the distance between the successive positions of the marker.
To find this distance, I suggest you estimate the *pose* of the marker for each image. Loosely speaking, the "pose" is the transformation matrix expressing the coordinates of an object relative to a camera... |
Cythonize a Python function to make it faster | 4,872,715 | 11 | 2011-02-02T09:33:08Z | 5,033,066 | 7 | 2011-02-17T18:37:33Z | [
"python",
"performance",
"cython"
] | Few weeks ago I asked a question on increasing the speed of a function written in Python. At that time, TryPyPy brought to my attention the possibility of using Cython for doing so. He also kindly gave an example of how I could Cythonize that code snippet. I want to do the same with the code below to see how fast I can... | As a general note, you can see exactly what C code Cython generates for every source line by running the `cython` command with the `-a` "annotate" option. See the Cython [documentation](http://docs.cython.org/src/userguide/language_basics.html?highlight=annotate) for examples. This is *extremely* helpful when trying to... |
What is the simplest way to create a shaped window in wxPython? | 4,873,063 | 5 | 2011-02-02T10:08:04Z | 4,879,656 | 8 | 2011-02-02T20:45:58Z | [
"python",
"wxpython",
"shaped-window"
] | I'd like to create a simple shaped window in wxPython. More or less I want to do the wx equivalent to Tkinter's **self.overrideredirect(1)** (It get's rid of the default OS boarder), then round the corners on the window. | There's a shaped frame demo in the wxPython demos. I apologize for the indirect source. They originally came as a windows installer [here](http://sourceforge.net/projects/wxpython/files/wxPython/2.8.11.0/wxPython2.8-win32-docs-demos-2.8.11.0.exe/download):
[source code](http://wxwidgets2.8.sourcearchive.com/documentat... |
Unsupported characters in input | 4,873,543 | 4 | 2011-02-02T10:54:54Z | 4,873,927 | 7 | 2011-02-02T11:31:53Z | [
"python",
"unicode",
"python-2.x"
] | I want to assign a string of characters to a variable but it says
```
: there isn't a "code to show.
```
I have a string that i want to assign to a variable
```
d="stunning:/ÃstÃnêÃ
/"
Unsupported characters in input
```
or
```
word="stuning:/ËstraɪkɪÅ/"
Unsupported characters in input
```
so basically t... | Set the source file encoding accordingly to the actual encoding of the file, so that the interpreter knows how to parse it.
For instance, if you use UTF-8, just add this string to the header of the file:
```
# -*- coding: utf8 -*-
```
It must be the first or the second line of the file. See [PEP 0263: Defining P... |
return tuple from a method | 4,873,613 | 3 | 2011-02-02T11:02:25Z | 4,873,685 | 14 | 2011-02-02T11:08:53Z | [
"python"
] | I am writing a method which returns a tuple on success but `None` on failure. I have not yet finalized on `None` (as a failure case return) but it is one of the choices. Can we return `-1,-1` for failure case? I am looking for best pythonic way to achieve this so that unpacking is easy.
Please let me know how we can i... | If there is a failure, why don't you raise an exception?
You can of course return (-1, -1) as failure, but it would not be a good solution in my opinion.
Remember that in Python EAFP (Easier to Ask Forgiveness than Permission) is favoured over LBYL (Look Before You Leap).
This means that it is considered better to j... |
Joining two 2D numpy arrays into a single 2D array of 2-tuples | 4,873,665 | 6 | 2011-02-02T11:06:44Z | 4,874,230 | 8 | 2011-02-02T12:02:04Z | [
"python",
"arrays",
"numpy"
] | I have two 2D numpy arrays like this, representing the x/y distances between three points. I need the x/y distances as tuples in a single array.
So from:
```
x_dists = array([[ 0, -1, -2],
[ 1, 0, -1],
[ 2, 1, 0]])
y_dists = array([[ 0, -1, -2],
[ 1, 0, -1],
... | ```
import numpy as np
dists = np.vstack(([x_dists.T], [y_dists.T])).T
```
returns `dists` like you wanted them. Afterwards it is not "a single 2D array of 2-tuples", but a normal 3D array where the third axis is the concatenation of the two original arrays.
You see:
```
dists.shape # (3, 3, 2)
``` |
Twisted: Creating a ThreadPool and then daemonizing leads to uninformative hangs | 4,875,326 | 5 | 2011-02-02T14:03:13Z | 4,877,676 | 7 | 2011-02-02T17:28:38Z | [
"python",
"django",
"twisted",
"threadpool",
"wsgi"
] | I am developing a networked application in Twisted, part of which consists of a web interface written in Django.
I wish to use Twisted's WSGI server to host the web interface, and I've written a working "tap" plugin to allow me to use `twistd`.
When running the server with the `-n` flag (don't daemonize) everything w... | Return a [`MultiService`](http://twistedmatrix.com/documents/10.2.0/api/twisted.application.service.MultiService.html) from your `ServiceMaker`; one that includes your `ThreadPoolService` as well as your main application service. The API for assembling such a thing is pretty straightforward:
```
multi = MultiService()... |
Python script to check if a zip file is corrupt | 4,875,747 | 9 | 2011-02-02T14:42:00Z | 4,875,877 | 12 | 2011-02-02T14:54:34Z | [
"python",
"zip"
] | How do i check if a zip file is corrupt or not.... like i have a zip file with 10 jpg images i am able to extract say 8 of the images two of the images in the zip are corrupt and i am not able to extract is there a way to check this in a python script | This code will either throw an exception (if the zip file is really bad or if it's not a zip file), or show the first bad file in the zip file.
```
import os
import sys
import zipfile
if __name__ == "__main__":
args = sys.argv[1:]
print "Testing zip file: %s" % args[0]
the_zip_file = zipfile.ZipFile(ar... |
How to test whether x is a member of a universal set? | 4,876,399 | 4 | 2011-02-02T15:36:43Z | 4,876,467 | 8 | 2011-02-02T15:41:32Z | [
"python",
"math"
] | I have a list L, and `x in L` evaluates to True if x is a member of L. What can I use instead of L in order `x in smth` will evaluate to True independently on the value of x?
So, I need something, what contains all objects, including itself, because x can also be this "smth". | ```
class Universe:
def __contains__(_,x): return True
``` |
How do you force wx.ListCtrl scroll bars to auto-lock to the bottom so that the most recent data is shown in the window? | 4,877,263 | 2 | 2011-02-02T16:50:20Z | 4,877,548 | 7 | 2011-02-02T17:16:27Z | [
"python",
"wxpython"
] | As new data comes into my wx.ListCtrl the window fills up and scroll bars appear. What I want to do is to have the most current data (at the bottom of the list) displayed on the windows. My first idea was a way to force the wx.ListCtrl scroll bars to default to the bottom of the window. If there is another/better way t... | After you add the new items, you should be able to use
```
self.EnsureVisible(self.GetItemCount() - 1)
```
to pin the scrollbar to the bottom. |
What is the __dict__.__dict__ attribute of a Python class? | 4,877,290 | 44 | 2011-02-02T16:52:57Z | 4,877,655 | 63 | 2011-02-02T17:26:02Z | [
"python",
"class",
"metaprogramming",
"magic-methods"
] | ```
>>> class A(object): pass
...
>>> A.__dict__
<dictproxy object at 0x173ef30>
>>> A.__dict__.__dict__
Traceback (most recent call last):
File "<string>", line 1, in <fragment>
AttributeError: 'dictproxy' object has no attribute '__dict__'
>>> A.__dict__.copy()
{'__dict__': <attribute '__dict__' of 'A' objects> ..... | First of all `A.__dict__.__dict__` is different from `A.__dict__['__dict__']`, and the former doesn't exist. The latter is the `__dict__` attribute that the instances of the class would have. It's a descriptor object that returns the internal dictionary of attributes for the specific instance. In short, the `__dict__` ... |
How to use custom AdminSite class? | 4,877,335 | 18 | 2011-02-02T16:57:08Z | 30,056,258 | 12 | 2015-05-05T14:47:59Z | [
"python",
"django",
"django-admin"
] | Which is the best way to implement my own `django.contrib.admin.sites.AdminSite`?
Actually I get a problem with the registration of `INSTALLED_APPS` in `django.contrib.admin.autodiscover`. If I use my custom AdminSite class in `urls.py`, there were no apps displayed on the admin page.
I fixed this with a litte hack. ... | ### The Problem
Using a custom class derived from `django.contrib.admin.AdminSite` for the admin site of a project, without having to write custom registration code to register models with the new class. When I use 3rd party apps with their own models, I'd rather not have to edit custom registration code only because ... |
numpy array of objects | 4,877,624 | 13 | 2011-02-02T17:22:52Z | 4,878,233 | 12 | 2011-02-02T18:18:21Z | [
"python",
"numpy",
"simulation"
] | I'm trying to implement a simulation for a lattice model (lattice boltzmann) in Python. Each site of the lattice has a number of properties, and interact with neighboring sites according to certain rules. I figured that it might be clever to make a class with all the properties and make a grid of instances of that clas... | You can [vectorize](http://docs.scipy.org/doc/numpy/reference/generated/numpy.vectorize.html) the class's `__init__` function:
```
import numpy as np
class Site:
def __init__(self, a):
self.a = a
def set_a(self, new_a):
self.a = new_a
vSite = np.vectorize(Site)
init_arry = np.arange(9).resha... |
How would I check a string for a certain letter in Python? | 4,877,844 | 10 | 2011-02-02T17:42:05Z | 4,877,867 | 22 | 2011-02-02T17:43:52Z | [
"python"
] | How would I tell Python to check the below for the letter x and then print "Yes"? The below is what I have so far...
```
dog = "xdasds"
if "x" is in dog:
print "Yes!"
``` | Use the `in` keyword without `is`.
```
if "x" in dog:
print "Yes!"
```
If you'd like to check for the non-existence of a character, use `not in`:
```
if "x" not in dog:
print "No!"
``` |
Python indentation error: | 4,878,369 | 3 | 2011-02-02T18:33:55Z | 4,878,380 | 7 | 2011-02-02T18:35:56Z | [
"python"
] | I have tried notepad++ and eclipse but even then , it is showing me an indentation error at line 18. I don't know, why it is throwing me an error like that...? please help me.
```
from brisa.core.reactors.qtreactor import QtReactor
reactor = QtReactor()
from brisa.core import config
from brisa.upnp.device import Devic... | The row
```
self.verticalLayout.addWidget(self.lineEdit)
```
should be on the same level of the other rows.
You might be missing it because your editor mixes tabs and spaces.
If you click on "edit" in your own question, you'll see that this row is not correctly indented. |
Python indentation error: | 4,878,369 | 3 | 2011-02-02T18:33:55Z | 4,878,450 | 13 | 2011-02-02T18:42:14Z | [
"python"
] | I have tried notepad++ and eclipse but even then , it is showing me an indentation error at line 18. I don't know, why it is throwing me an error like that...? please help me.
```
from brisa.core.reactors.qtreactor import QtReactor
reactor = QtReactor()
from brisa.core import config
from brisa.upnp.device import Devic... | In such cases it is usually a good idea to run python with the `-t` flag:
> -t : issue warnings about inconsistent tab usage (-tt: issue errors)
This will help to find indentation problems caused by accidentally used tabs. |
Django (w PyCharm) & PYTHON PATH issue | 4,878,661 | 5 | 2011-02-02T19:03:09Z | 5,418,074 | 10 | 2011-03-24T10:58:54Z | [
"python",
"django",
"pythonpath",
"pycharm"
] | I have purchased PyCharm and am trying to get things to work however I am encountering this issue..
Once I start a project everything works great...
Now if I want a standalone app.. let's say at /users/me/djangoApps I understand I have to add this directory to the python path.. I am trying to do so by creating a file... | In pycharm open the settings "cmd" + "," and then to "Project Structure" click on "Sources" to include any modules. |
Python: Tuples/dictionaries as keys, select, sort | 4,878,881 | 53 | 2011-02-02T19:24:11Z | 4,878,962 | 85 | 2011-02-02T19:34:16Z | [
"python",
"select",
"dictionary",
"key",
"tuples"
] | suppose I have quantities of fruits of different colors, e.g., 24 blue bananas, 12 green apples, 0 blue strawberries and so on.
I'd like to organize them in a data structure in Python that allows for easy selection and sorting. My idea was to put them into a dictionary with tuples as keys, e.g.,
```
{ ('banana', 'b... | Personally, one of the things I love about python is the tuple-dict combination. What you have here is effectively a 2d array (where x = fruit name and y = color), and I am generally a supporter of the dict of tuples for implementing 2d arrays, at least when something like `numpy` or a database isn't more appropriate. ... |
Python: Tuples/dictionaries as keys, select, sort | 4,878,881 | 53 | 2011-02-02T19:24:11Z | 4,878,996 | 10 | 2011-02-02T19:37:23Z | [
"python",
"select",
"dictionary",
"key",
"tuples"
] | suppose I have quantities of fruits of different colors, e.g., 24 blue bananas, 12 green apples, 0 blue strawberries and so on.
I'd like to organize them in a data structure in Python that allows for easy selection and sorting. My idea was to put them into a dictionary with tuples as keys, e.g.,
```
{ ('banana', 'b... | A dictionary probably isn't what you should be using in this case. A more full featured library would be a better alternative. Probably a real database. The easiest would be [sqlite](http://docs.python.org/library/sqlite3.html#module-sqlite3). You can keep the whole thing in memory by passing in the string ':memory:' i... |
Python: Tuples/dictionaries as keys, select, sort | 4,878,881 | 53 | 2011-02-02T19:24:11Z | 4,879,370 | 15 | 2011-02-02T20:13:16Z | [
"python",
"select",
"dictionary",
"key",
"tuples"
] | suppose I have quantities of fruits of different colors, e.g., 24 blue bananas, 12 green apples, 0 blue strawberries and so on.
I'd like to organize them in a data structure in Python that allows for easy selection and sorting. My idea was to put them into a dictionary with tuples as keys, e.g.,
```
{ ('banana', 'b... | Your best option will be to create a simple data structure to model what you have. Then you can store these objects in a simple list and sort/retrieve them any way you wish.
For this case, I'd use the following class:
```
class Fruit:
def __init__(self, name, color, quantity):
self.name = name
se... |
Python: Tuples/dictionaries as keys, select, sort | 4,878,881 | 53 | 2011-02-02T19:24:11Z | 4,880,247 | 13 | 2011-02-02T21:47:31Z | [
"python",
"select",
"dictionary",
"key",
"tuples"
] | suppose I have quantities of fruits of different colors, e.g., 24 blue bananas, 12 green apples, 0 blue strawberries and so on.
I'd like to organize them in a data structure in Python that allows for easy selection and sorting. My idea was to put them into a dictionary with tuples as keys, e.g.,
```
{ ('banana', 'b... | Database, dict of dicts, dictionary of list of dictionaries, named tuple (it's a subclass), sqlite, redundancy...
I didn't believe my eyes. What else ?
> "It might well be that dictionaries with tuples as keys are not the proper way to handle this situation."
>
> "my gut feeling is that a database is overkill for the ... |
Django: "projects" vs "apps" | 4,879,036 | 142 | 2011-02-02T19:41:49Z | 4,879,169 | 13 | 2011-02-02T19:54:31Z | [
"python",
"django",
"namespaces",
"project-organization"
] | I have a fairly complex "product" I'm getting ready to build using Django. I'm going to avoid using the terms "project" and "application" in this context, because I'm not clear on their specific meaning in Django.
Projects can have many apps. Apps can be shared among many projects. Fine.
I'm not reinventing the blog ... | I've found the following blog posts very useful about django applications and projects:
* <http://www.b-list.org/weblog/2006/sep/10/django-tips-laying-out-application/>
* <http://web.archive.org/web/20080302205555/www.pointy-stick.com/blog/2007/11/09/django-tip-developing-without-projects/>
In principle, you have a l... |
Django: "projects" vs "apps" | 4,879,036 | 142 | 2011-02-02T19:41:49Z | 4,879,205 | 41 | 2011-02-02T19:58:21Z | [
"python",
"django",
"namespaces",
"project-organization"
] | I have a fairly complex "product" I'm getting ready to build using Django. I'm going to avoid using the terms "project" and "application" in this context, because I'm not clear on their specific meaning in Django.
Projects can have many apps. Apps can be shared among many projects. Fine.
I'm not reinventing the blog ... | What is to stop you using `myproduct.myproduct`? What you need to achieve that roughly consists of doing this:
```
django-admin.py startproject myproduct
cd myproduct
mkdir myproduct
touch myproduct/__init__.py
touch myproduct/models.py
touch myproduct/views.py
```
and so on. Would it help if I said `views.py` doesn'... |
Django: "projects" vs "apps" | 4,879,036 | 142 | 2011-02-02T19:41:49Z | 4,879,235 | 54 | 2011-02-02T20:01:03Z | [
"python",
"django",
"namespaces",
"project-organization"
] | I have a fairly complex "product" I'm getting ready to build using Django. I'm going to avoid using the terms "project" and "application" in this context, because I'm not clear on their specific meaning in Django.
Projects can have many apps. Apps can be shared among many projects. Fine.
I'm not reinventing the blog ... | > Try to answer question: "What does my
> application do?". If you cannot answer
> in a single sentence, then maybe you can
> split it into several apps with cleaner
> logic.
I read this thought somewhere soon after I've started to work with django and I find that I ask this question of myself quite often and it helps... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.