content
stringlengths 85
101k
| title
stringlengths 0
150
| question
stringlengths 15
48k
| answers
list | answers_scores
list | non_answers
list | non_answers_scores
list | tags
list | name
stringlengths 35
137
|
|---|---|---|---|---|---|---|---|---|
Q:
django views question
In my django views i have the following
def create(request):
query=header.objects.filter(id=a)[0]
a=query.criteria_set.all()
logging.debug(a.details)
I get an error saying 'QuerySet' object has no attribute 'details' in the debug statement
.What is this error and what should be the correct statemnt to query this.And the model corresponding to this is as follows
where as the models has the following:
class header(models.Model):
title = models.CharField(max_length = 255)
created_by = models.CharField(max_length = 255)
def __unicode__(self):
return self.id()
class criteria(models.Model):
details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
Thanks..
A:
QuerySet.all() returns a QuerySet. Index it or iterate over it if you want to access the individual models:
logging.debug(a[0].details)
for m in a:
logging.debug(m.details)
|
django views question
|
In my django views i have the following
def create(request):
query=header.objects.filter(id=a)[0]
a=query.criteria_set.all()
logging.debug(a.details)
I get an error saying 'QuerySet' object has no attribute 'details' in the debug statement
.What is this error and what should be the correct statemnt to query this.And the model corresponding to this is as follows
where as the models has the following:
class header(models.Model):
title = models.CharField(max_length = 255)
created_by = models.CharField(max_length = 255)
def __unicode__(self):
return self.id()
class criteria(models.Model):
details = models.CharField(max_length = 255)
headerid = models.ForeignKey(header)
def __unicode__(self):
return self.id()
Thanks..
|
[
"QuerySet.all() returns a QuerySet. Index it or iterate over it if you want to access the individual models:\nlogging.debug(a[0].details)\n\nfor m in a:\n logging.debug(m.details)\n\n"
] |
[
3
] |
[] |
[] |
[
"django",
"django_queryset",
"django_views",
"python"
] |
stackoverflow_0002532304_django_django_queryset_django_views_python.txt
|
Q:
Python: ImportError no module named urllib
I just rented a VPS from Linode which has python2.5 and ubuntu 8.04. When I run this command from python shell:
import urllib
I get:
ImportError: No module named urllib
What can be the reason? How can I add this module to python? Isn't it prepackaged with the basic version?
Can it be PYTHONPATH problem?
A:
Ok, I resolved the issue.
Somehow, python-tk package (which includes urllib) was missing.
So the following line fixed the problem
apt-get install python-tk
|
Python: ImportError no module named urllib
|
I just rented a VPS from Linode which has python2.5 and ubuntu 8.04. When I run this command from python shell:
import urllib
I get:
ImportError: No module named urllib
What can be the reason? How can I add this module to python? Isn't it prepackaged with the basic version?
Can it be PYTHONPATH problem?
|
[
"Ok, I resolved the issue.\nSomehow, python-tk package (which includes urllib) was missing.\nSo the following line fixed the problem\napt-get install python-tk\n\n"
] |
[
1
] |
[
"I use a later OS, so I don't know if this will help, but just in case:\nmarcelo@localhost:~$ lsb_release -a\nNo LSB modules are available.\nDistributor ID: Ubuntu\nDescription: Ubuntu 9.10\nRelease: 9.10\nCodename: karmic\nmarcelo@localhost:~$ python\nPython 2.6.4rc2 (r264rc2:75497, Oct 20 2009, 02:54:09) \n[GCC 4.4.1] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import urllib # works fine\n>>> import sys\n>>> sys.path\n['', '/usr/lib/python2.6', '/usr/lib/python2.6/plat-linux2', '/usr/lib/python2.6/lib-tk', '/usr/lib/python2.6/lib-old', '/usr/lib/python2.6/lib-dynload', '/usr/lib/python2.6/dist-packages', '/usr/local/lib/python2.6/dist-packages']\n>>> \n\n"
] |
[
-1
] |
[
"importerror",
"python",
"pythonpath",
"urllib"
] |
stackoverflow_0002532321_importerror_python_pythonpath_urllib.txt
|
Q:
Python - Is a dictionary slow to find frequency of each character?
I am trying to find a frequency of each symbol in any given text using an algorithm of O(n) complexity. My algorithm looks like:
s = len(text)
P = 1.0/s
freqs = {}
for char in text:
try:
freqs[char]+=P
except:
freqs[char]=P
but I doubt that this dictionary-method is fast enough, because it depends on the underlying implementation of the dictionary methods. Is this the fastest method?
UPDATE: there is no increase in speed if collections and integers are used. It is because the algorithm is already of O(n) complexity, so no essential speedup is possible.
For example, results for 1MB text:
without collections:
real 0m0.695s
with collections:
real 0m0.625s
A:
Performance comparison
Note: time in the table doesn't include the time it takes to load files.
| approach | american-english, | big.txt, | time w.r.t. defaultdict |
| | time, seconds | time, seconds | |
|----------------+-------------------+---------------+-------------------------|
| Counter | 0.451 | 3.367 | 3.6 |
| setdefault | 0.348 | 2.320 | 2.5 |
| list | 0.277 | 1.822 | 2 |
| try/except | 0.158 | 1.068 | 1.2 |
| defaultdict | 0.141 | 0.925 | 1 |
| numpy | 0.012 | 0.076 | 0.082 |
| S.Mark's ext. | 0.003 | 0.019 | 0.021 |
| ext. in Cython | 0.001 | 0.008 | 0.0086 |
#+TBLFM: $4=$3/@7$3;%.2g
The files used: '/usr/share/dict/american-english' and 'big.txt'.
The script that compares 'Counter', 'setdefault', 'list', 'try/except', 'defaultdict', 'numpy', 'cython' -based, and @S.Mark's solutions is at http://gist.github.com/347000
The fastest solution is Python extension written in Cython:
import cython
@cython.locals(
chars=unicode,
i=cython.Py_ssize_t,
L=cython.Py_ssize_t[0x10000])
def countchars_cython(chars):
for i in range(0x10000): # unicode code points > 0xffff are not supported
L[i] = 0
for c in chars:
L[c] += 1
return {unichr(i): L[i] for i in range(0x10000) if L[i]}
Previous comparison:
* python (dict) : 0.5 seconds
* python (list) : 0.5 (ascii) (0.2 if read whole file in memory)
* perl : 0.5
* python (numpy): 0.07
* c++ : 0.05
* c : 0.008 (ascii)
Input data:
$ tail /usr/share/dict/american-english
éclat's
élan
élan's
émigré
émigrés
épée
épées
étude
étude's
études
$ du -h /usr/share/dict/american-english
912K /usr/share/dict/american-english
python (Counter): 0.5 seconds
#!/usr/bin/env python3.1
import collections, fileinput, textwrap
chars = (ch for word in fileinput.input() for ch in word.rstrip())
# faster (0.4s) but less flexible: chars = open(filename).read()
print(textwrap.fill(str(collections.Counter(chars)), width=79))
Run it:
$ time -p python3.1 count_char.py /usr/share/dict/american-english
Counter({'e': 87823, 's': 86620, 'i': 66548, 'a': 62778, 'n': 56696, 'r':
56286, 't': 51588, 'o': 48425, 'l': 39914, 'c': 30020, 'd': 28068, 'u': 25810,
"'": 24511, 'g': 22262, 'p': 20917, 'm': 20747, 'h': 18453, 'b': 14137, 'y':
12367, 'f': 10049, 'k': 7800, 'v': 7573, 'w': 6924, 'z': 3088, 'x': 2082, 'M':
1686, 'C': 1549, 'S': 1515, 'q': 1447, 'B': 1387, 'j': 1376, 'A': 1345, 'P':
974, 'L': 912, 'H': 860, 'T': 858, 'G': 811, 'D': 809, 'R': 749, 'K': 656, 'E':
618, 'J': 539, 'N': 531, 'W': 507, 'F': 502, 'O': 354, 'I': 344, 'V': 330, 'Z':
150, 'Y': 140, 'é': 128, 'U': 117, 'Q': 63, 'X': 42, 'è': 29, 'ö': 12, 'ü': 12,
'ó': 10, 'á': 10, 'ä': 7, 'ê': 6, 'â': 6, 'ñ': 6, 'ç': 4, 'å': 3, 'û': 3, 'í':
2, 'ô': 2, 'Å': 1})
real 0.44
user 0.43
sys 0.01
perl: 0.5 seconds
time -p perl -MData::Dumper -F'' -lanwe'$c{$_}++ for (@F);
END{ $Data::Dumper::Terse = 1; $Data::Dumper::Indent = 0; print Dumper(\%c) }
' /usr/share/dict/american-english
Output:
{'S' => 1515,'K' => 656,'' => 29,'d' => 28068,'Y' => 140,'E' => 618,'y' => 12367,'g' => 22262,'e' => 87823,'' => 2,'J' => 539,'' => 241,'' => 3,'' => 6,'' => 4,'' => 128,'D' => 809,'q' => 1447,'b' => 14137,'z' => 3088,'w' => 6924,'Q' => 63,'' => 10,'M' => 1686,'C' => 1549,'' => 10,'L' => 912,'X' => 42,'P' => 974,'' => 12,'\'' => 24511,'' => 6,'a' => 62778,'T' => 858,'N' => 531,'j' => 1376,'Z' => 150,'u' => 25810,'k' => 7800,'t' => 51588,'' => 6,'W' => 507,'v' => 7573,'s' => 86620,'B' => 1387,'H' => 860,'c' => 30020,'' => 12,'I' => 344,'' => 3,'G' => 811,'U' => 117,'F' => 502,'' => 2,'r' => 56286,'x' => 2082,'V' => 330,'h' => 18453,'f' => 10049,'' => 1,'i' => 66548,'A' => 1345,'O' => 354,'n' => 56696,'m' => 20747,'l' => 39914,'' => 7,'p' => 20917,'R' => 749,'o' => 48425}
real 0.51
user 0.49
sys 0.02
python (numpy): 0.07 seconds
Based on Ants Aasma's answer (modified to support unicode):
#!/usr/bin/env python
import codecs, itertools, operator, sys
import numpy
filename = sys.argv[1] if len(sys.argv)>1 else '/usr/share/dict/american-english'
# ucs2 or ucs4 python?
dtype = {2: numpy.uint16, 4: numpy.uint32}[len(buffer(u"u"))]
# count ordinals
text = codecs.open(filename, encoding='utf-8').read()
a = numpy.frombuffer(text, dtype=dtype)
counts = numpy.bincount(a)
# pretty print
counts = [(unichr(i), v) for i, v in enumerate(counts) if v]
counts.sort(key=operator.itemgetter(1))
print ' '.join('("%s" %d)' % c for c in counts if c[0] not in ' \t\n')
Output:
("Å" 1) ("í" 2) ("ô" 2) ("å" 3) ("û" 3) ("ç" 4) ("â" 6) ("ê" 6) ("ñ" 6) ("ä" 7) ("á" 10) ("ó" 10) ("ö" 12) ("ü" 12) ("è" 29) ("X" 42) ("Q" 63) ("U" 117) ("é" 128) ("Y" 140) ("Z" 150) ("V" 330) ("I" 344) ("O" 354) ("F" 502) ("W" 507) ("N" 531) ("J" 539) ("E" 618) ("K" 656) ("R" 749) ("D" 809) ("G" 811) ("T" 858) ("H" 860) ("L" 912) ("P" 974) ("A" 1345) ("j" 1376) ("B" 1387) ("q" 1447) ("S" 1515) ("C" 1549) ("M" 1686) ("x" 2082) ("z" 3088) ("w" 6924) ("v" 7573) ("k" 7800) ("f" 10049) ("y" 12367) ("b" 14137) ("h" 18453) ("m" 20747) ("p" 20917) ("g" 22262) ("'" 24511) ("u" 25810) ("d" 28068) ("c" 30020) ("l" 39914) ("o" 48425) ("t" 51588) ("r" 56286) ("n" 56696) ("a" 62778) ("i" 66548) ("s" 86620) ("e" 87823)
real 0.07
user 0.06
sys 0.01
c++: 0.05 seconds
// $ g++ *.cc -lboost_program_options
// $ ./a.out /usr/share/dict/american-english
#include <iostream>
#include <fstream>
#include <cstdlib> // exit
#include <boost/program_options/detail/utf8_codecvt_facet.hpp>
#include <boost/tr1/unordered_map.hpp>
#include <boost/foreach.hpp>
int main(int argc, char* argv[]) {
using namespace std;
// open input file
if (argc != 2) {
cerr << "Usage: " << argv[0] << " <filename>\n";
exit(2);
}
wifstream f(argv[argc-1]);
// assume the file has utf-8 encoding
locale utf8_locale(locale(""),
new boost::program_options::detail::utf8_codecvt_facet);
f.imbue(utf8_locale);
// count characters frequencies
typedef std::tr1::unordered_map<wchar_t, size_t> hashtable_t;
hashtable_t counts;
for (wchar_t ch; f >> ch; )
counts[ch]++;
// print result
wofstream of("output.utf8");
of.imbue(utf8_locale);
BOOST_FOREACH(hashtable_t::value_type i, counts)
of << "(" << i.first << " " << i.second << ") ";
of << endl;
}
Result:
$ cat output.utf8
(í 2) (O 354) (P 974) (Q 63) (R 749) (S 1,515) (ñ 6) (T 858) (U 117) (ó 10) (ô 2) (V 330) (W 507) (X 42) (ö 12) (Y 140) (Z 150) (û 3) (ü 12) (a 62,778) (b 14,137) (c 30,020) (d 28,068) (e 87,823) (f 10,049) (g 22,262) (h 18,453) (i 66,548) (j 1,376) (k 7,800) (l 39,914) (m 20,747) (n 56,696) (o 48,425) (p 20,917) (q 1,447) (r 56,286) (s 86,620) (t 51,588) (u 25,810) (Å 1) (' 24,511) (v 7,573) (w 6,924) (x 2,082) (y 12,367) (z 3,088) (A 1,345) (B 1,387) (C 1,549) (á 10) (â 6) (D 809) (E 618) (F 502) (ä 7) (å 3) (G 811) (H 860) (ç 4) (I 344) (J 539) (è 29) (K 656) (é 128) (ê 6) (L 912) (M 1,686) (N 531)
c (ascii): 0.0079 seconds
// $ gcc -O3 cc_ascii.c -o cc_ascii && time -p ./cc_ascii < input.txt
#include <stdio.h>
enum { N = 256 };
size_t counts[N];
int main(void) {
// count characters
int ch = -1;
while((ch = getchar()) != EOF)
++counts[ch];
// print result
size_t i = 0;
for (; i < N; ++i)
if (counts[i])
printf("('%c' %zu) ", (int)i, counts[i]);
return 0;
}
A:
How about avoiding float operations inside the loop and do it after everything is done?
By that way, you could just do +1 everytime, and its should be faster.
And better use collections.defaultdict as S.Lott advised.
freqs=collections.defaultdict(int)
for char in text:
freqs[char]+=1
Or You may want to try, collections.Counter in python 2.7+
>>> collections.Counter("xyzabcxyz")
Counter({'y': 2, 'x': 2, 'z': 2, 'a': 1, 'c': 1, 'b': 1})
Or
You may try psyco, which do just-in-time compiling for python.
You have loops, so I think you would get some performance gain with psyco
Edit 1:
I did some benchmarks base on big.txt (~6.5 MB) which is used in spelling corrector by peter norvig
Text Length: 6488666
dict.get : 11.9060001373 s
93 chars {u' ': 1036511, u'$': 110, u'(': 1748, u',': 77675, u'0': 3064, u'4': 2417, u'8': 2527, u'<': 2, u'@': 8, ....
if char in dict : 9.71799993515 s
93 chars {u' ': 1036511, u'$': 110, u'(': 1748, u',': 77675, u'0': 3064, u'4': 2417, u'8': 2527, u'<': 2, u'@': 8, ....
dict try/catch : 7.35899996758 s
93 chars {u' ': 1036511, u'$': 110, u'(': 1748, u',': 77675, u'0': 3064, u'4': 2417, u'8': 2527, u'<': 2, u'@': 8, ....
collections.default : 7.29699993134 s
93 chars defaultdict(<type 'int'>, {u' ': 1036511, u'$': 110, u'(': 1748, u',': 77675, u'0': 3064, u'4': 2417, u'8': 2527, u'<': 2, u'@': 8, ....
CPU Specs: 1.6GHz Intel Mobile Atom CPU
According to that, dict.get is slowest and collections.defaultdict is fastest, try/except is also the fast one.
Edit 2:
Added collections.Counter benchmarks, Its slower than dict.get and took 15s in my laptop
collections.Counter : 15.3439998627 s
93 chars Counter({u' ': 1036511, u'e': 628234, u't': 444459, u'a': 395872, u'o': 382683, u'n': 362397, u'i': 348464,
A:
I've written Char Counter C Extension to Python, looks like 300x faster than collections.Counter and 150x faster than collections.default(int)
C Char Counter : 0.0469999313354 s
93 chars {u' ': 1036511, u'$': 110, u'(': 1748, u',': 77675, u'0': 3064, u'4': 2417, u'8': 2527, u'<': 2, u'@': 8,
Here is Char Counter C Extension Codes
static PyObject *
CharCounter(PyObject *self, PyObject *args, PyObject *keywds)
{
wchar_t *t1;unsigned l1=0;
if (!PyArg_ParseTuple(args,"u#",&t1,&l1)) return NULL;
PyObject *resultList,*itemTuple;
for(unsigned i=0;i<=0xffff;i++)char_counter[i]=0;
unsigned chlen=0;
for(unsigned i=0;i<l1;i++){
if(char_counter[t1[i]]==0)char_list[chlen++]=t1[i];
char_counter[t1[i]]++;
}
resultList = PyList_New(0);
for(unsigned i=0;i<chlen;i++){
itemTuple = PyTuple_New(2);
PyTuple_SetItem(itemTuple, 0,PyUnicode_FromWideChar(&char_list[i],1));
PyTuple_SetItem(itemTuple, 1,PyInt_FromLong(char_counter[char_list[i]]));
PyList_Append(resultList, itemTuple);
Py_DECREF(itemTuple);
};
return resultList;
}
Where char_counter, and char_list are malloc-ated at module level, so no need to malloc every time when function calls.
char_counter=(unsigned*)malloc(sizeof(unsigned)*0x10000);
char_list=(wchar_t*)malloc(sizeof(wchar_t)*0x10000);
It returns a List with Tuples
[(u'T', 16282), (u'h', 287323), (u'e', 628234), (u' ', 1036511), (u'P', 8946), (u'r', 303977), (u'o', 382683), ...
To convert to dict format, just dict() will do.
dict(CharCounter(text))
PS: Benchmark included the time converting to dict
CharCounter accept only Python Unicode String u"", if the text is utf8, need to do .decode("utf8") in advance.
Input Supports Unicode until Basic Multilingual Plane (BMP) - 0x0000 to 0xFFFF
A:
No it's not the fastest, because you know that the characters have a limited range and you could use a list and direct indexing, using the numeric representation of the character, to store the frequencies.
A:
It is very, very hard to beat dict. It is very highly tuned since almost everything in Python is dict-based.
A:
I'm not familiar with python, but for finding frequencies, unless you know the range of frequencies (in which case you can use an array), dictionary is the way to go.
If you know your characters in a unicode, ASCII, etc. range, you can define an array with the correct number of values.
However, this will change the space complexity of this from O(n) to O(possible n), but you will earn a time complexity improvement from O(n*(dictionary extraction/insertion time)) to O(n).
A:
If you are really concerned about speed, you might consider first counting characters with integers and then obtaining frequencies through (float) division.
Here are the numbers:
python -mtimeit -s'x=0' 'x+=1'
10000000 loops, best of 3: 0.0661 usec per loop
python -mtimeit -s'x=0.' 'x+=1.'
10000000 loops, best of 3: 0.0965 usec per loop
A:
well, you can do it in the old fashioned style... as we know that there are not too many different characters and they are contiguous, we can use a plain array (or list here) and use the characters ordinal numbering for indexing:
s = 1.0*len(text)
counts = [0]*256 # change this if working with unicode
for char in text:
freqs[ord(char)]+=1
freqs = dict((chr(i), v/s) for i,v in enumerate(counts) if v)
This will be probably faster, but just by a constant factor, both methods should have the same complexity.
A:
Using this code on Alice in Wonderland (163793 chars) and "The Bible, Douay-Rheims Version" (5649295 chars) from Project Gutenberg:
from collections import defaultdict
import timeit
def countchars():
f = open('8300-8.txt', 'rb')
#f = open('11.txt')
s = f.read()
f.close()
charDict = defaultdict(int)
for aChar in s:
charDict[aChar] += 1
if __name__ == '__main__':
tm = timeit.Timer('countchars()', 'from countchars import countchars')
print tm.timeit(10)
I get:
2.27324003315 #Alice in Wonderland
74.8686217403 #Bible
The ratio between the number of chars for both books is 0.029 and the ratio between the times is 0.030, so, the algorithm is O(n) with a very small constant factor. Fast enough for most (all?) purposes, I should think.
A:
If the data is in a single byte encoding you can use numpy to accelerate the count process:
import numpy as np
def char_freq(data):
counts = np.bincount(np.frombuffer(data, dtype=np.byte))
freqs = counts.astype(np.double) / len(data)
return dict((chr(idx), freq) for idx, freq in enumerate(freqs) if freq > 0)
Some quick benchmarking shows that this is about 10x faster than aggregating to a defaultdict(int).
A:
To avoid the try except overhead you can use a defaultdict.
A:
Small speed up will be usage of dict.setdefault method, that way you will not pay rather big price for every new encountered character:
for char in text:
freq[char] = freq.setdefault(char, 0.0) + P
As a sidenote: having bare except: is considered very bad practice.
|
Python - Is a dictionary slow to find frequency of each character?
|
I am trying to find a frequency of each symbol in any given text using an algorithm of O(n) complexity. My algorithm looks like:
s = len(text)
P = 1.0/s
freqs = {}
for char in text:
try:
freqs[char]+=P
except:
freqs[char]=P
but I doubt that this dictionary-method is fast enough, because it depends on the underlying implementation of the dictionary methods. Is this the fastest method?
UPDATE: there is no increase in speed if collections and integers are used. It is because the algorithm is already of O(n) complexity, so no essential speedup is possible.
For example, results for 1MB text:
without collections:
real 0m0.695s
with collections:
real 0m0.625s
|
[
"Performance comparison\nNote: time in the table doesn't include the time it takes to load files.\n| approach | american-english, | big.txt, | time w.r.t. defaultdict |\n| | time, seconds | time, seconds | |\n|----------------+-------------------+---------------+-------------------------|\n| Counter | 0.451 | 3.367 | 3.6 |\n| setdefault | 0.348 | 2.320 | 2.5 |\n| list | 0.277 | 1.822 | 2 |\n| try/except | 0.158 | 1.068 | 1.2 |\n| defaultdict | 0.141 | 0.925 | 1 |\n| numpy | 0.012 | 0.076 | 0.082 |\n| S.Mark's ext. | 0.003 | 0.019 | 0.021 |\n| ext. in Cython | 0.001 | 0.008 | 0.0086 |\n#+TBLFM: $4=$3/@7$3;%.2g\n\nThe files used: '/usr/share/dict/american-english' and 'big.txt'.\nThe script that compares 'Counter', 'setdefault', 'list', 'try/except', 'defaultdict', 'numpy', 'cython' -based, and @S.Mark's solutions is at http://gist.github.com/347000\nThe fastest solution is Python extension written in Cython:\nimport cython\n\n@cython.locals(\n chars=unicode,\n i=cython.Py_ssize_t,\n L=cython.Py_ssize_t[0x10000])\ndef countchars_cython(chars):\n for i in range(0x10000): # unicode code points > 0xffff are not supported\n L[i] = 0\n\n for c in chars:\n L[c] += 1\n\n return {unichr(i): L[i] for i in range(0x10000) if L[i]}\n\n\nPrevious comparison:\n* python (dict) : 0.5 seconds\n* python (list) : 0.5 (ascii) (0.2 if read whole file in memory)\n* perl : 0.5\n* python (numpy): 0.07 \n* c++ : 0.05\n* c : 0.008 (ascii)\n\nInput data:\n$ tail /usr/share/dict/american-english\néclat's\nélan\nélan's\némigré\némigrés\népée\népées\nétude\nétude's\nétudes\n\n$ du -h /usr/share/dict/american-english\n912K /usr/share/dict/american-english\n\npython (Counter): 0.5 seconds\n#!/usr/bin/env python3.1\nimport collections, fileinput, textwrap\n\nchars = (ch for word in fileinput.input() for ch in word.rstrip())\n# faster (0.4s) but less flexible: chars = open(filename).read()\nprint(textwrap.fill(str(collections.Counter(chars)), width=79))\n\nRun it:\n$ time -p python3.1 count_char.py /usr/share/dict/american-english\n\nCounter({'e': 87823, 's': 86620, 'i': 66548, 'a': 62778, 'n': 56696, 'r':\n56286, 't': 51588, 'o': 48425, 'l': 39914, 'c': 30020, 'd': 28068, 'u': 25810,\n\"'\": 24511, 'g': 22262, 'p': 20917, 'm': 20747, 'h': 18453, 'b': 14137, 'y':\n12367, 'f': 10049, 'k': 7800, 'v': 7573, 'w': 6924, 'z': 3088, 'x': 2082, 'M':\n1686, 'C': 1549, 'S': 1515, 'q': 1447, 'B': 1387, 'j': 1376, 'A': 1345, 'P':\n974, 'L': 912, 'H': 860, 'T': 858, 'G': 811, 'D': 809, 'R': 749, 'K': 656, 'E':\n618, 'J': 539, 'N': 531, 'W': 507, 'F': 502, 'O': 354, 'I': 344, 'V': 330, 'Z':\n150, 'Y': 140, 'é': 128, 'U': 117, 'Q': 63, 'X': 42, 'è': 29, 'ö': 12, 'ü': 12,\n'ó': 10, 'á': 10, 'ä': 7, 'ê': 6, 'â': 6, 'ñ': 6, 'ç': 4, 'å': 3, 'û': 3, 'í':\n2, 'ô': 2, 'Å': 1})\nreal 0.44\nuser 0.43\nsys 0.01\nperl: 0.5 seconds\ntime -p perl -MData::Dumper -F'' -lanwe'$c{$_}++ for (@F);\nEND{ $Data::Dumper::Terse = 1; $Data::Dumper::Indent = 0; print Dumper(\\%c) }\n' /usr/share/dict/american-english\n\nOutput:\n{'S' => 1515,'K' => 656,'' => 29,'d' => 28068,'Y' => 140,'E' => 618,'y' => 12367,'g' => 22262,'e' => 87823,'' => 2,'J' => 539,'' => 241,'' => 3,'' => 6,'' => 4,'' => 128,'D' => 809,'q' => 1447,'b' => 14137,'z' => 3088,'w' => 6924,'Q' => 63,'' => 10,'M' => 1686,'C' => 1549,'' => 10,'L' => 912,'X' => 42,'P' => 974,'' => 12,'\\'' => 24511,'' => 6,'a' => 62778,'T' => 858,'N' => 531,'j' => 1376,'Z' => 150,'u' => 25810,'k' => 7800,'t' => 51588,'' => 6,'W' => 507,'v' => 7573,'s' => 86620,'B' => 1387,'H' => 860,'c' => 30020,'' => 12,'I' => 344,'' => 3,'G' => 811,'U' => 117,'F' => 502,'' => 2,'r' => 56286,'x' => 2082,'V' => 330,'h' => 18453,'f' => 10049,'' => 1,'i' => 66548,'A' => 1345,'O' => 354,'n' => 56696,'m' => 20747,'l' => 39914,'' => 7,'p' => 20917,'R' => 749,'o' => 48425}\nreal 0.51\nuser 0.49\nsys 0.02\npython (numpy): 0.07 seconds\nBased on Ants Aasma's answer (modified to support unicode):\n#!/usr/bin/env python\nimport codecs, itertools, operator, sys\nimport numpy\n\nfilename = sys.argv[1] if len(sys.argv)>1 else '/usr/share/dict/american-english'\n\n# ucs2 or ucs4 python?\ndtype = {2: numpy.uint16, 4: numpy.uint32}[len(buffer(u\"u\"))]\n\n# count ordinals\ntext = codecs.open(filename, encoding='utf-8').read()\na = numpy.frombuffer(text, dtype=dtype)\ncounts = numpy.bincount(a)\n\n# pretty print\ncounts = [(unichr(i), v) for i, v in enumerate(counts) if v]\ncounts.sort(key=operator.itemgetter(1))\nprint ' '.join('(\"%s\" %d)' % c for c in counts if c[0] not in ' \\t\\n')\n\nOutput:\n(\"Å\" 1) (\"í\" 2) (\"ô\" 2) (\"å\" 3) (\"û\" 3) (\"ç\" 4) (\"â\" 6) (\"ê\" 6) (\"ñ\" 6) (\"ä\" 7) (\"á\" 10) (\"ó\" 10) (\"ö\" 12) (\"ü\" 12) (\"è\" 29) (\"X\" 42) (\"Q\" 63) (\"U\" 117) (\"é\" 128) (\"Y\" 140) (\"Z\" 150) (\"V\" 330) (\"I\" 344) (\"O\" 354) (\"F\" 502) (\"W\" 507) (\"N\" 531) (\"J\" 539) (\"E\" 618) (\"K\" 656) (\"R\" 749) (\"D\" 809) (\"G\" 811) (\"T\" 858) (\"H\" 860) (\"L\" 912) (\"P\" 974) (\"A\" 1345) (\"j\" 1376) (\"B\" 1387) (\"q\" 1447) (\"S\" 1515) (\"C\" 1549) (\"M\" 1686) (\"x\" 2082) (\"z\" 3088) (\"w\" 6924) (\"v\" 7573) (\"k\" 7800) (\"f\" 10049) (\"y\" 12367) (\"b\" 14137) (\"h\" 18453) (\"m\" 20747) (\"p\" 20917) (\"g\" 22262) (\"'\" 24511) (\"u\" 25810) (\"d\" 28068) (\"c\" 30020) (\"l\" 39914) (\"o\" 48425) (\"t\" 51588) (\"r\" 56286) (\"n\" 56696) (\"a\" 62778) (\"i\" 66548) (\"s\" 86620) (\"e\" 87823)\nreal 0.07\nuser 0.06\nsys 0.01\n\nc++: 0.05 seconds\n// $ g++ *.cc -lboost_program_options \n// $ ./a.out /usr/share/dict/american-english \n#include <iostream>\n#include <fstream>\n#include <cstdlib> // exit\n\n#include <boost/program_options/detail/utf8_codecvt_facet.hpp>\n#include <boost/tr1/unordered_map.hpp>\n#include <boost/foreach.hpp>\n\nint main(int argc, char* argv[]) {\n using namespace std;\n\n // open input file\n if (argc != 2) {\n cerr << \"Usage: \" << argv[0] << \" <filename>\\n\";\n exit(2);\n }\n wifstream f(argv[argc-1]); \n\n // assume the file has utf-8 encoding\n locale utf8_locale(locale(\"\"), \n new boost::program_options::detail::utf8_codecvt_facet);\n f.imbue(utf8_locale); \n\n // count characters frequencies\n typedef std::tr1::unordered_map<wchar_t, size_t> hashtable_t; \n hashtable_t counts;\n for (wchar_t ch; f >> ch; )\n counts[ch]++;\n \n // print result\n wofstream of(\"output.utf8\");\n of.imbue(utf8_locale);\n BOOST_FOREACH(hashtable_t::value_type i, counts) \n of << \"(\" << i.first << \" \" << i.second << \") \";\n of << endl;\n}\n\nResult:\n$ cat output.utf8 \n\n(í 2) (O 354) (P 974) (Q 63) (R 749) (S 1,515) (ñ 6) (T 858) (U 117) (ó 10) (ô 2) (V 330) (W 507) (X 42) (ö 12) (Y 140) (Z 150) (û 3) (ü 12) (a 62,778) (b 14,137) (c 30,020) (d 28,068) (e 87,823) (f 10,049) (g 22,262) (h 18,453) (i 66,548) (j 1,376) (k 7,800) (l 39,914) (m 20,747) (n 56,696) (o 48,425) (p 20,917) (q 1,447) (r 56,286) (s 86,620) (t 51,588) (u 25,810) (Å 1) (' 24,511) (v 7,573) (w 6,924) (x 2,082) (y 12,367) (z 3,088) (A 1,345) (B 1,387) (C 1,549) (á 10) (â 6) (D 809) (E 618) (F 502) (ä 7) (å 3) (G 811) (H 860) (ç 4) (I 344) (J 539) (è 29) (K 656) (é 128) (ê 6) (L 912) (M 1,686) (N 531)\nc (ascii): 0.0079 seconds\n// $ gcc -O3 cc_ascii.c -o cc_ascii && time -p ./cc_ascii < input.txt\n#include <stdio.h>\n\nenum { N = 256 };\nsize_t counts[N];\n\nint main(void) {\n // count characters\n int ch = -1;\n while((ch = getchar()) != EOF)\n ++counts[ch];\n \n // print result\n size_t i = 0;\n for (; i < N; ++i) \n if (counts[i])\n printf(\"('%c' %zu) \", (int)i, counts[i]);\n return 0;\n}\n\n",
"How about avoiding float operations inside the loop and do it after everything is done?\nBy that way, you could just do +1 everytime, and its should be faster.\nAnd better use collections.defaultdict as S.Lott advised.\nfreqs=collections.defaultdict(int)\n\nfor char in text: \n freqs[char]+=1\n\nOr You may want to try, collections.Counter in python 2.7+\n>>> collections.Counter(\"xyzabcxyz\")\nCounter({'y': 2, 'x': 2, 'z': 2, 'a': 1, 'c': 1, 'b': 1})\n\nOr\nYou may try psyco, which do just-in-time compiling for python.\nYou have loops, so I think you would get some performance gain with psyco\n\nEdit 1:\nI did some benchmarks base on big.txt (~6.5 MB) which is used in spelling corrector by peter norvig\nText Length: 6488666\n\ndict.get : 11.9060001373 s\n93 chars {u' ': 1036511, u'$': 110, u'(': 1748, u',': 77675, u'0': 3064, u'4': 2417, u'8': 2527, u'<': 2, u'@': 8, ....\n\nif char in dict : 9.71799993515 s\n93 chars {u' ': 1036511, u'$': 110, u'(': 1748, u',': 77675, u'0': 3064, u'4': 2417, u'8': 2527, u'<': 2, u'@': 8, ....\n\ndict try/catch : 7.35899996758 s\n93 chars {u' ': 1036511, u'$': 110, u'(': 1748, u',': 77675, u'0': 3064, u'4': 2417, u'8': 2527, u'<': 2, u'@': 8, ....\n\ncollections.default : 7.29699993134 s\n93 chars defaultdict(<type 'int'>, {u' ': 1036511, u'$': 110, u'(': 1748, u',': 77675, u'0': 3064, u'4': 2417, u'8': 2527, u'<': 2, u'@': 8, ....\n\nCPU Specs: 1.6GHz Intel Mobile Atom CPU\nAccording to that, dict.get is slowest and collections.defaultdict is fastest, try/except is also the fast one.\n\nEdit 2:\nAdded collections.Counter benchmarks, Its slower than dict.get and took 15s in my laptop\ncollections.Counter : 15.3439998627 s\n93 chars Counter({u' ': 1036511, u'e': 628234, u't': 444459, u'a': 395872, u'o': 382683, u'n': 362397, u'i': 348464,\n\n",
"I've written Char Counter C Extension to Python, looks like 300x faster than collections.Counter and 150x faster than collections.default(int)\nC Char Counter : 0.0469999313354 s\n93 chars {u' ': 1036511, u'$': 110, u'(': 1748, u',': 77675, u'0': 3064, u'4': 2417, u'8': 2527, u'<': 2, u'@': 8,\n\nHere is Char Counter C Extension Codes\nstatic PyObject *\nCharCounter(PyObject *self, PyObject *args, PyObject *keywds)\n{\n wchar_t *t1;unsigned l1=0;\n\n if (!PyArg_ParseTuple(args,\"u#\",&t1,&l1)) return NULL;\n\n PyObject *resultList,*itemTuple;\n\n for(unsigned i=0;i<=0xffff;i++)char_counter[i]=0;\n\n unsigned chlen=0;\n\n for(unsigned i=0;i<l1;i++){\n if(char_counter[t1[i]]==0)char_list[chlen++]=t1[i];\n char_counter[t1[i]]++;\n }\n\n resultList = PyList_New(0);\n\n for(unsigned i=0;i<chlen;i++){\n itemTuple = PyTuple_New(2);\n\n PyTuple_SetItem(itemTuple, 0,PyUnicode_FromWideChar(&char_list[i],1));\n PyTuple_SetItem(itemTuple, 1,PyInt_FromLong(char_counter[char_list[i]]));\n\n PyList_Append(resultList, itemTuple);\n Py_DECREF(itemTuple);\n\n };\n\n return resultList;\n}\n\nWhere char_counter, and char_list are malloc-ated at module level, so no need to malloc every time when function calls.\nchar_counter=(unsigned*)malloc(sizeof(unsigned)*0x10000);\nchar_list=(wchar_t*)malloc(sizeof(wchar_t)*0x10000);\n\nIt returns a List with Tuples\n[(u'T', 16282), (u'h', 287323), (u'e', 628234), (u' ', 1036511), (u'P', 8946), (u'r', 303977), (u'o', 382683), ...\n\nTo convert to dict format, just dict() will do.\ndict(CharCounter(text))\n\nPS: Benchmark included the time converting to dict\nCharCounter accept only Python Unicode String u\"\", if the text is utf8, need to do .decode(\"utf8\") in advance.\nInput Supports Unicode until Basic Multilingual Plane (BMP) - 0x0000 to 0xFFFF\n",
"No it's not the fastest, because you know that the characters have a limited range and you could use a list and direct indexing, using the numeric representation of the character, to store the frequencies.\n",
"It is very, very hard to beat dict. It is very highly tuned since almost everything in Python is dict-based.\n",
"I'm not familiar with python, but for finding frequencies, unless you know the range of frequencies (in which case you can use an array), dictionary is the way to go.\nIf you know your characters in a unicode, ASCII, etc. range, you can define an array with the correct number of values.\nHowever, this will change the space complexity of this from O(n) to O(possible n), but you will earn a time complexity improvement from O(n*(dictionary extraction/insertion time)) to O(n).\n",
"If you are really concerned about speed, you might consider first counting characters with integers and then obtaining frequencies through (float) division.\nHere are the numbers:\npython -mtimeit -s'x=0' 'x+=1' \n10000000 loops, best of 3: 0.0661 usec per loop\n\npython -mtimeit -s'x=0.' 'x+=1.'\n10000000 loops, best of 3: 0.0965 usec per loop\n\n",
"well, you can do it in the old fashioned style... as we know that there are not too many different characters and they are contiguous, we can use a plain array (or list here) and use the characters ordinal numbering for indexing:\ns = 1.0*len(text)\ncounts = [0]*256 # change this if working with unicode\nfor char in text: \n freqs[ord(char)]+=1\n\nfreqs = dict((chr(i), v/s) for i,v in enumerate(counts) if v)\n\nThis will be probably faster, but just by a constant factor, both methods should have the same complexity.\n",
"Using this code on Alice in Wonderland (163793 chars) and \"The Bible, Douay-Rheims Version\" (5649295 chars) from Project Gutenberg:\nfrom collections import defaultdict\nimport timeit\n\ndef countchars():\n f = open('8300-8.txt', 'rb')\n #f = open('11.txt')\n s = f.read()\n f.close()\n charDict = defaultdict(int)\n for aChar in s:\n charDict[aChar] += 1\n\n\nif __name__ == '__main__':\n tm = timeit.Timer('countchars()', 'from countchars import countchars') \n print tm.timeit(10)\n\nI get:\n2.27324003315 #Alice in Wonderland\n74.8686217403 #Bible\n\nThe ratio between the number of chars for both books is 0.029 and the ratio between the times is 0.030, so, the algorithm is O(n) with a very small constant factor. Fast enough for most (all?) purposes, I should think.\n",
"If the data is in a single byte encoding you can use numpy to accelerate the count process:\nimport numpy as np\n\ndef char_freq(data):\n counts = np.bincount(np.frombuffer(data, dtype=np.byte))\n freqs = counts.astype(np.double) / len(data)\n return dict((chr(idx), freq) for idx, freq in enumerate(freqs) if freq > 0)\n\nSome quick benchmarking shows that this is about 10x faster than aggregating to a defaultdict(int).\n",
"To avoid the try except overhead you can use a defaultdict.\n",
"Small speed up will be usage of dict.setdefault method, that way you will not pay rather big price for every new encountered character:\nfor char in text:\n freq[char] = freq.setdefault(char, 0.0) + P\n\nAs a sidenote: having bare except: is considered very bad practice.\n"
] |
[
47,
16,
10,
6,
5,
4,
2,
2,
2,
2,
1,
1
] |
[] |
[] |
[
"algorithm",
"frequency",
"probability",
"python"
] |
stackoverflow_0002522152_algorithm_frequency_probability_python.txt
|
Q:
mod_cgi , mod_fastcgi, mod_scgi , mod_wsgi, mod_python, FLUP. I don't know how many more. what is mod_php equivalent?
I recently learnt Python. I liked it. I just wanted to use it for web development. This thought caused all the troubles. But I like these troubles :)
Coming from PHP world where there is only one way standardized. I expected the same and searched for python & apache.
Setting up Python on Windows/ Apache? says
Stay away from mod_python. One common
misleading idea is that mod_python is
like mod_php, but for python. That is
not true.
So what is equivalent of mod_php in python?
I need little clarification on this one How Python web frameworks, WSGI and CGI fit together
CGI, FastCGI and SCGI are language agnostic. You can write CGI scripts in Perl, Python, C, bash, or even Assembly :). So, I guess mod_cgi , mod_fastcgi, mod_scgi are their corresponding apache modules. Right?
WSGI is some kind of optimized/improved inshort an efficient version specifically designed for python language only. In order to use this mod_wsgi is a way to go. right?
This leaves out mod_python. What is it then?
Apache -> mod_fastcgi -> FLUP (via CGI protocol) -> Django (via WSGI protocol)
Flup is another way to run with wsgi for any webserver that can speak FCGI, SCGI or AJP
What is FLUP? What is AJP? How did Django come in the picture?
These questions raise quetions about PHP. How is it actually running? What technology is it using? mod_php & mod_python what are the differences?
In future if I want to use Perl or Java then again will I have to get confused? Kindly can someone explain things clearly and give a Complete Picture.
A:
The standard way to deploy a Python application to the web is via WSGI. These days there's no reason to use anything else.
mod_wsgi is the Apache module that supports WSGI. Other web servers will have different names for their WSGI modules.
A:
There is no exact equivalent to mod_php in the Python world.
FastCGI, SCGI, and AJP run the web app as a separate process (daemon), and pass messages between the web server and it.
mod_python is used to embed Python code into the httpd process during any of the request phases.
mod_wsgi can run Python code in either daemon or embedded mode.
CGI is a protocol that runs a script/program every time a request is made.
FLUP is a set of adapters that can be used to convert one of those interfaces to another.
A:
mod_python is the closest equivalent of mod_php, but this doesn't mean that mod_python will suit your needs. For each programming language you have to enumerate all the possible options and choose the one you'll need.
For PHP, you have mod_php and mod_cgi, but from this two mod_cgi is inferior in almost all ways to mod_php so people usually choose the latter. (There are some alternatives, like suphp if you need more security, etc.)
For Python you have mod_cgi, which will run the python interpreter each time you make a request. Mod_python instead has python embedded so it's usually faster and simpler to do, but for large projects, or projects that are using a framework (like DJango) you will probably want to use mod_wsgi because it is the most resource-friendly.
For ruby you also have the option to use mod_cgi, but that will be way too slow. mod_ruby is also an option, but only for small programs. mod_fastcgi was usually the option for rails/merb and other ruby based web frameworks, but they are superseeded by mod_rails and mod_rack, which are esource-friendly. But for simple scripts the latter are a bit too heavy-weight.
For mono (asp.net) you have mod_mono, which is usually the only option.
For java you usually run a separate Tomcat/Jetty web server, and use mod_proxy.
Of course running a separate web server and use mod_proxy is usually an option for all the web frameworks, although it is mostly suitable for the development process only. For production environments you have to choose carefuly the best option (the one which is the mostly resource-friendly) your framework (django,rails,asp.net,etc.) needs
A:
mod_python is the most like mod_php in what it does (ie. it tries to do everything). That's not necessarily a good thing and I wouldn't recommend writing applications to the native mod_python interfaces today.
WSGI is some kind of optimized/improved inshort an efficient version specifically designed for python
The difference is WSGI is defined in the Python language itself: it specifies what objects and values your code will receive. [S|Fast]CGI are more concerned with bytes on the wire.
By writing your application to the WSGI standard (either directly, or using a framework that supports it), you are uncoupling the concerns of application-writing and deployment.
In order to use this mod_wsgi is a way to go. right?
It's a way to go, and definitely a good choice for Apache users, but far from the only one. Write to WSGI and you can deploy in a wide range of environments, including [S|Fast]CGI and mod_python.
|
mod_cgi , mod_fastcgi, mod_scgi , mod_wsgi, mod_python, FLUP. I don't know how many more. what is mod_php equivalent?
|
I recently learnt Python. I liked it. I just wanted to use it for web development. This thought caused all the troubles. But I like these troubles :)
Coming from PHP world where there is only one way standardized. I expected the same and searched for python & apache.
Setting up Python on Windows/ Apache? says
Stay away from mod_python. One common
misleading idea is that mod_python is
like mod_php, but for python. That is
not true.
So what is equivalent of mod_php in python?
I need little clarification on this one How Python web frameworks, WSGI and CGI fit together
CGI, FastCGI and SCGI are language agnostic. You can write CGI scripts in Perl, Python, C, bash, or even Assembly :). So, I guess mod_cgi , mod_fastcgi, mod_scgi are their corresponding apache modules. Right?
WSGI is some kind of optimized/improved inshort an efficient version specifically designed for python language only. In order to use this mod_wsgi is a way to go. right?
This leaves out mod_python. What is it then?
Apache -> mod_fastcgi -> FLUP (via CGI protocol) -> Django (via WSGI protocol)
Flup is another way to run with wsgi for any webserver that can speak FCGI, SCGI or AJP
What is FLUP? What is AJP? How did Django come in the picture?
These questions raise quetions about PHP. How is it actually running? What technology is it using? mod_php & mod_python what are the differences?
In future if I want to use Perl or Java then again will I have to get confused? Kindly can someone explain things clearly and give a Complete Picture.
|
[
"The standard way to deploy a Python application to the web is via WSGI. These days there's no reason to use anything else.\nmod_wsgi is the Apache module that supports WSGI. Other web servers will have different names for their WSGI modules.\n",
"There is no exact equivalent to mod_php in the Python world.\n\nFastCGI, SCGI, and AJP run the web app as a separate process (daemon), and pass messages between the web server and it.\nmod_python is used to embed Python code into the httpd process during any of the request phases.\nmod_wsgi can run Python code in either daemon or embedded mode.\nCGI is a protocol that runs a script/program every time a request is made.\nFLUP is a set of adapters that can be used to convert one of those interfaces to another.\n\n",
"mod_python is the closest equivalent of mod_php, but this doesn't mean that mod_python will suit your needs. For each programming language you have to enumerate all the possible options and choose the one you'll need.\nFor PHP, you have mod_php and mod_cgi, but from this two mod_cgi is inferior in almost all ways to mod_php so people usually choose the latter. (There are some alternatives, like suphp if you need more security, etc.)\nFor Python you have mod_cgi, which will run the python interpreter each time you make a request. Mod_python instead has python embedded so it's usually faster and simpler to do, but for large projects, or projects that are using a framework (like DJango) you will probably want to use mod_wsgi because it is the most resource-friendly.\nFor ruby you also have the option to use mod_cgi, but that will be way too slow. mod_ruby is also an option, but only for small programs. mod_fastcgi was usually the option for rails/merb and other ruby based web frameworks, but they are superseeded by mod_rails and mod_rack, which are esource-friendly. But for simple scripts the latter are a bit too heavy-weight.\nFor mono (asp.net) you have mod_mono, which is usually the only option.\nFor java you usually run a separate Tomcat/Jetty web server, and use mod_proxy.\nOf course running a separate web server and use mod_proxy is usually an option for all the web frameworks, although it is mostly suitable for the development process only. For production environments you have to choose carefuly the best option (the one which is the mostly resource-friendly) your framework (django,rails,asp.net,etc.) needs\n",
"mod_python is the most like mod_php in what it does (ie. it tries to do everything). That's not necessarily a good thing and I wouldn't recommend writing applications to the native mod_python interfaces today.\n\nWSGI is some kind of optimized/improved inshort an efficient version specifically designed for python\n\nThe difference is WSGI is defined in the Python language itself: it specifies what objects and values your code will receive. [S|Fast]CGI are more concerned with bytes on the wire.\nBy writing your application to the WSGI standard (either directly, or using a framework that supports it), you are uncoupling the concerns of application-writing and deployment.\n\nIn order to use this mod_wsgi is a way to go. right? \n\nIt's a way to go, and definitely a good choice for Apache users, but far from the only one. Write to WSGI and you can deploy in a wide range of environments, including [S|Fast]CGI and mod_python.\n"
] |
[
10,
7,
4,
2
] |
[] |
[] |
[
"apache",
"php",
"python"
] |
stackoverflow_0002532477_apache_php_python.txt
|
Q:
How do I make this simple list comprehension?
I'm new to python, and I'm trying to get to know the list comprehensions better.
I'm not even really sure if list comprehension is the word I'm looking for, since I'm not generating a list. But I am doing something similar.
This is what I am trying to do:
I have a list of numbers, the length of which is divisible by three.
So say I have nums = [1, 2, 3, 4, 5, 6]
I want to iterate over the list and get the sum of each group of three digits.
Currently I am doing this:
for i in range(0, len(nums), 3):
nsum = a + b + c for a, b, c in nums[i:i+3]
print(nsum)
I know this is wrong, but is there a way to do this? I'm sure I've overlooked something probably very simple... But I can't think of another way to do this.
A:
See sum(iterable[, start]) builtin, and use it on slices.
Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable‘s items are normally numbers, and are not allowed to be strings.
>>> nums
[1, 2, 3, 4, 5, 6]
>>> [sum(nums[i:i+3]) for i in range(0, len(nums),3)]
[6, 15]
>>>
A:
import itertools
nums = [1, 2, 3, 4, 5, 6]
print [a + b + c for a, b, c in itertools.izip(*[iter(nums)] * 3)]
A:
nums = [1, 2, 3, 4, 5, 6]
map(sum, itertools.izip(*[iter(nums)]*3))
|
How do I make this simple list comprehension?
|
I'm new to python, and I'm trying to get to know the list comprehensions better.
I'm not even really sure if list comprehension is the word I'm looking for, since I'm not generating a list. But I am doing something similar.
This is what I am trying to do:
I have a list of numbers, the length of which is divisible by three.
So say I have nums = [1, 2, 3, 4, 5, 6]
I want to iterate over the list and get the sum of each group of three digits.
Currently I am doing this:
for i in range(0, len(nums), 3):
nsum = a + b + c for a, b, c in nums[i:i+3]
print(nsum)
I know this is wrong, but is there a way to do this? I'm sure I've overlooked something probably very simple... But I can't think of another way to do this.
|
[
"See sum(iterable[, start]) builtin, and use it on slices.\n\nSums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable‘s items are normally numbers, and are not allowed to be strings. \n\n>>> nums\n[1, 2, 3, 4, 5, 6]\n>>> [sum(nums[i:i+3]) for i in range(0, len(nums),3)]\n[6, 15]\n>>> \n\n",
"import itertools\n\nnums = [1, 2, 3, 4, 5, 6]\n\nprint [a + b + c for a, b, c in itertools.izip(*[iter(nums)] * 3)]\n\n",
"nums = [1, 2, 3, 4, 5, 6]\nmap(sum, itertools.izip(*[iter(nums)]*3))\n\n"
] |
[
6,
4,
1
] |
[] |
[] |
[
"list_comprehension",
"python"
] |
stackoverflow_0002532525_list_comprehension_python.txt
|
Q:
How to implement this mechanism:
i want to implement a dynamic relation mechanism with python something like:
a:=10
b:=30
c:=a+b
print c
a+=20
print c
output:
40
60
c is always result of a+b.
so if a or b change, then c automatically updates value. i write a code in C# and do this by set and get mechanism. now want to translate it to python code for using in another program (FontLab Studio 5). I'm not so familiar with Python. does he have a get,set feature like C#? if not ho to implement one?
A:
This is probably overkill, but it illustrates how you should create getters/setters in Python and achieve the functionality you want:
class Calc(object):
def __init__(self, a = 0, b = 0):
self._a = a
self._b = b
@property
def a(self):
return self._a
@a.setter
def a(self, value):
self._a = value
@property
def b(self):
return self._b
@b.setter
def b(self, value):
self._b = value
@property
def c(self):
return self._a + self._b
def __str__(self):
return str(self.c)
calc = Calc()
calc.a = 1
calc.b = 2
print calc.c
calc.a += 10
print calc.c
If you don't want to make a and b a property, the code can be simplified:
class Calc(object):
def __init__(self, a = 0, b = 0):
self.a = a
self.b = b
@property
def c(self):
return self.a + self.b
def __str__(self):
return str(self.c)
A:
In your situation, c actually is a function which must be called.
You could use something like this:
a = 10
b = 30
c = lambda: a + b
print c()
a += 20
print c()
If you dislike that the method call is made explicit for c, you could use a general Calc object, which hides this implementation:
class Calc(object):
def __init__(self):
object.__setattr__(self, '_params', dict())
def __getattr__(self, name):
param = self._params[name]
if callable(param):
return param()
else:
return param
def __setattr__(self, name, value):
self._params[name] = value
def __delattr__(self, name):
del self._params[name]
And then you could do:
c = Calc()
c.a = 10
c.b = 30
c.c = lambda: c.a + c.b
print c.c
c.a += 20
print c.c
A:
New-style Python classes support properties.
A:
something like this:
class C:
def __init__(self):
self.x = 0
self.y = 0
def get(self):
return self.x + self.y
def __str__(self):
return self.__unicode__()
def __unicode__(self):
return str(self.get())
c = C()
c.x = 1
print c
c.y =2
print c
With new style classes and annotations you can probably make it better.
|
How to implement this mechanism:
|
i want to implement a dynamic relation mechanism with python something like:
a:=10
b:=30
c:=a+b
print c
a+=20
print c
output:
40
60
c is always result of a+b.
so if a or b change, then c automatically updates value. i write a code in C# and do this by set and get mechanism. now want to translate it to python code for using in another program (FontLab Studio 5). I'm not so familiar with Python. does he have a get,set feature like C#? if not ho to implement one?
|
[
"This is probably overkill, but it illustrates how you should create getters/setters in Python and achieve the functionality you want:\nclass Calc(object):\n def __init__(self, a = 0, b = 0):\n self._a = a\n self._b = b\n\n @property\n def a(self):\n return self._a\n\n @a.setter\n def a(self, value):\n self._a = value\n\n @property\n def b(self):\n return self._b\n\n @b.setter\n def b(self, value):\n self._b = value\n\n @property\n def c(self):\n return self._a + self._b\n\n def __str__(self):\n return str(self.c)\n\ncalc = Calc()\ncalc.a = 1\ncalc.b = 2\nprint calc.c\ncalc.a += 10\nprint calc.c\n\nIf you don't want to make a and b a property, the code can be simplified:\nclass Calc(object):\n def __init__(self, a = 0, b = 0):\n self.a = a\n self.b = b\n\n @property\n def c(self):\n return self.a + self.b\n\n def __str__(self):\n return str(self.c)\n\n",
"In your situation, c actually is a function which must be called.\nYou could use something like this:\na = 10\nb = 30\nc = lambda: a + b\n\nprint c()\na += 20\nprint c()\n\nIf you dislike that the method call is made explicit for c, you could use a general Calc object, which hides this implementation:\nclass Calc(object):\n def __init__(self):\n object.__setattr__(self, '_params', dict())\n\n def __getattr__(self, name):\n param = self._params[name]\n if callable(param):\n return param()\n else:\n return param\n\n def __setattr__(self, name, value):\n self._params[name] = value\n\n def __delattr__(self, name):\n del self._params[name]\n\nAnd then you could do:\nc = Calc()\nc.a = 10\nc.b = 30\nc.c = lambda: c.a + c.b\n\nprint c.c\nc.a += 20\nprint c.c\n\n",
"New-style Python classes support properties.\n",
"something like this:\nclass C:\n def __init__(self):\n self.x = 0\n self.y = 0\n\n def get(self):\n return self.x + self.y\n\n def __str__(self):\n return self.__unicode__()\n\n def __unicode__(self):\n return str(self.get())\n\nc = C()\nc.x = 1\nprint c\nc.y =2\nprint c\n\nWith new style classes and annotations you can probably make it better.\n"
] |
[
4,
3,
2,
1
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002532664_python.txt
|
Q:
What is the best library in python to use to interface with a SQL database?
I am currently processing text/html data and I wish to store my results in some sort of database. My current setup is Pydev with Eclipse.
What is the best non-distributed database to use with my current development environment?
What is the best library in python to use to interface with suggested database?
A:
If you won't be using the database itself from multiple locations at once then you can use the built-in sqlite3 module with a SQLite database.
A:
"Best" of course depends on your needs, and aside from "text/html data" you haven't given us anything to go on. One might say that a relational database is not the best way to store text/HTML data, but again without more info who could really say?
Given that you limited the answers to "SQL" in your title, however, I can at least suggest that the sqlalchemy package is quite possibly the "best" way to get to the database.
Ignacio's suggestion of using SQLite as the underlying database is also a good starting point -- and an ending point, as he hints, if an "embedded" database suffices for your needs. If you use sqlalchemy to get to it, you can keep the SQL out of your code, and if the need arises you can trivially swap SQLite out for a more powerful solution (e.g. PostgreSQL).
|
What is the best library in python to use to interface with a SQL database?
|
I am currently processing text/html data and I wish to store my results in some sort of database. My current setup is Pydev with Eclipse.
What is the best non-distributed database to use with my current development environment?
What is the best library in python to use to interface with suggested database?
|
[
"If you won't be using the database itself from multiple locations at once then you can use the built-in sqlite3 module with a SQLite database.\n",
"\"Best\" of course depends on your needs, and aside from \"text/html data\" you haven't given us anything to go on. One might say that a relational database is not the best way to store text/HTML data, but again without more info who could really say?\nGiven that you limited the answers to \"SQL\" in your title, however, I can at least suggest that the sqlalchemy package is quite possibly the \"best\" way to get to the database. \nIgnacio's suggestion of using SQLite as the underlying database is also a good starting point -- and an ending point, as he hints, if an \"embedded\" database suffices for your needs. If you use sqlalchemy to get to it, you can keep the SQL out of your code, and if the need arises you can trivially swap SQLite out for a more powerful solution (e.g. PostgreSQL).\n"
] |
[
2,
2
] |
[] |
[] |
[
"database",
"eclipse",
"python"
] |
stackoverflow_0002532135_database_eclipse_python.txt
|
Q:
Free Cryptography libraries
What are the most stable and useful Cryptography libraries, that they are:
written with/for python, c++, c#, .net
opensource, GNU, or other free license
A:
For C# and Java, there is bouncycastle. The granddaddy of crypto libraries is openssl. For C++, another very mature library is crypto++.
A:
The standard Python library (implementing common ciphers like AES and RSA) is PyCrypto. It doesn't support things like PKCS yet, however. There is a partial Python wrapper for the Crypto++ library given by PyCryptopp, which you may find useful.
The OpenSSL library is also wrapped for Python by PyOpenSSL. A Python implementation of SSH is Paramiko.
A:
Take a look at KeyCzar
Some features of Keyczar include:
A simple API
Key rotation and versioning
Safe default algorithms, modes, and key lengths
Automated generation of initialization vectors and ciphertext signatures
Java, Python, and C++ implementations
International support in Java (Python coming soon)
Doesn't seem to have C# support though.
A:
NSS works with C++, and has bindings for Java and Python, although I'm not sure if it has .NET/Mono bindings yet.
|
Free Cryptography libraries
|
What are the most stable and useful Cryptography libraries, that they are:
written with/for python, c++, c#, .net
opensource, GNU, or other free license
|
[
"For C# and Java, there is bouncycastle. The granddaddy of crypto libraries is openssl. For C++, another very mature library is crypto++.\n",
"The standard Python library (implementing common ciphers like AES and RSA) is PyCrypto. It doesn't support things like PKCS yet, however. There is a partial Python wrapper for the Crypto++ library given by PyCryptopp, which you may find useful.\nThe OpenSSL library is also wrapped for Python by PyOpenSSL. A Python implementation of SSH is Paramiko.\n",
"Take a look at KeyCzar \n\nSome features of Keyczar include:\n\nA simple API\nKey rotation and versioning\nSafe default algorithms, modes, and key lengths\nAutomated generation of initialization vectors and ciphertext signatures\nJava, Python, and C++ implementations\nInternational support in Java (Python coming soon)\n\n\nDoesn't seem to have C# support though.\n",
"NSS works with C++, and has bindings for Java and Python, although I'm not sure if it has .NET/Mono bindings yet.\n"
] |
[
2,
2,
1,
0
] |
[] |
[] |
[
"c#",
"c++",
"cryptography",
"python"
] |
stackoverflow_0002532983_c#_c++_cryptography_python.txt
|
Q:
how to convert Python 3 to Python 2 code?
I had written a program in Python 3, but now want to convert it into Python 2 code. Are there any utilities to do that automatically?
A:
You want 3to2 for that.
|
how to convert Python 3 to Python 2 code?
|
I had written a program in Python 3, but now want to convert it into Python 2 code. Are there any utilities to do that automatically?
|
[
"You want 3to2 for that.\n"
] |
[
47
] |
[] |
[] |
[
"python",
"python_3.x"
] |
stackoverflow_0002533217_python_python_3.x.txt
|
Q:
unittest tests reuse for family of classes
I have problem organizing my unittest based class test for family of tests. For example assume I implement a "dictionary" interface, and have 5 different implementations want to testing.
I do write one test class that tests a dictionary interface. But how can I nicely reuse it to test my all classes? So far I do ugly:
DictType = hashtable.HashDict
In top of file and then use DictType in test class. To test another class I manually change the DictType to something else.
How can do this otherwise? Can't pass arguments to unittest classes so is there a nicer way?
A:
The way I tackle this with standard unittest is by subclassing -- overriding data is as easy as overriding methods, after all.
So, I have a base class for the tests:
class MappingTestBase(unittest.TestCase):
dictype = None
# write all the tests using self.dictype
and subclasses:
class HashtableTest(MappingTestBase):
dictype = hashtable.HashDict
class OtherMappingTest(MappingTestBase):
dictype = othermodule.mappingimpl
Here, the subclasses need override only dictype. Sometimes it's handier to also expose MappingTestBase use "hook methods". When the types being tested don't have exactly identical interfaces in all cases, this can be worked around by having the subclasses override the hook methods as needed -- this is the "Template Method" design pattern, see e.g. this page which has a commented and timelined collection of a couple of video lectures of mine on design patterns -- part II is about Template Method and variants thereof for about the first 30 minutes.
You don't have to have all of this in a single module, of course (though I often find it clearest to lay things out this way, you could also make one separate test module per type you're testing, each importing the module with the abstract base class).
A:
You could look at testscenarios which allows you to set a list called scenarios. The code then generates a version of the test class for each value/scenario in the list
See the example
So in your case the scenarios would be a list like [ {dicttype:hashtable.HashDict}, {dicttype:otherimpl.class}, ] and use self.dicttype in your test code.
|
unittest tests reuse for family of classes
|
I have problem organizing my unittest based class test for family of tests. For example assume I implement a "dictionary" interface, and have 5 different implementations want to testing.
I do write one test class that tests a dictionary interface. But how can I nicely reuse it to test my all classes? So far I do ugly:
DictType = hashtable.HashDict
In top of file and then use DictType in test class. To test another class I manually change the DictType to something else.
How can do this otherwise? Can't pass arguments to unittest classes so is there a nicer way?
|
[
"The way I tackle this with standard unittest is by subclassing -- overriding data is as easy as overriding methods, after all.\nSo, I have a base class for the tests:\nclass MappingTestBase(unittest.TestCase):\n dictype = None\n # write all the tests using self.dictype\n\nand subclasses:\nclass HashtableTest(MappingTestBase):\n dictype = hashtable.HashDict\n\nclass OtherMappingTest(MappingTestBase):\n dictype = othermodule.mappingimpl\n\nHere, the subclasses need override only dictype. Sometimes it's handier to also expose MappingTestBase use \"hook methods\". When the types being tested don't have exactly identical interfaces in all cases, this can be worked around by having the subclasses override the hook methods as needed -- this is the \"Template Method\" design pattern, see e.g. this page which has a commented and timelined collection of a couple of video lectures of mine on design patterns -- part II is about Template Method and variants thereof for about the first 30 minutes.\nYou don't have to have all of this in a single module, of course (though I often find it clearest to lay things out this way, you could also make one separate test module per type you're testing, each importing the module with the abstract base class).\n",
"You could look at testscenarios which allows you to set a list called scenarios. The code then generates a version of the test class for each value/scenario in the list \nSee the example\nSo in your case the scenarios would be a list like [ {dicttype:hashtable.HashDict}, {dicttype:otherimpl.class}, ] and use self.dicttype in your test code.\n"
] |
[
5,
0
] |
[] |
[] |
[
"python",
"unit_testing"
] |
stackoverflow_0002532197_python_unit_testing.txt
|
Q:
Python: How do sets work
I have a list of objects which I want to turn into a set. My objects contain a few fields that some of which are o.id and o.area. I want two objects to be equal if these two fields are the same. ie: o1==o2 if and only if o1.area==o2.area and o1.id==o2.id.
I tried over-writing __eq__ and __cmp__ but I get the error: TypeError: unhashable instance.
What should I over-write?
A:
Define the __hash__ method to return a meaningful hash based on the id and area fields. E.g.:
def __hash__(self):
return hash(self.id) ^ hash(self.area)
A:
"TypeError: unhashable instance." error is probably due to old-style class definition i.e.:
class A:
pass
Use new style instead:
class A(object):
pass
If you override __cmp__ function you should override __hash__ for using your object in sets. In the other case hash considers all object instances as unequal and __cmp__ function will never be called.
|
Python: How do sets work
|
I have a list of objects which I want to turn into a set. My objects contain a few fields that some of which are o.id and o.area. I want two objects to be equal if these two fields are the same. ie: o1==o2 if and only if o1.area==o2.area and o1.id==o2.id.
I tried over-writing __eq__ and __cmp__ but I get the error: TypeError: unhashable instance.
What should I over-write?
|
[
"Define the __hash__ method to return a meaningful hash based on the id and area fields. E.g.:\ndef __hash__(self):\n return hash(self.id) ^ hash(self.area)\n\n",
"\"TypeError: unhashable instance.\" error is probably due to old-style class definition i.e.: \nclass A:\n pass\n\nUse new style instead:\nclass A(object):\n pass\n\nIf you override __cmp__ function you should override __hash__ for using your object in sets. In the other case hash considers all object instances as unequal and __cmp__ function will never be called. \n"
] |
[
38,
9
] |
[] |
[] |
[
"hash",
"python",
"set"
] |
stackoverflow_0002532365_hash_python_set.txt
|
Q:
How to use a python api on iPhone?
There is an "Unofficial Plurk API in Python".
Plurk is a twitter-like website.
Can I use the API(python) from Objective-C? Or i have to port them?
A:
Apple's iPhone developer license prohibits applications that use interpreted code. So, python is out, unfortunately.
A:
The way I see it, one option is to try this this.
Alternatively, ths plurk api (which is really more of a python-automated abstraction than an API) isn't very big and is unlikely to take very long to port. Apart from being exceptionally simple code. The author's done all the legwork, defining urls and associated functions and so on.
A:
The iPhone SDK will not allow you to run any Python code. You need to convert it to C, C++, Objective-C or ObjectiveC++.
A:
Well, Plurk has an official API now, and I wrote an Objective-C library to connect to Plurk. Maybe you are interested to give it a try.
http://github.com/zonble/ObjectivePlurk
|
How to use a python api on iPhone?
|
There is an "Unofficial Plurk API in Python".
Plurk is a twitter-like website.
Can I use the API(python) from Objective-C? Or i have to port them?
|
[
"Apple's iPhone developer license prohibits applications that use interpreted code. So, python is out, unfortunately.\n",
"The way I see it, one option is to try this this.\nAlternatively, ths plurk api (which is really more of a python-automated abstraction than an API) isn't very big and is unlikely to take very long to port. Apart from being exceptionally simple code. The author's done all the legwork, defining urls and associated functions and so on.\n",
"The iPhone SDK will not allow you to run any Python code. You need to convert it to C, C++, Objective-C or ObjectiveC++.\n",
"Well, Plurk has an official API now, and I wrote an Objective-C library to connect to Plurk. Maybe you are interested to give it a try.\nhttp://github.com/zonble/ObjectivePlurk\n"
] |
[
4,
3,
2,
1
] |
[
"Unfortunately, you can only do what Apple allows you to do (they are VERY controlling). However, if you jail break your device (this violates your usage agreement with Apple) you can do many, many things with what I consider to be an amazing device (unfortunatly, Apple limits it's true possibilities). \n"
] |
[
-6
] |
[
"iphone",
"objective_c",
"python"
] |
stackoverflow_0000768941_iphone_objective_c_python.txt
|
Q:
How to setup and teardown temporary django db for unit testing?
I would like to have a python module containing some unit tests that I can pass to hg bisect --command.
The unit tests are testing some functionality of a django app, but I don't think I can use hg bisect --command manage.py test mytestapp because mytestapp would have to be enabled in settings.py, and the edits to settings.py would be clobbered when hg bisect updates the working directory.
Therefore, I would like to know if something like the following is the best way to go:
import functools, os, sys, unittest
sys.path.append(path_to_myproject)
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
def with_test_db(func):
"""Decorator to setup and teardown test db."""
@functools.wraps
def wrapper(*args, **kwargs):
try:
# Set up temporary django db
func(*args, **kwargs)
finally:
# Tear down temporary django db
class TestCase(unittest.TestCase):
@with_test_db
def test(self):
# Do some tests using the temporary django db
self.fail('Mark this revision as bad.')
if '__main__' == __name__:
unittest.main()
I should be most grateful if you could advise either:
If there is a simpler way, perhaps subclassing django.test.TestCase but not editing settings.py or, if not;
What the lines above that say "Set up temporary django db" and "Tear down temporary django db" should be?
A:
Cracked it. I now have one python file completely independent of any django app that can run unit tests with a test database:
#!/usr/bin/env python
"""Run a unit test and return result.
This can be used with `hg bisect`.
It is assumed that this file resides in the same dir as settings.py
"""
import os
from os.path import abspath, dirname
import sys
import unittest
# Set up django
project_dir = abspath(dirname(dirname(__file__)))
sys.path.insert(0, project_dir)
os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'
from django.db import connection
from django.test import TestCase
from django.test.utils import setup_test_environment, teardown_test_environment
from myproject import settings
from myproject.myapp.models import MyModel
class MyTestCase(TestCase):
def test_something(self):
# A failed assertion will make unittest.main() return non-zero
# which if used with `hg bisect` will mark the revision as bad
self.assertEqual(0, len(MyModel.objects.all())) # and so on
if '__main__' == __name__:
try:
setup_test_environment()
settings.DEBUG = False
verbosity = 0
old_database_name = settings.DATABASE_NAME
connection.creation.create_test_db(verbosity)
unittest.main()
finally:
connection.creation.destroy_test_db(old_database_name, verbosity)
teardown_test_environment()
A:
You must use the internal Django TestCase to do so.
from django.test import TestCase
class TestCase(TestCase):
# before every call to setUp(), the db is automatically
# set back to the state is was after the first syncdb then
# all these fixture files will be loaded in the db
fixtures = ['mammals.json', 'birds']
# put whatever you want here, you don't need to call the
# super()
def setUp(self):
# Test definitions as before.
call_setup_methods()
def test(self):
# Do some tests using the temporary django db
self.fail('Mark this revision as bad.')
It's fully compatible with unittest so your code don't need to change much.
You can learn more about django.test, fixtures, flush and loaddata commands.
If you do want to use a decorator to do the job, you can use the call_command to use in your python program any django command. e.g :
from django.core.management import call_command
call_command('flush', 'myapp')
call_command('loaddata', 'myapp')
|
How to setup and teardown temporary django db for unit testing?
|
I would like to have a python module containing some unit tests that I can pass to hg bisect --command.
The unit tests are testing some functionality of a django app, but I don't think I can use hg bisect --command manage.py test mytestapp because mytestapp would have to be enabled in settings.py, and the edits to settings.py would be clobbered when hg bisect updates the working directory.
Therefore, I would like to know if something like the following is the best way to go:
import functools, os, sys, unittest
sys.path.append(path_to_myproject)
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
def with_test_db(func):
"""Decorator to setup and teardown test db."""
@functools.wraps
def wrapper(*args, **kwargs):
try:
# Set up temporary django db
func(*args, **kwargs)
finally:
# Tear down temporary django db
class TestCase(unittest.TestCase):
@with_test_db
def test(self):
# Do some tests using the temporary django db
self.fail('Mark this revision as bad.')
if '__main__' == __name__:
unittest.main()
I should be most grateful if you could advise either:
If there is a simpler way, perhaps subclassing django.test.TestCase but not editing settings.py or, if not;
What the lines above that say "Set up temporary django db" and "Tear down temporary django db" should be?
|
[
"Cracked it. I now have one python file completely independent of any django app that can run unit tests with a test database:\n#!/usr/bin/env python\n\"\"\"Run a unit test and return result.\n\nThis can be used with `hg bisect`.\nIt is assumed that this file resides in the same dir as settings.py\n\n\"\"\"\n\nimport os\nfrom os.path import abspath, dirname\nimport sys\nimport unittest\n\n# Set up django\nproject_dir = abspath(dirname(dirname(__file__)))\nsys.path.insert(0, project_dir)\nos.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings'\n\nfrom django.db import connection\nfrom django.test import TestCase\nfrom django.test.utils import setup_test_environment, teardown_test_environment\n\nfrom myproject import settings\nfrom myproject.myapp.models import MyModel\n\n\nclass MyTestCase(TestCase):\n\n def test_something(self):\n # A failed assertion will make unittest.main() return non-zero\n # which if used with `hg bisect` will mark the revision as bad\n self.assertEqual(0, len(MyModel.objects.all())) # and so on\n\n\nif '__main__' == __name__:\n try:\n setup_test_environment()\n settings.DEBUG = False \n verbosity = 0\n old_database_name = settings.DATABASE_NAME\n connection.creation.create_test_db(verbosity)\n unittest.main()\n finally:\n connection.creation.destroy_test_db(old_database_name, verbosity)\n teardown_test_environment()\n\n",
"You must use the internal Django TestCase to do so. \nfrom django.test import TestCase\n\nclass TestCase(TestCase):\n\n # before every call to setUp(), the db is automatically \n # set back to the state is was after the first syncdb then\n # all these fixture files will be loaded in the db \n fixtures = ['mammals.json', 'birds']\n\n # put whatever you want here, you don't need to call the\n # super()\n def setUp(self):\n # Test definitions as before.\n call_setup_methods()\n\n def test(self):\n # Do some tests using the temporary django db\n self.fail('Mark this revision as bad.')\n\nIt's fully compatible with unittest so your code don't need to change much. \nYou can learn more about django.test, fixtures, flush and loaddata commands.\nIf you do want to use a decorator to do the job, you can use the call_command to use in your python program any django command. e.g :\nfrom django.core.management import call_command\n\ncall_command('flush', 'myapp')\ncall_command('loaddata', 'myapp')\n\n"
] |
[
10,
5
] |
[] |
[] |
[
"django",
"mercurial",
"python",
"unit_testing"
] |
stackoverflow_0002533457_django_mercurial_python_unit_testing.txt
|
Q:
Standardizing a Release/Tools group on a specific language
I'm part of a six-member build and release team for an embedded software company. We also support a lot of developer tools, such as Atlassian's Fisheye, Jira, etc., Perforce, Bugzilla, AnthillPro, and a couple of homebrew tools (like my Django release notes generator).
Most of the time, our team just writes little plugins for larger apps (ex: customize workflows in Anthill), long-term utility scripts (package up a release for QA), or things like Perforce triggers (don't let people check into a specific branch unless their change description includes a bug number; authenticate against Active Directory instead of Perforce's internal passwords). That's about the scale of our problems, although we sometimes tackle something slightly more sizable.
My boss, who is reasonably technical, has asked us to standardize on one or two languages so we can more easily substitute for each other. He's advocating bash scripts and Perl, due to their universality and simplicity. I can see his point--we mostly do "glue", so why not use "glue" languages rather than saddle ourselves with something designed for much larger projects? Since some of the tools we work with are Java-based, we do need to use something that speaks JVM sometimes. (The path of least resistance for these projects is BeanShell and Groovy.) I feel a tremendous itch toward language advocacy, but I'm trying to avoid saying "We should use Python 'cause I like it and Perl is gross."
Instead, I'm trying to come up with a good approach to defining our problem set: what problems do we solve with scripts? Would we benefit from a library of common functions by our team, or are most of our projects more isolated? What is it reasonable to expect my co-workers to learn? What languages give us the most ease of development and ease of modification?
Can you folks suggest some useful ways to approach this problem, both for my own thinking process and to help me facilitate some brainstorming among my coworkers?
A:
Two points:
"Eww Perl gross" is somewhat of an urban legend. You can write great clean self-documenting code in Perl, and your can write write-only code in pretty much any language. It's a property of a developer, not a language.
Just because you're writing glue code, doesn't mean the code has to suck like some glue hacks tend to be.
From many threads comparing Perl vs Python on SO, it appears to me that Perl's CPAN is more expansive than Python's repository, but I have no experience with Python and can't substantiate with real comparison.
BUT, one thing I do know. After 5 seconds search, CPAN has a JIRA module. Whether that's a good factor for you or not, that's up to you.
A:
Google standardized on Python for such tasks (and many more) a bit before I joined the company; as far as I know, huge advantages such as Python's great implementations on the JVM and .NET didn't even play a role in the decision -- it was all about readability. At the time (and to some extent, even now) the theory at Google was that every engineer must be able, at need, to tweak every part of the codebase -- including of course build scripts, spiders (which were in Python at the time), and so forth. Demanding of engineers already proficient in C++ and Java to learn many more "scripting" languages (Python, Perl, Bash, Awk, Sed, and so forth) was simply unconsciounable: one had to be selected. Given that constraint, Python was the clear choice (under other constraints, Perl might also have been -- but I can't see the inevitable mix of Bash, Awk and Sed ever competing on such grounds!_) -- and that's how I ended up working there, a bit later;-).
Given that the overall potential of Python vs Ruby vs Perl vs PHP vs Bash + Awk + Sed vs ... is roughly equal, picking one is clearly a winner -- and Python has clean readability, strong implementations on JVM and .NET as big vigorishes. Seriously, I can only think of Javascript (inevitable for client-side work, now rich with strong implementations such as V8) as a possible "competitor" (unfortunately, JS inevitably carries on a lot of baggage for backwards compatibility -- unless you can use a use strict;-like constraint to help on that, it must be an important downside).
A:
I don't think anyone is going to be able to solve your problem on Stackoverflow. Your choice of tools, methods, and process are much more affected by social constraints, e.g. what your boss wants and what you want, then technical merits. That's not necessarily bad.
The short answer is "Use what is going to be most pleasing to the developers". If everyone likes Python more than Perl, for whatever reason, they are probably going to get more done in Python. If they like Ruby more than Python, it's the same thing.
Some things to evaluate as part of your selection:
What do the developers already know?
What are they most willing to learn?
How much weekly time can your team spend learning new things (e.g. lunch seminars, formal classes, etc)?
What do most people in the community use to work with the tool you need to support? For instance, Fisheye has a Java API, and some REST examples for Perl and Python. If you're writing Fisheye extensions, Java seems to be the win there. If you're merely accessing Fisheye data, any language can use the REST stuff.
What is most of your code base in already? What can you replace and what do you have to continue to support? I find that many companies can't answer this question because every developer seems to add two new technologies they don't tell anyone about. :)
Which platforms do you need to support? Some languages have platform specific issues, and I don't mean just Windows vs. Unix. Do you have legacy hardware you have to support? Does your tool work on that stuff?
How much of the stuff you produce can benefit other parts of the company? What are other teams using?
Do the people advocating one tool know it well enough to be its champion? I ask What are five things he hate about your favorite language? If people can't name five valid things that are wrong with their language or tool, they don't have enough experience with it.
The Longer Answer
People tend to try to reduce this to a technical argument because they are afraid to admit their biases or examine why they think what they think. Your boss might favor bash and Perl because that's what he did a lot of work in when he was getting started. You might like Python because you have a personal affinity for the way Python does things. I like Perl because I like its flexibility and DWIMmery. Like any social situation, different people are going to be attracted to different parts of different things. Just because you like chocolate doesn't make vanilla evil. I could give you lots of good arguments why Perl can be useful, but that doesn't mean that something else can't give you the same value.
What problems do we solve with scripts?
That one you have to answer for yourself. :)
Would we benefit from a library of common functions by our team, or are most of our projects more isolated?
This is most likely a good thing in Python, Perl, Ruby, Java, and almost any other language that you might choose. I think this part of your requirement is language agnostic. No matter which one you choose, you'll probably want to do this.
What is it reasonable to expect my co-workers to learn?
A good developer should be able to work with several different languages at least to an apprentice level. Those languages should include ones that have vastly different assumptions about how people express problems, say, for example, the set { Smalltalk Perl C Lisp Java }.
The best developers I've hired and worked with have always wanted to use the right tool for the job instead of making the job right for the tool. They might have their favorite language, but they didn't grouse (too much) about using a different tool when it made more sense.
Many "developers", however, seem to think that they are getting paid to play with their favorite tool. You need to convert them into people who think they have a toolbox to solve problems that create business value.
And remember, you never stop learning. As a developer you don't have to choose one language then defend it with your life, forsaking all others, in sickness and in health, and so on. Good developers are going to continue to track new technologies and evaluate them for usefulness for their tasks. Just because you choose one tool over another doesn't mean you stop paying attention.
No matter what you choose, someone is going to complain. Don't look for the solution that makes everyone happy. There isn't one, short of getting rid of the developers who aren't happy.
What languages give us the most ease of development and ease of modification?
A skilled practitioner in just about any language will think that his chosen language is the easiest to develop, modify, and maintain. Unskilled practitioners tend to blame the language and the tools for their problems. Some languages have steeper learning curves, and some have bigger payouts. A person's tolerance with immediate gratification is a big factor here.
That being said, different languages have developed different cultures and different toolsets. Perl people tend to like vi or emacs, Ruby people tend to like TextMate, Java people tend to like Eclipse or IntelliJ. That's not always true, but the culture that evolves around the tools are often more important than the technical details of the tool. If your developers like a particular type of tool, they are probably going to like the language that has a culture built around that sort of tool.
Some processes and tools take more time to get used to or require more education, but they can have larger advantages when used properly. Other tools get you started sooner but might not give you a path to bigger and greater things, such as cross-team development. The trick, however, is to not code to the tools so you aren't stuck in any particular toolset.
|
Standardizing a Release/Tools group on a specific language
|
I'm part of a six-member build and release team for an embedded software company. We also support a lot of developer tools, such as Atlassian's Fisheye, Jira, etc., Perforce, Bugzilla, AnthillPro, and a couple of homebrew tools (like my Django release notes generator).
Most of the time, our team just writes little plugins for larger apps (ex: customize workflows in Anthill), long-term utility scripts (package up a release for QA), or things like Perforce triggers (don't let people check into a specific branch unless their change description includes a bug number; authenticate against Active Directory instead of Perforce's internal passwords). That's about the scale of our problems, although we sometimes tackle something slightly more sizable.
My boss, who is reasonably technical, has asked us to standardize on one or two languages so we can more easily substitute for each other. He's advocating bash scripts and Perl, due to their universality and simplicity. I can see his point--we mostly do "glue", so why not use "glue" languages rather than saddle ourselves with something designed for much larger projects? Since some of the tools we work with are Java-based, we do need to use something that speaks JVM sometimes. (The path of least resistance for these projects is BeanShell and Groovy.) I feel a tremendous itch toward language advocacy, but I'm trying to avoid saying "We should use Python 'cause I like it and Perl is gross."
Instead, I'm trying to come up with a good approach to defining our problem set: what problems do we solve with scripts? Would we benefit from a library of common functions by our team, or are most of our projects more isolated? What is it reasonable to expect my co-workers to learn? What languages give us the most ease of development and ease of modification?
Can you folks suggest some useful ways to approach this problem, both for my own thinking process and to help me facilitate some brainstorming among my coworkers?
|
[
"Two points:\n\n\"Eww Perl gross\" is somewhat of an urban legend. You can write great clean self-documenting code in Perl, and your can write write-only code in pretty much any language. It's a property of a developer, not a language. \nJust because you're writing glue code, doesn't mean the code has to suck like some glue hacks tend to be.\nFrom many threads comparing Perl vs Python on SO, it appears to me that Perl's CPAN is more expansive than Python's repository, but I have no experience with Python and can't substantiate with real comparison.\nBUT, one thing I do know. After 5 seconds search, CPAN has a JIRA module. Whether that's a good factor for you or not, that's up to you.\n\n",
"Google standardized on Python for such tasks (and many more) a bit before I joined the company; as far as I know, huge advantages such as Python's great implementations on the JVM and .NET didn't even play a role in the decision -- it was all about readability. At the time (and to some extent, even now) the theory at Google was that every engineer must be able, at need, to tweak every part of the codebase -- including of course build scripts, spiders (which were in Python at the time), and so forth. Demanding of engineers already proficient in C++ and Java to learn many more \"scripting\" languages (Python, Perl, Bash, Awk, Sed, and so forth) was simply unconsciounable: one had to be selected. Given that constraint, Python was the clear choice (under other constraints, Perl might also have been -- but I can't see the inevitable mix of Bash, Awk and Sed ever competing on such grounds!_) -- and that's how I ended up working there, a bit later;-).\nGiven that the overall potential of Python vs Ruby vs Perl vs PHP vs Bash + Awk + Sed vs ... is roughly equal, picking one is clearly a winner -- and Python has clean readability, strong implementations on JVM and .NET as big vigorishes. Seriously, I can only think of Javascript (inevitable for client-side work, now rich with strong implementations such as V8) as a possible \"competitor\" (unfortunately, JS inevitably carries on a lot of baggage for backwards compatibility -- unless you can use a use strict;-like constraint to help on that, it must be an important downside).\n",
"I don't think anyone is going to be able to solve your problem on Stackoverflow. Your choice of tools, methods, and process are much more affected by social constraints, e.g. what your boss wants and what you want, then technical merits. That's not necessarily bad. \nThe short answer is \"Use what is going to be most pleasing to the developers\". If everyone likes Python more than Perl, for whatever reason, they are probably going to get more done in Python. If they like Ruby more than Python, it's the same thing. \nSome things to evaluate as part of your selection:\n\nWhat do the developers already know?\nWhat are they most willing to learn?\nHow much weekly time can your team spend learning new things (e.g. lunch seminars, formal classes, etc)? \nWhat do most people in the community use to work with the tool you need to support? For instance, Fisheye has a Java API, and some REST examples for Perl and Python. If you're writing Fisheye extensions, Java seems to be the win there. If you're merely accessing Fisheye data, any language can use the REST stuff.\nWhat is most of your code base in already? What can you replace and what do you have to continue to support? I find that many companies can't answer this question because every developer seems to add two new technologies they don't tell anyone about. :)\nWhich platforms do you need to support? Some languages have platform specific issues, and I don't mean just Windows vs. Unix. Do you have legacy hardware you have to support? Does your tool work on that stuff?\nHow much of the stuff you produce can benefit other parts of the company? What are other teams using?\nDo the people advocating one tool know it well enough to be its champion? I ask What are five things he hate about your favorite language? If people can't name five valid things that are wrong with their language or tool, they don't have enough experience with it.\n\nThe Longer Answer\nPeople tend to try to reduce this to a technical argument because they are afraid to admit their biases or examine why they think what they think. Your boss might favor bash and Perl because that's what he did a lot of work in when he was getting started. You might like Python because you have a personal affinity for the way Python does things. I like Perl because I like its flexibility and DWIMmery. Like any social situation, different people are going to be attracted to different parts of different things. Just because you like chocolate doesn't make vanilla evil. I could give you lots of good arguments why Perl can be useful, but that doesn't mean that something else can't give you the same value.\nWhat problems do we solve with scripts?\nThat one you have to answer for yourself. :)\nWould we benefit from a library of common functions by our team, or are most of our projects more isolated?\nThis is most likely a good thing in Python, Perl, Ruby, Java, and almost any other language that you might choose. I think this part of your requirement is language agnostic. No matter which one you choose, you'll probably want to do this.\nWhat is it reasonable to expect my co-workers to learn?\nA good developer should be able to work with several different languages at least to an apprentice level. Those languages should include ones that have vastly different assumptions about how people express problems, say, for example, the set { Smalltalk Perl C Lisp Java }. \nThe best developers I've hired and worked with have always wanted to use the right tool for the job instead of making the job right for the tool. They might have their favorite language, but they didn't grouse (too much) about using a different tool when it made more sense.\nMany \"developers\", however, seem to think that they are getting paid to play with their favorite tool. You need to convert them into people who think they have a toolbox to solve problems that create business value.\nAnd remember, you never stop learning. As a developer you don't have to choose one language then defend it with your life, forsaking all others, in sickness and in health, and so on. Good developers are going to continue to track new technologies and evaluate them for usefulness for their tasks. Just because you choose one tool over another doesn't mean you stop paying attention.\nNo matter what you choose, someone is going to complain. Don't look for the solution that makes everyone happy. There isn't one, short of getting rid of the developers who aren't happy.\nWhat languages give us the most ease of development and ease of modification?\nA skilled practitioner in just about any language will think that his chosen language is the easiest to develop, modify, and maintain. Unskilled practitioners tend to blame the language and the tools for their problems. Some languages have steeper learning curves, and some have bigger payouts. A person's tolerance with immediate gratification is a big factor here.\nThat being said, different languages have developed different cultures and different toolsets. Perl people tend to like vi or emacs, Ruby people tend to like TextMate, Java people tend to like Eclipse or IntelliJ. That's not always true, but the culture that evolves around the tools are often more important than the technical details of the tool. If your developers like a particular type of tool, they are probably going to like the language that has a culture built around that sort of tool.\nSome processes and tools take more time to get used to or require more education, but they can have larger advantages when used properly. Other tools get you started sooner but might not give you a path to bigger and greater things, such as cross-team development. The trick, however, is to not code to the tools so you aren't stuck in any particular toolset.\n"
] |
[
6,
4,
1
] |
[
"First, it's important to note that it is very hard to convince someone they're wrong.\n\nHe's advocating bash scripts and Perl,\n due to their universality and\n simplicity\n\nBash scripts are not simple. The bash programming model is really complex and unfriendly. if statements and expressions, in particular are horrifying.\nPerl may or may not be simple. \nBash is universal. Perl, however, is exactly as universal as Python. Python is pre-installed in almost all Linux distributions. So that argument is specious.\nThe \"universality\" of bash, Perl and python is exactly the same. The \"simplicity\", however, is not the same. You won't find it easy to to \"prove\" or \"convince\" anyone of this once they've already pronounced Perl as simple.\nThe Situation.\nIf the boss is advocating Perl, and Perl is not the answer, you will find it is very hard to convince someone they're wrong, making this effort nearly impossible.\nIf the boss was just throwing out ideas, then this is just difficult.\nQuick Hack.\nAn easy thing you can do is to attempt head-to-head comparisons of Python and Perl for some randomly-chosen jobs. You can then have a code walkthrough to demonstrate the relative opacity of Perl compared with the relative clarity of Python.\nEven this is fraught with terrible dangers.\n\nSome folks really think code golf is important. Python loses at code golf. Perl wins. There's nothing worse than \"Angry Co-worker with Perl Bias\" who will kill you with code-golf solutions that -- because they're smaller -- can baffle management into thinking that they're clearer or \"better\" on some arbitrary scale.\nSome folks really think explicit is \"wordy\" and bad. Python often loses because the assumptions are stated as actual parameter values. Some folks can (and do) complain at having to actually write things down. Read Stack Overflow for all of the Python questions where someone wants to make the try: block go away in a puff of assumptions.\n\nIf you choose random problems, you may -- accidentally -- chose something for which there's an existing piece of Perl or Python that can be downloaded and installed. A language can win just through an accident of the draw. Rather than a more in-depth comparison of language features.\nBest Bet\nThe best you can do is the following.\n\nIdentify what folks value. You can call these \"non-functional\" requirements. These are quality factors. What are the foundational, core principles? Open, Accessible, Transferrable Skills, Simplicity, Cleanliness, Honesty, Integrity, Thriftiness, Reverence, Patience, Hard Work, A Sense of Perspective, Reef the Main in Winds over 20 kn, etc. This is hard. No sympathy here.\nIdentify the technical use cases. These are \"functional\" requirements. Which bits of glue and integration there are? This is hard, also. Requirements erupt of out of the woodwork when you do this. Also, when you have a Perl bigot on the team, numerous non-functional requirements will pile into this area. Your manager -- who proposed Perl -- may be the Perl bigot, and the use cases may be difficult to collect in the presence of a Perl bigot.\nIdentify how (a) Perl + Bash vs. (b) Python vs. (c) Java fit this core values and the functional requirements. Note that using Python means you do not need to use Bash as much. My preference, BTW, is to pare Bash down to the rock-bottom minimum.\n\nThis is a big, difficult job. It's hard to short-cut. If you find that Perl is not the answer and the Perl bigot you need to convince is the manager who proposed Perl in the first place, you may find that convincing someone that they're wrong is very hard. \nEdit. I am aware that I am forbidden from using the string \"Perl Bigot\" to describe the manager's potential level of bias toward Perl. I, however, insist on using \"Perl Bigot\" to describe the manager who proposed Perl. The question provides no information on which to change this. The worst case is that (a) the manager is the Perl Bigot and (b) Perl is not the answer.\n"
] |
[
-1
] |
[
"groovy",
"perl",
"python"
] |
stackoverflow_0002527867_groovy_perl_python.txt
|
Q:
Python: UTF-8 problems (again...)
I have a database which is synchronized against an external web source twice a day. This web source contains a bunch of entries, which have names and some extra information about these names.
Some of these names are silly and I want to rename them when inserting them into my own database. To rename these silly names, I have a standard dictionary as such:
RENAME_TABLE = { "Wσird" : "Weird", ... }
As you can see, this is where UTF-8 comes into play. This is the function which performs renaming of all the problematic entries:
def rename_all_entries():
all_keys = RENAME_TABLE.keys()
entries = Entry.objects.filter(name__in=all_keys)
for entry in entries:
entry.name = RENAME_TABLE[entry.name]
entry.save()
So it tries to find the old name in RENAME_TABLE and renames the entry if found. However, I get a KeyError exception when using RENAME_TABLE[entry.name].
Now I'm lost, what do I do? I have...
# -*- coding: utf-8 -*-
...in the top of the Python file.
A:
The error you are receiving is due to the unicode string you want not being in the dictionary. Recall that in Python 2.x (I assume you are using that), the default string type is 8-bit, not unicode, so you are actually keying the dictionary with 8-bit strings. To declare a unicode string, use u"my unicode string". Then it should be accepted as a key.
|
Python: UTF-8 problems (again...)
|
I have a database which is synchronized against an external web source twice a day. This web source contains a bunch of entries, which have names and some extra information about these names.
Some of these names are silly and I want to rename them when inserting them into my own database. To rename these silly names, I have a standard dictionary as such:
RENAME_TABLE = { "Wσird" : "Weird", ... }
As you can see, this is where UTF-8 comes into play. This is the function which performs renaming of all the problematic entries:
def rename_all_entries():
all_keys = RENAME_TABLE.keys()
entries = Entry.objects.filter(name__in=all_keys)
for entry in entries:
entry.name = RENAME_TABLE[entry.name]
entry.save()
So it tries to find the old name in RENAME_TABLE and renames the entry if found. However, I get a KeyError exception when using RENAME_TABLE[entry.name].
Now I'm lost, what do I do? I have...
# -*- coding: utf-8 -*-
...in the top of the Python file.
|
[
"The error you are receiving is due to the unicode string you want not being in the dictionary. Recall that in Python 2.x (I assume you are using that), the default string type is 8-bit, not unicode, so you are actually keying the dictionary with 8-bit strings. To declare a unicode string, use u\"my unicode string\". Then it should be accepted as a key. \n"
] |
[
4
] |
[] |
[] |
[
"django",
"encoding",
"python",
"utf_8"
] |
stackoverflow_0002534596_django_encoding_python_utf_8.txt
|
Q:
Python inter-computer communication
This whole topic is way out of my depth, so forgive my imprecise question, but I have two computers both connected to one LAN.
What I want is to be able to communicate one string between the two, by running a python script on the first (the host) where the string will originate, and a second on the client computer to retrieve the string.
What is the most efficient way for an inexperienced programmer like me to achieve this?
A:
First, lets get the nomenclature straight. Usually the part that initiate the communication is the client, the parts that is waiting for a connection is a server, which then will receive the data from the client and generate a response. From your question, the "host" is the client and the "client" seems to be the server.
Then you have to decide how to transfer the data. You can use straight sockets, in which case you can use SocketServer, or you can rely on an existing protocol, like HTTP or XML-RPC, in which case you will find ready to use library packages with plenty of examples (e.g. xmlrpclib and SimpleXMLRPCServer)
A:
There are about a million ways.
If I were doing it, I'd use the SocketServer library, because it's not too insane, fairly well documented, and most importantly, I've used it before.
There are a couple of examples here: http://docs.python.org/library/socketserver.html#examples
|
Python inter-computer communication
|
This whole topic is way out of my depth, so forgive my imprecise question, but I have two computers both connected to one LAN.
What I want is to be able to communicate one string between the two, by running a python script on the first (the host) where the string will originate, and a second on the client computer to retrieve the string.
What is the most efficient way for an inexperienced programmer like me to achieve this?
|
[
"First, lets get the nomenclature straight. Usually the part that initiate the communication is the client, the parts that is waiting for a connection is a server, which then will receive the data from the client and generate a response. From your question, the \"host\" is the client and the \"client\" seems to be the server.\nThen you have to decide how to transfer the data. You can use straight sockets, in which case you can use SocketServer, or you can rely on an existing protocol, like HTTP or XML-RPC, in which case you will find ready to use library packages with plenty of examples (e.g. xmlrpclib and SimpleXMLRPCServer)\n",
"There are about a million ways.\nIf I were doing it, I'd use the SocketServer library, because it's not too insane, fairly well documented, and most importantly, I've used it before.\nThere are a couple of examples here: http://docs.python.org/library/socketserver.html#examples\n"
] |
[
4,
3
] |
[
"File share and polling filesystem every minute. No joke. Of course, it depends on what are requirements for your applications and what lag is acceptable but in practice using file shares is quite common.\n"
] |
[
-2
] |
[
"python"
] |
stackoverflow_0002534527_python.txt
|
Q:
do the Python libraries have a natural dependence on the global namespace?
I first ran into this when trying to determine the relative performance of two generators:
t = timeit.repeat('g.get()', setup='g = my_generator()')
So I dug into the timeit module and found that the setup and statement are evaluated with their own private, initially empty namespaces so naturally the binding of g never becomes accessible to the g.get() statement. The obvious solution is to wrap them into a class, thus adding to the global namespace.
I bumped into this again when attempting, in another project, to use the multiprocessing module to divide a task among workers. I even bundled everything nicely into a class but unfortunately the call
pool.apply_async(runmc, arg)
fails with a PicklingError because buried inside the work object that runmc instantiates is (effectively) an assignment:
self.predicate = lambda x, y: x > y
so the whole object can't be (understandably) pickled and whereas:
def foo(x, y):
return x > y
pickle.dumps(foo)
is fine, the sequence
bar = lambda x, y: x > y
yields True from callable(bar) and from type(bar), but it Can't pickle <function <lambda> at 0xb759b764>: it's not found as __main__.<lambda>.
I've given only code fragments because I can easily fix these cases by merely pulling them out into module or object level defs. The bug here appears to be in my understanding of the semantics of namespace use in general. If the nature of the language requires that I create more def statements I'll happily do so; I fear that I'm missing an essential concept though. Why is there such a strong reliance on the global namespace? Or, what am I failing to understand?
Namespaces are one honking great idea -- let's do more of those!
A:
The pickle protocol(s) would have a serious problem picking classes and functions in the most general case; by pickling them "by name" instead, it makes the difficulty go away, but nds up requiring that they be bound to (and recoverable by) names that are top-level in a module (which, since a module is its own namespace, doesn't conflict with "namespaces are one honking great idea", after all;-).
As for your timeit problem, I don't undestand what you mean wrt "the global namespace" - for example:
>>> timeit.repeat('g.get(23)', 'g = {}')
[0.29134988784790039, 0.27160286903381348, 0.27237796783447266]
the namespace where g is bound leaves the binding fully accessible by the statement being repeated. If what you're binding to g is a generator, maybe your problem is that generators don't have .get() methods and perhaps you meant .next()?
|
do the Python libraries have a natural dependence on the global namespace?
|
I first ran into this when trying to determine the relative performance of two generators:
t = timeit.repeat('g.get()', setup='g = my_generator()')
So I dug into the timeit module and found that the setup and statement are evaluated with their own private, initially empty namespaces so naturally the binding of g never becomes accessible to the g.get() statement. The obvious solution is to wrap them into a class, thus adding to the global namespace.
I bumped into this again when attempting, in another project, to use the multiprocessing module to divide a task among workers. I even bundled everything nicely into a class but unfortunately the call
pool.apply_async(runmc, arg)
fails with a PicklingError because buried inside the work object that runmc instantiates is (effectively) an assignment:
self.predicate = lambda x, y: x > y
so the whole object can't be (understandably) pickled and whereas:
def foo(x, y):
return x > y
pickle.dumps(foo)
is fine, the sequence
bar = lambda x, y: x > y
yields True from callable(bar) and from type(bar), but it Can't pickle <function <lambda> at 0xb759b764>: it's not found as __main__.<lambda>.
I've given only code fragments because I can easily fix these cases by merely pulling them out into module or object level defs. The bug here appears to be in my understanding of the semantics of namespace use in general. If the nature of the language requires that I create more def statements I'll happily do so; I fear that I'm missing an essential concept though. Why is there such a strong reliance on the global namespace? Or, what am I failing to understand?
Namespaces are one honking great idea -- let's do more of those!
|
[
"The pickle protocol(s) would have a serious problem picking classes and functions in the most general case; by pickling them \"by name\" instead, it makes the difficulty go away, but nds up requiring that they be bound to (and recoverable by) names that are top-level in a module (which, since a module is its own namespace, doesn't conflict with \"namespaces are one honking great idea\", after all;-).\nAs for your timeit problem, I don't undestand what you mean wrt \"the global namespace\" - for example:\n>>> timeit.repeat('g.get(23)', 'g = {}')\n[0.29134988784790039, 0.27160286903381348, 0.27237796783447266]\n\nthe namespace where g is bound leaves the binding fully accessible by the statement being repeated. If what you're binding to g is a generator, maybe your problem is that generators don't have .get() methods and perhaps you meant .next()?\n"
] |
[
3
] |
[] |
[] |
[
"namespaces",
"python"
] |
stackoverflow_0002534847_namespaces_python.txt
|
Q:
Deleting dirs after finishing a command prompt
I have a python script that ends with running a program (iexpress.exe) in a dos prompt.
The program that runs in dos prompt, uses a dir called workdir.
After the program has finished in the dos prompt I would like python to delete the dir.
I have just made a simple solution of putting a delay of 30sec:
time.sleep(30)
removeall(workdir)
os.rmdir(workdir)
But how should I do it, if python should delete the dir right after the process has finished?
A:
Make the python program call the exe and not fall off the end
ie call the exe using subprocess.Popen
The when the exe finishes you are still in python
|
Deleting dirs after finishing a command prompt
|
I have a python script that ends with running a program (iexpress.exe) in a dos prompt.
The program that runs in dos prompt, uses a dir called workdir.
After the program has finished in the dos prompt I would like python to delete the dir.
I have just made a simple solution of putting a delay of 30sec:
time.sleep(30)
removeall(workdir)
os.rmdir(workdir)
But how should I do it, if python should delete the dir right after the process has finished?
|
[
"Make the python program call the exe and not fall off the end\nie call the exe using subprocess.Popen\nThe when the exe finishes you are still in python\n"
] |
[
0
] |
[] |
[] |
[
"cmd",
"python",
"python_3.x"
] |
stackoverflow_0002534917_cmd_python_python_3.x.txt
|
Q:
Rest Web Service with App Engine and Webapp
I want to build a REST web service on app engine. Currently i have this:
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
class UsersHandler(webapp.RequestHandler):
def get(self, name):
self.response.out.write('Hello '+ name+'!')
def main():
util.run_wsgi_app(application)
#Map url like /rest/users/johnsmith
application = webapp.WSGIApplication([(r'/rest/users/(.*)',UsersHandler)]
debug=True)
if __name__ == '__main__':
main()
And i would like to retreive for example all my users when the path /rest/users is accessed. I Imagine I can do this by building another handler, but I want to know if is possible to do it inside of this handler.
A:
Sure, you can -- change your handler's get method to
def get(self, name=None):
if name is None:
"""deal with the /rest/users case"""
else:
# deal with the /rest/users/(.*) case
self.response.out.write('Hello '+ name+'!')
and your application to
application = webapp.WSGIApplication([(r'/rest/users/(.*)', UsersHandler),
(r'/rest/users', UsersHandler)]
debug=True)
In other words, map your handler to all the URL patterns you want it to handle, and make sure the handler's get method can distinguish among them easily (typically via its arguments).
|
Rest Web Service with App Engine and Webapp
|
I want to build a REST web service on app engine. Currently i have this:
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
class UsersHandler(webapp.RequestHandler):
def get(self, name):
self.response.out.write('Hello '+ name+'!')
def main():
util.run_wsgi_app(application)
#Map url like /rest/users/johnsmith
application = webapp.WSGIApplication([(r'/rest/users/(.*)',UsersHandler)]
debug=True)
if __name__ == '__main__':
main()
And i would like to retreive for example all my users when the path /rest/users is accessed. I Imagine I can do this by building another handler, but I want to know if is possible to do it inside of this handler.
|
[
"Sure, you can -- change your handler's get method to\ndef get(self, name=None):\n if name is None:\n \"\"\"deal with the /rest/users case\"\"\"\n else:\n # deal with the /rest/users/(.*) case\n self.response.out.write('Hello '+ name+'!') \n\nand your application to\napplication = webapp.WSGIApplication([(r'/rest/users/(.*)', UsersHandler),\n (r'/rest/users', UsersHandler)] \n debug=True)\n\nIn other words, map your handler to all the URL patterns you want it to handle, and make sure the handler's get method can distinguish among them easily (typically via its arguments).\n"
] |
[
14
] |
[] |
[] |
[
"google_app_engine",
"python",
"rest",
"web_applications"
] |
stackoverflow_0002534947_google_app_engine_python_rest_web_applications.txt
|
Q:
Way to call super(MyClass, self).__init__() without MyClass?
I find this syntax astoundingly annoying. Every time I rename my class, I have to change this call for no apparent reason. Isn't there some __class__ magic variable or something I can use at least? Interested in answers for Python 2.5, but it doesn't hurt to know if later versions fixed this.
A:
As far as I know, this isn't possible in 2.5. However, in 3.0, this was changed so that you can simply call super().__init__().
A:
This is fixed in Python 3. http://docs.python.org/py3k/library/functions.html#super
http://www.python.org/dev/peps/pep-3135/
A:
If your class only inherits from one class it is safe to do just this:
class B(A):
def __init__(self):
A.__init__(self)
But I could be mistaken.
A:
In Python 3.0, the super() can be called without arguments to do the same thing.
|
Way to call super(MyClass, self).__init__() without MyClass?
|
I find this syntax astoundingly annoying. Every time I rename my class, I have to change this call for no apparent reason. Isn't there some __class__ magic variable or something I can use at least? Interested in answers for Python 2.5, but it doesn't hurt to know if later versions fixed this.
|
[
"As far as I know, this isn't possible in 2.5. However, in 3.0, this was changed so that you can simply call super().__init__().\n",
"This is fixed in Python 3. http://docs.python.org/py3k/library/functions.html#super\nhttp://www.python.org/dev/peps/pep-3135/\n",
"If your class only inherits from one class it is safe to do just this:\nclass B(A):\n def __init__(self):\n A.__init__(self)\n\nBut I could be mistaken.\n",
"In Python 3.0, the super() can be called without arguments to do the same thing.\n"
] |
[
4,
4,
3,
2
] |
[
"EDIT: As pointed out by Alex, this causes infinite recursion when there is more than a single level of inheritance. Do not use this approach.\nYes, \"new\" style classes have a __class__ attribute available which can be used, eg.\nclass B(object):\n def __init__(self):\n print \"B.__init__():\"\n\nclass D(B):\n def __init__(self):\n print \"D.__init__():\"\n super(self.__class__, self).__init__()\n\n>>> d = D()\nD.__init__():\nB.__init__():\n\n>>> dir(d)\n['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__']\n>>> d.__class__\n<class '__main__.D'>\n\nHowever this fails if a class were to inherit from D:\n>>> class E(D):\n... pass\n...\n>>> E()\nD.__init__():\nD.__init__():\n[...]\nD.__init__():\nD.__init__():\nTraceback (most recent call last):\n File \"<stdin>\", line 4, in __init__\n File \"<stdin>\", line 4, in __init__\n [...]\n File \"<stdin>\", line 4, in __init__\n File \"<stdin>\", line 4, in __init__\nRuntimeError: maximum recursion depth exceeded while calling a Python object\n\n"
] |
[
-1
] |
[
"python",
"syntax"
] |
stackoverflow_0002535037_python_syntax.txt
|
Q:
How to load google map geo-location not using kml
How to load google map geo-location not using kml. Like this site: http://www.housingmaps.com/
A:
This example from Google is what you're looking for.
|
How to load google map geo-location not using kml
|
How to load google map geo-location not using kml. Like this site: http://www.housingmaps.com/
|
[
"This example from Google is what you're looking for.\n"
] |
[
1
] |
[] |
[] |
[
"django",
"google_maps",
"javascript",
"kml",
"python"
] |
stackoverflow_0002535379_django_google_maps_javascript_kml_python.txt
|
Q:
motion computation from video using pyglet in python
I am writing a simple motion detection program but i want it to be cross platform so im using python and the pyglet library since it provides a simple way to load videos in different formats (specially wmv and mpeg). So far i have the code given below which loads the movie and plays it in a window. Now i need to:
1) grab frame at time t and t-1
2) do a subtraction to see which pixels are active for motion detection.
any ideas on how to grab frames and to skip over frames and is it possible to put the pixel values into a matrix in numpy or something directly from pyglet? or should look into using something other than pyglet?
thanks
kuaywai
import pyglet
import sys
window = pyglet.window.Window(resizable=True)
window.set_minimum_size(320,200)
window.set_caption('Motion detect 1.0')
video_intro = pyglet.resource.media('movie1.wmv')
player = pyglet.media.Player()
player.queue(video_intro)
print 'calculating movie size...'
if not player.source or not player.source.video_format:
sys.exit
myWidth = player.source.video_format.width
myHeight = player.source.video_format.height
if player.source.video_format.sample_aspect > 1:
myWidth *= player.source.video_format.sample_aspect
elif player.source.video_format.sample_aspect < 1:
myHeight /= player.source.video_format.sample_aspect
print 'its size is %d,%d' % (myWidth,myHeight)
player.play()
@window.event
def on_draw():
window.clear()
(w,h) = window.get_size()
player.get_texture().blit(0, h-myHeight,
width=myWidth,
height=myHeight)
pyglet.app.run()
A:
To me it seems like you have to skip the play function and manually step through the video/animation, maybe using source.get_animation().frames which is a list of frames where each frame is a simple image. I'm guessing this isn't really going to be pracitical with large videos but that is generally not something you should be handling in Python anyway.
|
motion computation from video using pyglet in python
|
I am writing a simple motion detection program but i want it to be cross platform so im using python and the pyglet library since it provides a simple way to load videos in different formats (specially wmv and mpeg). So far i have the code given below which loads the movie and plays it in a window. Now i need to:
1) grab frame at time t and t-1
2) do a subtraction to see which pixels are active for motion detection.
any ideas on how to grab frames and to skip over frames and is it possible to put the pixel values into a matrix in numpy or something directly from pyglet? or should look into using something other than pyglet?
thanks
kuaywai
import pyglet
import sys
window = pyglet.window.Window(resizable=True)
window.set_minimum_size(320,200)
window.set_caption('Motion detect 1.0')
video_intro = pyglet.resource.media('movie1.wmv')
player = pyglet.media.Player()
player.queue(video_intro)
print 'calculating movie size...'
if not player.source or not player.source.video_format:
sys.exit
myWidth = player.source.video_format.width
myHeight = player.source.video_format.height
if player.source.video_format.sample_aspect > 1:
myWidth *= player.source.video_format.sample_aspect
elif player.source.video_format.sample_aspect < 1:
myHeight /= player.source.video_format.sample_aspect
print 'its size is %d,%d' % (myWidth,myHeight)
player.play()
@window.event
def on_draw():
window.clear()
(w,h) = window.get_size()
player.get_texture().blit(0, h-myHeight,
width=myWidth,
height=myHeight)
pyglet.app.run()
|
[
"To me it seems like you have to skip the play function and manually step through the video/animation, maybe using source.get_animation().frames which is a list of frames where each frame is a simple image. I'm guessing this isn't really going to be pracitical with large videos but that is generally not something you should be handling in Python anyway.\n"
] |
[
0
] |
[] |
[] |
[
"motion_detection",
"pyglet",
"python",
"video_processing"
] |
stackoverflow_0002532261_motion_detection_pyglet_python_video_processing.txt
|
Q:
Potential annoyances of tab delimited Python source?
Edit: This question has already been asked and answered, and I apparently am not good at using the search wizard. See Why does Python pep-8 strongly recommend spaces over tabs for indentation? and the link in the comments. Thanks for replying to those who did so.
I want to start a new project, and I want this to be my first Python project. I was looking through the style guide, http://www.python.org/dev/peps/pep-0008/, which "strongly recommends" using a 4-spaces indentation style for new projects. But I just hate this idea! In my opinion, tabs are better for this purpose.
What annoyances could crop up one day if another developer wanted to work on my tab-delimited files?
A:
Most Python programmers will have their editors configured to automatically use four spaces for all .py files… Which could, at least initially, cause some minor headaches if they try to edit your source.
But apart from that (given that PEP 666 was rejected), it shouldn't cause any major trouble.
Of course, if you get serious about Python, it would be a good idea to follow PEP 8, as most Python code conforms to it… But, given that this is your first Python project, you've got bigger things to worry about than tabs VS spaces.
A:
If all the world used tab-indented Python source, then everyone would be happy.
If all the world used 4-space indented Python source, then everyone would be happy.
Unhappiness arises when one tries to comingle tab-indented code with 4-space indented code.
The majority of Python code seems to be of the 4-space variety. If you ever wish to rip out some of this code and use it in your project, you will be saved from the minor annoyance of having to run it through a space-to-tab converter (like unexpand) if you stick with the PEP recommendation and use 4-spaces.
You'll also cause less of a hassle for other developers (who follow the 4-space convention) who may wish to contribute to your project.
PS. Finding a good text editor is especially important when writing code in Python. It should allow you to press [TAB] and insert 4 spaces instead of 1 tab.
It should also allow you to be able to shift blocks of code by 1 level of indention to the left or right easily. Once you find the right editor (e.g. emacs or vim), working with the 4-space convention is a breeze.
|
Potential annoyances of tab delimited Python source?
|
Edit: This question has already been asked and answered, and I apparently am not good at using the search wizard. See Why does Python pep-8 strongly recommend spaces over tabs for indentation? and the link in the comments. Thanks for replying to those who did so.
I want to start a new project, and I want this to be my first Python project. I was looking through the style guide, http://www.python.org/dev/peps/pep-0008/, which "strongly recommends" using a 4-spaces indentation style for new projects. But I just hate this idea! In my opinion, tabs are better for this purpose.
What annoyances could crop up one day if another developer wanted to work on my tab-delimited files?
|
[
"Most Python programmers will have their editors configured to automatically use four spaces for all .py files… Which could, at least initially, cause some minor headaches if they try to edit your source.\nBut apart from that (given that PEP 666 was rejected), it shouldn't cause any major trouble.\nOf course, if you get serious about Python, it would be a good idea to follow PEP 8, as most Python code conforms to it… But, given that this is your first Python project, you've got bigger things to worry about than tabs VS spaces.\n",
"If all the world used tab-indented Python source, then everyone would be happy.\nIf all the world used 4-space indented Python source, then everyone would be happy.\nUnhappiness arises when one tries to comingle tab-indented code with 4-space indented code.\nThe majority of Python code seems to be of the 4-space variety. If you ever wish to rip out some of this code and use it in your project, you will be saved from the minor annoyance of having to run it through a space-to-tab converter (like unexpand) if you stick with the PEP recommendation and use 4-spaces. \nYou'll also cause less of a hassle for other developers (who follow the 4-space convention) who may wish to contribute to your project.\nPS. Finding a good text editor is especially important when writing code in Python. It should allow you to press [TAB] and insert 4 spaces instead of 1 tab.\nIt should also allow you to be able to shift blocks of code by 1 level of indention to the left or right easily. Once you find the right editor (e.g. emacs or vim), working with the 4-space convention is a breeze.\n"
] |
[
1,
1
] |
[] |
[] |
[
"ide",
"python",
"tabs"
] |
stackoverflow_0002535397_ide_python_tabs.txt
|
Q:
What is a really simple explanation of unit testing?
I've never done any unit testing before, and would like to learn what it is and how it can be useful in my Python code.
I've read through a few Python unit testing tutorials online but they're all so complicated and assume an extended programming background. I'm using Python with Pylons to create a simple web app.
Any simple examples would be greatly appreciated.
Thanks!
A:
Consider this.
Here's a class we've written.
class Something( object ):
def __init__( self, a, b ):
self.a= a
self.b= b
def sum( self ):
return self.a+self.b+self.a
That's a test for that class.
import unittest
class TestSomething( unittest.TestCase ):
def setUp( self ):
self.s = Something( 1, 2 )
def test_should_sum( self ):
self.assertEquals( 3, self.s.sum() )
if __name__ == "__main__":
unittest.main()
Does the class -- as a stand-alone unit -- pass the test?
If not, what's the bug?
We've taken the class -- as a stand-alone unit -- and tested it. That's unit testing.
|
What is a really simple explanation of unit testing?
|
I've never done any unit testing before, and would like to learn what it is and how it can be useful in my Python code.
I've read through a few Python unit testing tutorials online but they're all so complicated and assume an extended programming background. I'm using Python with Pylons to create a simple web app.
Any simple examples would be greatly appreciated.
Thanks!
|
[
"Consider this.\nHere's a class we've written.\nclass Something( object ):\n def __init__( self, a, b ):\n self.a= a\n self.b= b\n def sum( self ):\n return self.a+self.b+self.a\n\nThat's a test for that class.\nimport unittest\nclass TestSomething( unittest.TestCase ):\n def setUp( self ):\n self.s = Something( 1, 2 )\n def test_should_sum( self ):\n self.assertEquals( 3, self.s.sum() )\n\nif __name__ == \"__main__\":\n unittest.main()\n\nDoes the class -- as a stand-alone unit -- pass the test?\nIf not, what's the bug?\nWe've taken the class -- as a stand-alone unit -- and tested it. That's unit testing. \n"
] |
[
5
] |
[] |
[] |
[
"pylons",
"python",
"unit_testing"
] |
stackoverflow_0002535431_pylons_python_unit_testing.txt
|
Q:
Catching a python app before it exits
I have a python app which is supposed to be very long-lived, but sometimes the process just disappears and I don't know why. Nothing gets logged when this happens, so I'm at a bit of a loss.
Is there some way in code I can hook in to an exit event, or some other way to get some of my code to run just before the process quits? I'd like to log the state of memory structures to better understand what's going on.
A:
atexit is pronounced "at exit". The first times I read that function name, I read it as "a texit", which doesn't make nearly as much sense.
A:
You might try running your application directly from a console (cmd on windows, sh/bash/etc on unix), so you can see any stack trace, etc printed to the console when the process dies.
A:
I'm not sure if you are able to modify the source code, but if so you might want to try this:
def debugexcept(type, value, tb):
if hasattr(sys, 'ps1') or not (sys.stderr.isatty() and sys.stdin.isatty()) or type == SyntaxError:
sys.__excepthook__(type, value, tb)
else:
import traceback, pdb
traceback.print_exception(type, value, tb)
print
pdb.pm()
sys.excepthook = debugexcept
If you launch your python program from a command line you should be dumped into the python debugger when it dies, assuming something 'bad' has happened to cause an exception. I'm guessing maybe stderr/stdout have been captured and you're not seeing some exception?
ie search for something like:
sys.stdout = open('stdout.log', 'w')
sys.stderr = open('stderr.log', 'w')
If the process is dieing without an exception at all then that might be harder to find. One (very hard way) on windows would be to use something like windbg to attach to the process and set a breakpoint in the CRT at some relevant spot.
Good luck!
|
Catching a python app before it exits
|
I have a python app which is supposed to be very long-lived, but sometimes the process just disappears and I don't know why. Nothing gets logged when this happens, so I'm at a bit of a loss.
Is there some way in code I can hook in to an exit event, or some other way to get some of my code to run just before the process quits? I'd like to log the state of memory structures to better understand what's going on.
|
[
"atexit is pronounced \"at exit\". The first times I read that function name, I read it as \"a texit\", which doesn't make nearly as much sense.\n",
"You might try running your application directly from a console (cmd on windows, sh/bash/etc on unix), so you can see any stack trace, etc printed to the console when the process dies.\n",
"I'm not sure if you are able to modify the source code, but if so you might want to try this:\ndef debugexcept(type, value, tb):\n if hasattr(sys, 'ps1') or not (sys.stderr.isatty() and sys.stdin.isatty()) or type == SyntaxError:\n sys.__excepthook__(type, value, tb)\n else:\n import traceback, pdb\n traceback.print_exception(type, value, tb)\n print\n pdb.pm()\n\n\nsys.excepthook = debugexcept\n\nIf you launch your python program from a command line you should be dumped into the python debugger when it dies, assuming something 'bad' has happened to cause an exception. I'm guessing maybe stderr/stdout have been captured and you're not seeing some exception?\nie search for something like:\nsys.stdout = open('stdout.log', 'w')\nsys.stderr = open('stderr.log', 'w')\n\nIf the process is dieing without an exception at all then that might be harder to find. One (very hard way) on windows would be to use something like windbg to attach to the process and set a breakpoint in the CRT at some relevant spot.\nGood luck!\n"
] |
[
8,
3,
3
] |
[] |
[] |
[
"crash",
"python"
] |
stackoverflow_0002535403_crash_python.txt
|
Q:
Looking for a smarter way to convert a Python list to a GList?
I'm really new to C -> Python interaction and am currently writing a small app in C which will read a file (using Python to parse it) and then using the parsed information to execute small Python snippets. At the moment I'm feeling very much like I'm reinventing wheels, for example this function:
typedef gpointer (list_func)(PyObject *obj);
GList *pylist_to_glist(list_func func, PyObject *pylist)
{
GList *result = NULL;
if (func == NULL)
{
fprintf(stderr, "No function definied for coverting PyObject.\n");
}
else if (PyList_Check(pylist))
{
PyObject *pIter = PyObject_GetIter(pylist);
PyObject *pItem;
while ((pItem = PyIter_Next(pIter)))
{
gpointer obj = func(pItem);
if (obj != NULL) result = g_list_append(result, obj);
else fprintf(stderr, "Could not convert PyObject to C object.\n");
Py_DECREF(pItem);
}
Py_DECREF(pIter);
}
return result;
}
I would really like to do this in a easier/smarter way less prone to memory leaks and errors.
All comments and suggestions are appreciated.
A:
I recommend PySequence_Fast and friends:
else
{
PyObject *pSeqfast = PySequence_Fast(pylist, "must be a sequence");
Py_ssize_t n = PySequence_Fast_GET_SIZE(pSeqFast);
for(Py_ssize_t i = 0; i < n ; ++i)
{
gpointer obj = func(PySequence_Fast_GET_ITEM(pSeqfast, i));
if (obj != NULL) result = g_list_append(result, obj);
else fprintf(stderr, "Could not convert PyObject to C object.\n");
}
Py_DECREF(pSeqfast);
}
|
Looking for a smarter way to convert a Python list to a GList?
|
I'm really new to C -> Python interaction and am currently writing a small app in C which will read a file (using Python to parse it) and then using the parsed information to execute small Python snippets. At the moment I'm feeling very much like I'm reinventing wheels, for example this function:
typedef gpointer (list_func)(PyObject *obj);
GList *pylist_to_glist(list_func func, PyObject *pylist)
{
GList *result = NULL;
if (func == NULL)
{
fprintf(stderr, "No function definied for coverting PyObject.\n");
}
else if (PyList_Check(pylist))
{
PyObject *pIter = PyObject_GetIter(pylist);
PyObject *pItem;
while ((pItem = PyIter_Next(pIter)))
{
gpointer obj = func(pItem);
if (obj != NULL) result = g_list_append(result, obj);
else fprintf(stderr, "Could not convert PyObject to C object.\n");
Py_DECREF(pItem);
}
Py_DECREF(pIter);
}
return result;
}
I would really like to do this in a easier/smarter way less prone to memory leaks and errors.
All comments and suggestions are appreciated.
|
[
"I recommend PySequence_Fast and friends:\nelse\n{\n PyObject *pSeqfast = PySequence_Fast(pylist, \"must be a sequence\");\n Py_ssize_t n = PySequence_Fast_GET_SIZE(pSeqFast);\n\n for(Py_ssize_t i = 0; i < n ; ++i)\n {\n gpointer obj = func(PySequence_Fast_GET_ITEM(pSeqfast, i));\n if (obj != NULL) result = g_list_append(result, obj);\n else fprintf(stderr, \"Could not convert PyObject to C object.\\n\");\n }\n Py_DECREF(pSeqfast);\n}\n\n"
] |
[
1
] |
[] |
[] |
[
"c",
"glib",
"python",
"python_embedding"
] |
stackoverflow_0002535448_c_glib_python_python_embedding.txt
|
Q:
How to change the value of None in Python?
I'm currently reading chapter 5.8 of Dive Into Python and Mark Pilgrim says:
There are no constants in Python. Everything can be changed if you try hard enough. This fits with one of the core principles of Python: bad behavior should be discouraged but not banned. If you really want to change the value of None, you can do it, but don't come running to me when your code is impossible to debug.
I tried this in the interpreter
None = "bad"
I get a
SyntaxError: assignment to None
Just out of curiosity how do you change None?
EDIT:
Interestingly:
>>> import __builtin__
>>> __builtin__.None is None
True
>>> None
>>> None = "bad"
File "<stdin>", line 1
SyntaxError: assignment to None
>>> __builtin__.None = "bad"
File "<stdin>", line 1
SyntaxError: assignment to None
>>> setattr(__builtin__, "None", "bad")
>>> __builtin__.None
'bad'
>>> None
>>> __builtin__.None is None
False
>>> __builtin__.None = None
File "<stdin>", line 1
SyntaxError: assignment to None
Also
>>> class Abc:
... def __init__(self):
... self.None = None
...
File "<stdin>", line 3
SyntaxError: assignment to None
>>> class Abc:
... def __init__(self):
... setattr(self,'None',None)
...
>>>
So I guess 'None = ' just doesn't work in any context
A:
You first have to install an old version of Python (I think it needs to be 2.2 or older). In 2.4 and newer for certain (and I believe in 2.3) the assignment in question is a syntax error. Mark's excellent book is, alas, a bit dated by now.
|
How to change the value of None in Python?
|
I'm currently reading chapter 5.8 of Dive Into Python and Mark Pilgrim says:
There are no constants in Python. Everything can be changed if you try hard enough. This fits with one of the core principles of Python: bad behavior should be discouraged but not banned. If you really want to change the value of None, you can do it, but don't come running to me when your code is impossible to debug.
I tried this in the interpreter
None = "bad"
I get a
SyntaxError: assignment to None
Just out of curiosity how do you change None?
EDIT:
Interestingly:
>>> import __builtin__
>>> __builtin__.None is None
True
>>> None
>>> None = "bad"
File "<stdin>", line 1
SyntaxError: assignment to None
>>> __builtin__.None = "bad"
File "<stdin>", line 1
SyntaxError: assignment to None
>>> setattr(__builtin__, "None", "bad")
>>> __builtin__.None
'bad'
>>> None
>>> __builtin__.None is None
False
>>> __builtin__.None = None
File "<stdin>", line 1
SyntaxError: assignment to None
Also
>>> class Abc:
... def __init__(self):
... self.None = None
...
File "<stdin>", line 3
SyntaxError: assignment to None
>>> class Abc:
... def __init__(self):
... setattr(self,'None',None)
...
>>>
So I guess 'None = ' just doesn't work in any context
|
[
"You first have to install an old version of Python (I think it needs to be 2.2 or older). In 2.4 and newer for certain (and I believe in 2.3) the assignment in question is a syntax error. Mark's excellent book is, alas, a bit dated by now.\n"
] |
[
13
] |
[] |
[] |
[
"python",
"syntax"
] |
stackoverflow_0002535477_python_syntax.txt
|
Q:
Using numpy.apply
What's wrong with this snippet of code?
import numpy as np
from scipy import stats
d = np.arange(10.0)
cutoffs = [stats.scoreatpercentile(d, pct) for pct in range(0, 100, 20)]
f = lambda x: np.sum(x > cutoffs)
fv = np.vectorize(f)
# why don't these two lines output the same values?
[f(x) for x in d] # => [0, 1, 2, 2, 3, 3, 4, 4, 5, 5]
fv(d) # => array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Any ideas?
A:
cutoffs is a list. The numbers you extract from d are all turned into float and applied using numpy.vectorize. (It's actually rather odd—it looks like first it tries numpy floats that work like you want then it tries normal Python floats.) By a rather odd, stupid behavior in Python, floats are always less than lists, so instead of getting things like
>>> # Here is a vectorized array operation, like you get from numpy. It won't
>>> # happen if you just use a float and a list.
>>> 2.0 > [0.0, 1.8, 3.6, 5.4, 7.2]
[True, True, False, False, False] # not real
you get
>>> # This is an actual copy-paste from a Python interpreter
>>> 2.0 > [0.0, 1.8, 3.6, 5.4, 7.2]
False
To solve the problem, you can make cutoffs a numpy array instead of a list. (You could probably also move the comparison into numpy operations entirely instead of faking it with numpy.vectorize, but I do not know offhand.)
|
Using numpy.apply
|
What's wrong with this snippet of code?
import numpy as np
from scipy import stats
d = np.arange(10.0)
cutoffs = [stats.scoreatpercentile(d, pct) for pct in range(0, 100, 20)]
f = lambda x: np.sum(x > cutoffs)
fv = np.vectorize(f)
# why don't these two lines output the same values?
[f(x) for x in d] # => [0, 1, 2, 2, 3, 3, 4, 4, 5, 5]
fv(d) # => array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
Any ideas?
|
[
"cutoffs is a list. The numbers you extract from d are all turned into float and applied using numpy.vectorize. (It's actually rather odd—it looks like first it tries numpy floats that work like you want then it tries normal Python floats.) By a rather odd, stupid behavior in Python, floats are always less than lists, so instead of getting things like \n>>> # Here is a vectorized array operation, like you get from numpy. It won't\n>>> # happen if you just use a float and a list.\n>>> 2.0 > [0.0, 1.8, 3.6, 5.4, 7.2]\n[True, True, False, False, False] # not real\n\nyou get\n>>> # This is an actual copy-paste from a Python interpreter\n>>> 2.0 > [0.0, 1.8, 3.6, 5.4, 7.2]\nFalse\n\nTo solve the problem, you can make cutoffs a numpy array instead of a list. (You could probably also move the comparison into numpy operations entirely instead of faking it with numpy.vectorize, but I do not know offhand.)\n"
] |
[
1
] |
[] |
[] |
[
"numpy",
"python",
"scipy"
] |
stackoverflow_0002535556_numpy_python_scipy.txt
|
Q:
llvm-py questions
1) Is it possible to use llvm-py on Windows without Visual Studio 2008? Maybe I can compile files on another computer and use on my?
2) Is llvm-py mature enough in your opinion? If not, what are the problems?
A:
As far as I know, llvm-py is unmaintained. The project would require some kind of compiler, although you should be able to use the free VS express edition I would imagine.
On the other hand, the LLVM C bindings are maintained, so it is always possible to use the Python ctypes module to wrap the LLVM C API, without having to compile anything (assuming you already have a copy of LLVM compiled for your platform).
|
llvm-py questions
|
1) Is it possible to use llvm-py on Windows without Visual Studio 2008? Maybe I can compile files on another computer and use on my?
2) Is llvm-py mature enough in your opinion? If not, what are the problems?
|
[
"As far as I know, llvm-py is unmaintained. The project would require some kind of compiler, although you should be able to use the free VS express edition I would imagine.\nOn the other hand, the LLVM C bindings are maintained, so it is always possible to use the Python ctypes module to wrap the LLVM C API, without having to compile anything (assuming you already have a copy of LLVM compiled for your platform).\n"
] |
[
3
] |
[] |
[] |
[
"llvm",
"python"
] |
stackoverflow_0002355019_llvm_python.txt
|
Q:
XML RPC client for C# over secured socket (https)
I have a secured (https) XML-RPC server written in python, and I have tested it with a python based client. but I need a C# based client for it, I have given a try to xml-rpc.net
but it is not working with https? can any one please help me out? or I will have to write a client from scratch?
Thanks
A:
Your https server probably has a self-signed or other invalid certificate. Get a valid certificate or suppress https certificate validation with
ServicePointManager.ServerCertificateValidationCallback = (a, b, c, e) => true ;
|
XML RPC client for C# over secured socket (https)
|
I have a secured (https) XML-RPC server written in python, and I have tested it with a python based client. but I need a C# based client for it, I have given a try to xml-rpc.net
but it is not working with https? can any one please help me out? or I will have to write a client from scratch?
Thanks
|
[
"Your https server probably has a self-signed or other invalid certificate. Get a valid certificate or suppress https certificate validation with\nServicePointManager.ServerCertificateValidationCallback = (a, b, c, e) => true ;\n\n"
] |
[
2
] |
[] |
[] |
[
"c#",
"https",
"python",
"xml_rpc"
] |
stackoverflow_0002536271_c#_https_python_xml_rpc.txt
|
Q:
Intra-package references in python and GUI tests
I have problem concerning python packages and testing. I'm writing an application using wx python and have the following basic folder/package structure for the gui parts. The mainframe.py window has a dependency to the logpane.py panel, which is easily imported using an absolute import in mainframe.py:
import guiapp.utilviews.logpane
Folder/package layout:
mainapp
- main.py
guiapp
- __init__.py
utilviews
- __init__.py
- logpane.py
- other stuff...
mainview
- __init__.py
- mainframe.py
- other stuff here...
other views...
However, for the gui parts of the application I'd like to, in addition to unit tests (and they pose no problem), have a small "test"/example for each view. That is, for the logpane, I'd like to have small runnable example that will lauch a bare bone application showing the view to test that layout is ok etc.
The way I started out was that I had a
if __name__ == "__main__":
# create some small window and a wx app
# instanciate the panel and launch the app
pass
in the actual implementation file of the panel/view itself. This worked wonders for the logpane. I could just run the file standalone to have a look at the view and see that it held together.
But of course the strategy broke down for the mainframe.py since the dependency to logpane.py couldn't be resolved. This since the current main module is the mainframe.py and the only way mainframe.py can reach the utilviews package is if the main/launched module is further up in the tree.
So how do I structure these types of tests? For unit tests I use nose which is nice and takes care of the problem since nose is launched per the mainapp folder (so all intrapackage references works). But these tests are like small stand-alone programs. I simply can't clutter the mainapp folder with these python files (there will be many such files). Are there any other way I can accomplish this?
Any input is valuable.
Thanks,
Rickard
A:
You could use PYTHONPATH. Set it to your main project directory, before executing your test file. It will then be able to resolve all your imports just as if you would be executing from that directory.
$ find
.
./test
./test/test.py
./some
./some/__init__.py
$ cat some/__init__.py
x = 10
$ cat test/test.py
import some
print some.x
$ cd test
$ export PYTHONPATH=..
$ python test.py
10
|
Intra-package references in python and GUI tests
|
I have problem concerning python packages and testing. I'm writing an application using wx python and have the following basic folder/package structure for the gui parts. The mainframe.py window has a dependency to the logpane.py panel, which is easily imported using an absolute import in mainframe.py:
import guiapp.utilviews.logpane
Folder/package layout:
mainapp
- main.py
guiapp
- __init__.py
utilviews
- __init__.py
- logpane.py
- other stuff...
mainview
- __init__.py
- mainframe.py
- other stuff here...
other views...
However, for the gui parts of the application I'd like to, in addition to unit tests (and they pose no problem), have a small "test"/example for each view. That is, for the logpane, I'd like to have small runnable example that will lauch a bare bone application showing the view to test that layout is ok etc.
The way I started out was that I had a
if __name__ == "__main__":
# create some small window and a wx app
# instanciate the panel and launch the app
pass
in the actual implementation file of the panel/view itself. This worked wonders for the logpane. I could just run the file standalone to have a look at the view and see that it held together.
But of course the strategy broke down for the mainframe.py since the dependency to logpane.py couldn't be resolved. This since the current main module is the mainframe.py and the only way mainframe.py can reach the utilviews package is if the main/launched module is further up in the tree.
So how do I structure these types of tests? For unit tests I use nose which is nice and takes care of the problem since nose is launched per the mainapp folder (so all intrapackage references works). But these tests are like small stand-alone programs. I simply can't clutter the mainapp folder with these python files (there will be many such files). Are there any other way I can accomplish this?
Any input is valuable.
Thanks,
Rickard
|
[
"You could use PYTHONPATH. Set it to your main project directory, before executing your test file. It will then be able to resolve all your imports just as if you would be executing from that directory.\n$ find\n.\n./test\n./test/test.py\n./some\n./some/__init__.py\n\n$ cat some/__init__.py \nx = 10\n\n$ cat test/test.py \nimport some\nprint some.x\n\n$ cd test\n$ export PYTHONPATH=..\n$ python test.py\n10\n\n"
] |
[
2
] |
[] |
[] |
[
"package",
"project_layout",
"python",
"testing"
] |
stackoverflow_0002536335_package_project_layout_python_testing.txt
|
Q:
Simple way to create possible case
I have lists of data such as
a = [1,2,3,4]
b = ["a","b","c","d","e"]
c = ["001","002","003"]
And I want to create new another list that was mixed from all possible case of a,b,c like this
d = ["1a001","1a002","1a003",...,"4e003"]
Is there any module or method to generate d without write many for loop?
A:
[''.join(str(y) for y in x) for x in itertools.product(a, b, c)]
A:
This is a little simpler to do if you convert a to be a list of str too.
and saves needlessly calling str() on each element of b and c
>>> from itertools import product
>>> a = [1,2,3,4]
>>> b = ["a","b","c","d","e"]
>>> c = ["001","002","003"]
>>> a = map(str,a) # so a=['1', '2', '3', '4']
>>> map(''.join, product(a, b, c))
['1a001', '1a002', '1a003', '1b001', '1b002', '1b003', '1c001', '1c002', '1c003', '1d001', '1d002', '1d003', '1e001', '1e002', '1e003', '2a001', '2a002', '2a003', '2b001', '2b002', '2b003', '2c001', '2c002', '2c003', '2d001', '2d002', '2d003', '2e001', '2e002', '2e003', '3a001', '3a002', '3a003', '3b001', '3b002', '3b003', '3c001', '3c002', '3c003', '3d001', '3d002', '3d003', '3e001', '3e002', '3e003', '4a001', '4a002', '4a003', '4b001', '4b002', '4b003', '4c001', '4c002', '4c003', '4d001', '4d002', '4d003', '4e001', '4e002', '4e003']
Here is a timing comparison
timeit astr=map(str,a);map(''.join, product(astr, b, c))
10000 loops, best of 3: 43 us per loop
timeit [''.join(str(y) for y in x) for x in product(a, b, c)]
1000 loops, best of 3: 399 us per loop
A:
How about this? Using map
print [''.join(map(str,y)) for y in itertools.product(a,b,c)]
A:
map(''.join, itertools.product(map(str, a), b, c))
|
Simple way to create possible case
|
I have lists of data such as
a = [1,2,3,4]
b = ["a","b","c","d","e"]
c = ["001","002","003"]
And I want to create new another list that was mixed from all possible case of a,b,c like this
d = ["1a001","1a002","1a003",...,"4e003"]
Is there any module or method to generate d without write many for loop?
|
[
"[''.join(str(y) for y in x) for x in itertools.product(a, b, c)]\n\n",
"This is a little simpler to do if you convert a to be a list of str too.\nand saves needlessly calling str() on each element of b and c\n>>> from itertools import product\n>>> a = [1,2,3,4]\n>>> b = [\"a\",\"b\",\"c\",\"d\",\"e\"]\n>>> c = [\"001\",\"002\",\"003\"]\n>>> a = map(str,a) # so a=['1', '2', '3', '4']\n>>> map(''.join, product(a, b, c))\n['1a001', '1a002', '1a003', '1b001', '1b002', '1b003', '1c001', '1c002', '1c003', '1d001', '1d002', '1d003', '1e001', '1e002', '1e003', '2a001', '2a002', '2a003', '2b001', '2b002', '2b003', '2c001', '2c002', '2c003', '2d001', '2d002', '2d003', '2e001', '2e002', '2e003', '3a001', '3a002', '3a003', '3b001', '3b002', '3b003', '3c001', '3c002', '3c003', '3d001', '3d002', '3d003', '3e001', '3e002', '3e003', '4a001', '4a002', '4a003', '4b001', '4b002', '4b003', '4c001', '4c002', '4c003', '4d001', '4d002', '4d003', '4e001', '4e002', '4e003']\n\nHere is a timing comparison\ntimeit astr=map(str,a);map(''.join, product(astr, b, c))\n10000 loops, best of 3: 43 us per loop\n\ntimeit [''.join(str(y) for y in x) for x in product(a, b, c)]\n1000 loops, best of 3: 399 us per loop\n\n",
"How about this? Using map\nprint [''.join(map(str,y)) for y in itertools.product(a,b,c)]\n\n",
"map(''.join, itertools.product(map(str, a), b, c))\n\n"
] |
[
17,
1,
1,
1
] |
[] |
[] |
[
"case",
"methods",
"module",
"python"
] |
stackoverflow_0002535924_case_methods_module_python.txt
|
Q:
Pylons: View latest debug message
Is there a way to view the latest debug message instead of having to copy and paste something like "_debug/view/1269848287" to the browser everytime?
A:
(On the off-chance that this helps...)
Ubuntu's default Terminal program auto-detects URLs. When my pylons programs burp, I just ctrl-click on the link in the console.
|
Pylons: View latest debug message
|
Is there a way to view the latest debug message instead of having to copy and paste something like "_debug/view/1269848287" to the browser everytime?
|
[
"(On the off-chance that this helps...)\nUbuntu's default Terminal program auto-detects URLs. When my pylons programs burp, I just ctrl-click on the link in the console.\n"
] |
[
0
] |
[] |
[] |
[
"debugging",
"pylons",
"python"
] |
stackoverflow_0002536468_debugging_pylons_python.txt
|
Q:
python: list modules within the package
I have a package with a few modules, each module has a class (or a few classes) defined within it. I need to get the list of all modules within the package. Is there an API for this in python?
Here is the file structure:
\pkg\
\pkg\__init__.py
\pkg\module1.py -> defines Class1
\pkg\module2.py -> defines Class2
\pkg\module3.py -> defines Class3 and Class31
from within module1 I need to get the list of modules within pkg, and then import all the classes defined in these modules
Update 1:
Ok, after considering the answers and comments below I figured, that it's not that's easy to achieve my need. In order to have the code I proposed below working, all the modules should be explicitly imported beforehand.
So now the new concept:
How to get the list of modules within a package without loading the modules? Using python API, i.e. - without listing all the files in the package folder?
Thanks
ak
A:
One ad-hoc approach is list the files in the directory, import each file dynamically with __import__ and then list the classes of the resulting module.
A:
ok, this was actually pretty straightforward:
import pkg
sub_modules = (
pkg.__dict__.get(a) for a in dir(pkg)
if isinstance(
pkg.__dict__.get(a), types.ModuleType
)
)
for m in sub_modules:
for c in (
m.__dict__.get(a) for a in dir(m)
if isinstance(m.__dict__.get(a), type(Base))
):
""" c is what I needed """
|
python: list modules within the package
|
I have a package with a few modules, each module has a class (or a few classes) defined within it. I need to get the list of all modules within the package. Is there an API for this in python?
Here is the file structure:
\pkg\
\pkg\__init__.py
\pkg\module1.py -> defines Class1
\pkg\module2.py -> defines Class2
\pkg\module3.py -> defines Class3 and Class31
from within module1 I need to get the list of modules within pkg, and then import all the classes defined in these modules
Update 1:
Ok, after considering the answers and comments below I figured, that it's not that's easy to achieve my need. In order to have the code I proposed below working, all the modules should be explicitly imported beforehand.
So now the new concept:
How to get the list of modules within a package without loading the modules? Using python API, i.e. - without listing all the files in the package folder?
Thanks
ak
|
[
"One ad-hoc approach is list the files in the directory, import each file dynamically with __import__ and then list the classes of the resulting module.\n",
"ok, this was actually pretty straightforward:\nimport pkg\n\nsub_modules = ( \n pkg.__dict__.get(a) for a in dir(pkg) \n if isinstance( \n pkg.__dict__.get(a), types.ModuleType\n ) \n) \n\nfor m in sub_modules: \n for c in ( \n m.__dict__.get(a) for a in dir(m) \n if isinstance(m.__dict__.get(a), type(Base))\n ): \n \"\"\" c is what I needed \"\"\"\n\n"
] |
[
1,
0
] |
[] |
[] |
[
"import",
"module",
"package",
"python"
] |
stackoverflow_0002536610_import_module_package_python.txt
|
Q:
How to improve my Python regex syntax?
I very new to Python, and fairly new to regex. (I have no Perl experience.)
I am able to use regular expressions in a way that works, but I'm not sure that my code is particularly Pythonic or consise.
For example, If I wanted to read in a text file and print out text that appears directly between the words 'foo' and 'bar' in each line (presuming this occurred one or zero times a line) I would write the following:
fileList = open(inFile, 'r')
pattern = re.compile(r'(foo)(.*)(bar)')
for line in fileList:
result = pattern.search(line)
if (result != None):
print result.groups()[1]
Is there a better way? The if is necessary to avoid calling groups() on None. But I suspect there is a more concise way to obtain the matching String when there is one, without throwing errors when there isn't.
I'm not hoping for Perl-like unreadability. I just want to accomplish this common task in the commonest and simplest way.
A:
I think it's fine.
Some minor points:-
You can replace result.groups()[x] with result.group(x+1).
If you don't need to capture foo and bar, just use r'foo(.*)bar'.
If you're using Python 2.5+, try to use the with statement so even when there's exception the file can be closed properly.
BTW, as a 5-liner (not that I recommend this):
import re
pattern = re.compile(r'foo(.*)bar')
with open(inFile, 'r') as fileList:
searchResults = (pattern.search(line) for line in fileList)
groups = (result.group(1) for result in searchResults if result is not None)
print '\n'.join(groups)
A:
There are two tricks to be had: the first is the re.finditer regular expression function (and method).
The second is the use of the mmap module.
From the documentation on re.DOTALL, we can note that . does not match newlines:
without this flag, '.' will match anything except a newline.
So if you look for all matches anywhere in the file (such as when read into a string using f.read()), you can pretend each line is an isolated substring (note: it's not quite true, though. If you want the ^ and $ assertions to work this way, use re.MULTILINE). Now, because you noted that we assume there are only zero or one occurrences per line, we don't have to worry about re.finditer() matching more than it should (because it would!). So right away, you could replace all that with iterating over finditer() instead:
fileList = open(inFile, 'r')
pattern = re.compile(r'foo(.*)bar')
for result in pattern.finditer(fileList.read()):
print result.groups(1)
This isn't really nice though. The problem here is that the entire file is read into memory for your convenience. It'd be nice if there was a convenient way to do it without possibly breaking on larger files. And, well, there is! Enter the mmap module.
mmap lets you treat a file as if it were a string (a mutable string, no less!), and it doesn't load the whole thing into memory. The long and short of it is, you can use the following code instead:
fileList = open(inFile, 'r+b')
fileS = mmap.mmap(fileList.fileno(), 0)
pattern = re.compile(r'foo(.*)bar')
for result in pattern.finditer(fileS):
print result.groups(1)
and it will work just the same, but without consuming the whole file at once (hopefully).
A:
you don't need regex. split your string on "bar", iterate them, find "foo", do a split on "foo" and get the results to the right. Of course, you can use other string manipulation like getting the index and stuff.
>>> s="w1 w2 foo what i want bar w3 w4 foowhatiwantbar w5"
>>> for item in s.split("bar"):
... if "foo" in item:
... print item.split("foo")[1:]
...
[' what i want ']
['whatiwant']
A:
I have a few minor suggestions:
Unless you're certain that foo and bar can occur no more than once per line, it's better to use .*? instead of .*
If you need to make sure that foo and bar should only be matched as entire words (as opposed to foonly and rebar), you should add \b anchors around them (\bfoo\b etc.)
You could use lookaround to match only the match itself ((?<=\bfoo\b).*?(?=\bbar\b)), so now result.group(0) will contain the match. But that's not really more readable :)
|
How to improve my Python regex syntax?
|
I very new to Python, and fairly new to regex. (I have no Perl experience.)
I am able to use regular expressions in a way that works, but I'm not sure that my code is particularly Pythonic or consise.
For example, If I wanted to read in a text file and print out text that appears directly between the words 'foo' and 'bar' in each line (presuming this occurred one or zero times a line) I would write the following:
fileList = open(inFile, 'r')
pattern = re.compile(r'(foo)(.*)(bar)')
for line in fileList:
result = pattern.search(line)
if (result != None):
print result.groups()[1]
Is there a better way? The if is necessary to avoid calling groups() on None. But I suspect there is a more concise way to obtain the matching String when there is one, without throwing errors when there isn't.
I'm not hoping for Perl-like unreadability. I just want to accomplish this common task in the commonest and simplest way.
|
[
"I think it's fine.\nSome minor points:-\n\nYou can replace result.groups()[x] with result.group(x+1).\nIf you don't need to capture foo and bar, just use r'foo(.*)bar'.\nIf you're using Python 2.5+, try to use the with statement so even when there's exception the file can be closed properly.\n\n\nBTW, as a 5-liner (not that I recommend this):\nimport re\npattern = re.compile(r'foo(.*)bar')\nwith open(inFile, 'r') as fileList:\n searchResults = (pattern.search(line) for line in fileList)\n groups = (result.group(1) for result in searchResults if result is not None)\n print '\\n'.join(groups)\n\n",
"There are two tricks to be had: the first is the re.finditer regular expression function (and method).\nThe second is the use of the mmap module.\nFrom the documentation on re.DOTALL, we can note that . does not match newlines:\n\nwithout this flag, '.' will match anything except a newline.\n\nSo if you look for all matches anywhere in the file (such as when read into a string using f.read()), you can pretend each line is an isolated substring (note: it's not quite true, though. If you want the ^ and $ assertions to work this way, use re.MULTILINE). Now, because you noted that we assume there are only zero or one occurrences per line, we don't have to worry about re.finditer() matching more than it should (because it would!). So right away, you could replace all that with iterating over finditer() instead:\nfileList = open(inFile, 'r')\npattern = re.compile(r'foo(.*)bar')\nfor result in pattern.finditer(fileList.read()):\n print result.groups(1)\n\nThis isn't really nice though. The problem here is that the entire file is read into memory for your convenience. It'd be nice if there was a convenient way to do it without possibly breaking on larger files. And, well, there is! Enter the mmap module.\nmmap lets you treat a file as if it were a string (a mutable string, no less!), and it doesn't load the whole thing into memory. The long and short of it is, you can use the following code instead:\nfileList = open(inFile, 'r+b')\nfileS = mmap.mmap(fileList.fileno(), 0)\npattern = re.compile(r'foo(.*)bar')\nfor result in pattern.finditer(fileS):\n print result.groups(1)\n\nand it will work just the same, but without consuming the whole file at once (hopefully).\n",
"you don't need regex. split your string on \"bar\", iterate them, find \"foo\", do a split on \"foo\" and get the results to the right. Of course, you can use other string manipulation like getting the index and stuff. \n>>> s=\"w1 w2 foo what i want bar w3 w4 foowhatiwantbar w5\"\n>>> for item in s.split(\"bar\"):\n... if \"foo\" in item:\n... print item.split(\"foo\")[1:]\n...\n[' what i want ']\n['whatiwant']\n\n",
"I have a few minor suggestions:\n\nUnless you're certain that foo and bar can occur no more than once per line, it's better to use .*? instead of .*\nIf you need to make sure that foo and bar should only be matched as entire words (as opposed to foonly and rebar), you should add \\b anchors around them (\\bfoo\\b etc.)\nYou could use lookaround to match only the match itself ((?<=\\bfoo\\b).*?(?=\\bbar\\b)), so now result.group(0) will contain the match. But that's not really more readable :)\n\n"
] |
[
3,
1,
0,
0
] |
[] |
[] |
[
"python",
"regex"
] |
stackoverflow_0002536684_python_regex.txt
|
Q:
Counts of events grouped by date in python?
This is no doubt another noobish question, but I'll ask it anyways:
I have a data set of events with exact datetime in UTC. I'd like to create a line chart showing total number of events by day (date) in the specified date range. Right now I can retrieve the total data set for the needed date range, but then I need to go through it and count up for each date.
The app is running on google app engine and is using python.
What is the best way to create a new data set showing date and corresponding counts (including if there were no events on that date) that I can then use to pass this info to a django template?
Data set for this example looks like this:
class Event(db.Model):
event_name = db.StringProperty()
doe = db.DateTimeProperty()
dlu = db.DateTimeProperty()
user = db.UserProperty()
Ideally, I want something with date and count for that date.
Thanks and please let me know if something else is needed to answer this question!
A:
You'll have to do the binning in-memory (i.e. after the datastore fetch).
The .date() method of a datetime instance will facilitate your binning; it chops off the time element. Then you can use a dictionary to hold the bins:
bins = {}
for event in Event.all().fetch(1000):
bins.setdefault(event.doe.date(), []).append( event )
Then do what you wish with (e.g. count) the bins. For a direct count:
counts = collections.defaultdict(int)
for event in Event.all().fetch(1000):
counts[event.doe.date()] += 1
A:
I can't see how that would be possible with single query as GQL has no support for GROUP BY or aggregation generally.
A:
In order to minimize the amount of work you do, you'll probably want to write a task that sums up the per-day totals once, so you can reuse them. I'd suggest using the bulkupdate library to run a once-a-day task that counts events for the previous day, and creates a new model instance, with a key name based on the date, containing the count. Then, you can get all needed data points by doing a query (or better, a batch get) for the set of summary entities you need.
|
Counts of events grouped by date in python?
|
This is no doubt another noobish question, but I'll ask it anyways:
I have a data set of events with exact datetime in UTC. I'd like to create a line chart showing total number of events by day (date) in the specified date range. Right now I can retrieve the total data set for the needed date range, but then I need to go through it and count up for each date.
The app is running on google app engine and is using python.
What is the best way to create a new data set showing date and corresponding counts (including if there were no events on that date) that I can then use to pass this info to a django template?
Data set for this example looks like this:
class Event(db.Model):
event_name = db.StringProperty()
doe = db.DateTimeProperty()
dlu = db.DateTimeProperty()
user = db.UserProperty()
Ideally, I want something with date and count for that date.
Thanks and please let me know if something else is needed to answer this question!
|
[
"You'll have to do the binning in-memory (i.e. after the datastore fetch).\nThe .date() method of a datetime instance will facilitate your binning; it chops off the time element. Then you can use a dictionary to hold the bins:\nbins = {}\nfor event in Event.all().fetch(1000):\n bins.setdefault(event.doe.date(), []).append( event )\n\nThen do what you wish with (e.g. count) the bins. For a direct count:\ncounts = collections.defaultdict(int)\nfor event in Event.all().fetch(1000):\n counts[event.doe.date()] += 1\n\n",
"I can't see how that would be possible with single query as GQL has no support for GROUP BY or aggregation generally.\n",
"In order to minimize the amount of work you do, you'll probably want to write a task that sums up the per-day totals once, so you can reuse them. I'd suggest using the bulkupdate library to run a once-a-day task that counts events for the previous day, and creates a new model instance, with a key name based on the date, containing the count. Then, you can get all needed data points by doing a query (or better, a batch get) for the set of summary entities you need.\n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"django",
"google_app_engine",
"python"
] |
stackoverflow_0002534424_django_google_app_engine_python.txt
|
Q:
Python Introspection: How to get varnames of class methods?
I want to get the names of the keyword arguments of the methods of a class. I think I understood how to get the names of the methods and how to get the variable names of a specific method, but I don't get how to combine these:
class A(object):
def A1(self, test1=None):
self.test1 = test1
def A2(self, test2=None):
self.test2 = test2
def A3(self):
pass
def A4(self, test4=None, test5=None):
self.test4 = test4
self.test5 = test5
a = A()
# to get the names of the methods:
for methodname in a.__class__.__dict__.keys():
print methodname
# to get the variable names of a specific method:
for varname in a.A1.__func__.__code__.co_varnames:
print varname
# I want to have something like this:
for function in class:
print function.name
for varname in function:
print varname
# desired output:
A1
self
test1
A2
self
test2
A3
self
A4
self
test4
test5
I will have to expose the names of the methods and their arguments to an external API. I have written a twisted app to link to the mentioned api and this twisted app will have to publish this data via the api.
So, I think I will use something like:
for methodname in A.__dict__.keys():
if not methodname.startswith('__'):
print methodname
for varname in A.__dict__[methodname].__code__.co_varnames:
print varname
Once, the surroundings get more stable I will think about a better solution.
A:
import inspect
for name, method in inspect.getmembers(a, inspect.ismethod):
print name
(args, varargs, varkw, defaults) = inspect.getargspec(method)
for arg in args:
print arg
A:
Well, as a direct extension of what you did:
for varname in a.__class__.__dict__['A1'].__code__.co_varnames:
print varname
prints:
self
test1
P.S.: to be honest, I have a feeling this can be done more elegantly...
For example, you can replace a.__class__ with A, but you knew that ;-)
|
Python Introspection: How to get varnames of class methods?
|
I want to get the names of the keyword arguments of the methods of a class. I think I understood how to get the names of the methods and how to get the variable names of a specific method, but I don't get how to combine these:
class A(object):
def A1(self, test1=None):
self.test1 = test1
def A2(self, test2=None):
self.test2 = test2
def A3(self):
pass
def A4(self, test4=None, test5=None):
self.test4 = test4
self.test5 = test5
a = A()
# to get the names of the methods:
for methodname in a.__class__.__dict__.keys():
print methodname
# to get the variable names of a specific method:
for varname in a.A1.__func__.__code__.co_varnames:
print varname
# I want to have something like this:
for function in class:
print function.name
for varname in function:
print varname
# desired output:
A1
self
test1
A2
self
test2
A3
self
A4
self
test4
test5
I will have to expose the names of the methods and their arguments to an external API. I have written a twisted app to link to the mentioned api and this twisted app will have to publish this data via the api.
So, I think I will use something like:
for methodname in A.__dict__.keys():
if not methodname.startswith('__'):
print methodname
for varname in A.__dict__[methodname].__code__.co_varnames:
print varname
Once, the surroundings get more stable I will think about a better solution.
|
[
"import inspect\n\nfor name, method in inspect.getmembers(a, inspect.ismethod):\n print name\n (args, varargs, varkw, defaults) = inspect.getargspec(method)\n for arg in args:\n print arg\n\n",
"Well, as a direct extension of what you did:\nfor varname in a.__class__.__dict__['A1'].__code__.co_varnames:\n print varname\n\nprints:\nself\ntest1\n\nP.S.: to be honest, I have a feeling this can be done more elegantly... \nFor example, you can replace a.__class__ with A, but you knew that ;-) \n"
] |
[
10,
5
] |
[] |
[] |
[
"class",
"introspection",
"python"
] |
stackoverflow_0002536879_class_introspection_python.txt
|
Q:
Where do you use generators feature in your python code?
I have studied generators feature and i think i got it but i would like to understand where i could apply it in my code.
I have in mind the following example i read in "Python essential reference" book:
# tail -f
def tail(f):
f.seek(0,2)
while True:
line = f.readline()
if not line:
time.sleep(0.1)
continue
yield line
Do you have any other effective example where generators are the best tool for the job like tail -f?
How often do you use generators feature and in which kind of functionality\part of program do you usually apply it?
A:
I use them a lot when I implement scanners (tokenizers) or when I iterate over data containers.
Edit: here is a demo tokenizer I used for a C++ syntax highlight program:
whitespace = ' \t\r\n'
operators = '~!%^&*()-+=[]{};:\'"/?.,<>\\|'
def scan(s):
"returns a token and a state/token id"
words = {0:'', 1:'', 2:''} # normal, operator, whitespace
state = 2 # I pick ws as first state
for c in s:
if c in operators:
if state != 1:
yield (words[state], state)
words[state] = ''
state = 1
words[state] += c
elif c in whitespace:
if state != 2:
yield (words[state], state)
words[state] = ''
state = 2
words[state] += c
else:
if state != 0:
yield (words[state], state)
words[state] = ''
state = 0
words[state] += c
yield (words[state], state)
Usage example:
>>> it = scan('foo(); i++')
>>> it.next()
('', 2)
>>> it.next()
('foo', 0)
>>> it.next()
('();', 1)
>>> it.next()
(' ', 2)
>>> it.next()
('i', 0)
>>> it.next()
('++', 1)
>>>
A:
Whenever your code would either generate an unlimited number of values or more generally if too much memory would be consumed by generating the whole list at first.
Or if it is likely that you don't iterate over the whole generated list (and the list is very large). I mean there is no point in generating every value first (and waiting for the generation) if it is not used.
My latest encounter with generators was when I implemented a linear recurrent sequence (LRS) like e.g. the Fibonacci sequence.
A:
In all cases where I have algorithms that read anything, I use generators exclusively.
Why?
Layering in filtering, mapping and reduction rules is so much easier in a context of multiple generators.
Example:
def discard_blank( source ):
for line in source:
if len(line) == 0:
continue
yield line
def clean_end( source ):
for line in source:
yield line.rstrip()
def split_fields( source ):
for line in source;
yield line.split()
def convert_pos( tuple_source, position ):
for line in tuple_source:
yield line[:position]+int(line[position])+line[position+1:]
with open('somefile','r') as source:
data= convert_pos( split_fields( discard_blank( clean_end( source ) ) ), 0 )
total= 0
for l in data:
print l
total += l[0]
print total
My preference is to use many small generators so that a small change is not disruptive to the entire process chain.
A:
In general, to separate data aquisition (which might be complicated) from consumption. In particular:
to concatenate results of several b-tree queries - the db part generates and executes the queries yield-ing records from each one, the consumer only sees single data items arriving.
buffering (read-ahead ) - the generator fetches data in blocks and yields single elements from each block. Again, the consumer is separated from the gory details.
Generators can also work as coroutines. You can pass data into them using nextval=g.next(data) on the 'consumer' side and data = yield(nextval) on the generator side. In this case the generator and its consumer 'swap' values. You can even make yield throw an exception within the generator context: g.throw(exc) does that.
|
Where do you use generators feature in your python code?
|
I have studied generators feature and i think i got it but i would like to understand where i could apply it in my code.
I have in mind the following example i read in "Python essential reference" book:
# tail -f
def tail(f):
f.seek(0,2)
while True:
line = f.readline()
if not line:
time.sleep(0.1)
continue
yield line
Do you have any other effective example where generators are the best tool for the job like tail -f?
How often do you use generators feature and in which kind of functionality\part of program do you usually apply it?
|
[
"I use them a lot when I implement scanners (tokenizers) or when I iterate over data containers.\nEdit: here is a demo tokenizer I used for a C++ syntax highlight program:\nwhitespace = ' \\t\\r\\n'\noperators = '~!%^&*()-+=[]{};:\\'\"/?.,<>\\\\|'\n\ndef scan(s):\n \"returns a token and a state/token id\"\n words = {0:'', 1:'', 2:''} # normal, operator, whitespace\n state = 2 # I pick ws as first state\n for c in s:\n if c in operators:\n if state != 1:\n yield (words[state], state)\n words[state] = ''\n state = 1\n words[state] += c\n elif c in whitespace:\n if state != 2:\n yield (words[state], state)\n words[state] = ''\n state = 2\n words[state] += c\n else:\n if state != 0:\n yield (words[state], state)\n words[state] = ''\n state = 0\n words[state] += c\n yield (words[state], state)\n\nUsage example:\n>>> it = scan('foo(); i++')\n>>> it.next()\n('', 2)\n>>> it.next()\n('foo', 0)\n>>> it.next()\n('();', 1)\n>>> it.next()\n(' ', 2)\n>>> it.next()\n('i', 0)\n>>> it.next()\n('++', 1)\n>>> \n\n",
"Whenever your code would either generate an unlimited number of values or more generally if too much memory would be consumed by generating the whole list at first.\nOr if it is likely that you don't iterate over the whole generated list (and the list is very large). I mean there is no point in generating every value first (and waiting for the generation) if it is not used.\nMy latest encounter with generators was when I implemented a linear recurrent sequence (LRS) like e.g. the Fibonacci sequence. \n",
"In all cases where I have algorithms that read anything, I use generators exclusively. \nWhy? \nLayering in filtering, mapping and reduction rules is so much easier in a context of multiple generators.\nExample:\ndef discard_blank( source ):\n for line in source:\n if len(line) == 0:\n continue\n yield line\n\ndef clean_end( source ):\n for line in source:\n yield line.rstrip()\n\ndef split_fields( source ):\n for line in source;\n yield line.split()\n\ndef convert_pos( tuple_source, position ):\n for line in tuple_source:\n yield line[:position]+int(line[position])+line[position+1:]\n\nwith open('somefile','r') as source:\n data= convert_pos( split_fields( discard_blank( clean_end( source ) ) ), 0 )\n total= 0\n for l in data:\n print l\n total += l[0]\n print total\n\nMy preference is to use many small generators so that a small change is not disruptive to the entire process chain.\n",
"In general, to separate data aquisition (which might be complicated) from consumption. In particular:\n\nto concatenate results of several b-tree queries - the db part generates and executes the queries yield-ing records from each one, the consumer only sees single data items arriving.\nbuffering (read-ahead ) - the generator fetches data in blocks and yields single elements from each block. Again, the consumer is separated from the gory details.\n\nGenerators can also work as coroutines. You can pass data into them using nextval=g.next(data) on the 'consumer' side and data = yield(nextval) on the generator side. In this case the generator and its consumer 'swap' values. You can even make yield throw an exception within the generator context: g.throw(exc) does that.\n"
] |
[
6,
4,
2,
1
] |
[] |
[] |
[
"generator",
"python"
] |
stackoverflow_0002536241_generator_python.txt
|
Q:
Generation of an array of Random numbers with defined Min, Max, Mean and Stdev with given number of elements and error level
I'd like to generate an array of Random numbers with defined Min, Max, Mean and Stdev with given number of elements and error level. Is there such a library in C, C++, PHP or Python to do so? Please kindly advise. Thanks!
A:
The Boost C++ random number library may do some of what you want, certainly you can with some distributions select the modal value of the distribution. That's all I've needed in my own code, so I've never investigated further. The library doesn't generate arrays - you would typically use a C++ std::vector to contain the results of random number generation.
A:
If you want to use python, then I suggest that you use numpy.
http://docs.scipy.org/doc/numpy/reference/routines.random.html
You can probably find many distributions that fit your needs, but maybe you can sample from a beta distribution and rescale the values to fit your needs. Your code will end up looking like this
a1, a2 = ....
temp_array = numpy.random.beta(a1, a2, array_size)
answer = temp_array*(max_value-min_value) + min_value
If you choose this aproach then you need to do a bit of work to find formulas for a1 and a2.
|
Generation of an array of Random numbers with defined Min, Max, Mean and Stdev with given number of elements and error level
|
I'd like to generate an array of Random numbers with defined Min, Max, Mean and Stdev with given number of elements and error level. Is there such a library in C, C++, PHP or Python to do so? Please kindly advise. Thanks!
|
[
"The Boost C++ random number library may do some of what you want, certainly you can with some distributions select the modal value of the distribution. That's all I've needed in my own code, so I've never investigated further. The library doesn't generate arrays - you would typically use a C++ std::vector to contain the results of random number generation.\n",
"If you want to use python, then I suggest that you use numpy. \nhttp://docs.scipy.org/doc/numpy/reference/routines.random.html\nYou can probably find many distributions that fit your needs, but maybe you can sample from a beta distribution and rescale the values to fit your needs. Your code will end up looking like this\na1, a2 = ....\ntemp_array = numpy.random.beta(a1, a2, array_size)\nanswer = temp_array*(max_value-min_value) + min_value\n\nIf you choose this aproach then you need to do a bit of work to find formulas for a1 and a2.\n"
] |
[
4,
4
] |
[] |
[] |
[
"c++",
"generator",
"python",
"statistics"
] |
stackoverflow_0002536615_c++_generator_python_statistics.txt
|
Q:
Prevent wxPython from showing 'Unhandled exception' dialog
I have complex GUI application written in Python and wxPython.
I want it to be certified for Windows Vista, so it has to crash in a way that causes Windows Error Reporting dialog (The one that asks "Do you want to send report to Microsoft?") to appear. This is relevant to test case no 32 from "Certified for Windows Vista Test Cases" document.
Unfortunately when I crash my app with ThreadHijacker tool wxPython shows message like:
Unhandled exception
---------------------------
An unhandled exception occurred. Press "Abort" to terminate the program,
"Retry" to exit the program normally and "Ignore" to try to continue.
---------------------------
Abort Retry Ignore
How can I prevent wxPython from showing this message? I have custom sys.excepthook, but it seems that this dialog is shown before my except hook can interfere.
EDIT:
wxWidgets docs says that wxAppConsole::OnExceptionInMainLoop is called and under MSW it displays some fancy dialog that allows user to choose between the different options. It seems however, that wxPython doesn't allow overloading that function... Does anyone know how to change default behaviour of wxAppConsole::OnExceptionInMainLoop in wxPython?
I prefer solutions that are on Python level over those that go into C/C++
EDIT2:
All in all, I asked at wxPython mailing list, and Robin Dunn answered that he'll look into making wxAppConsole::OnExceptionInMainLoop overridable in next releases of wxPython. Since I couldn't wait, I had to compile my own version of wxPython which does not include that function. It turned out that the presence of wxAppConsole::OnExceptionInMainLoop function can be enabled/disabled by proper setting of compilation flags.
A:
It all ended up with compiling my own wxWidgets and wxPython, with just one compilation flag changed: wxUSE_EXCEPTIONS should be set to 0.
Robin Dunn wrote that he will try to patch wxPython, so this behaviour could be modified without recompiling of the whole library.
A:
If I remember correctly, this is a catch(...) at top level (wxApp) in wxWidgets. You can either use a vectored Exception Handler or _set_se_translator() to get a first shot at the Structured Exception, and exit to WER, i.e. ReportFault() from there.
A:
Is it possible for you to just handle everything? You would have to, I guess, put a try:except: block around every method bound to a widget. You could write a decorator:
def catch_exception(f):
def safe(*args, **kw):
try:
f(*args, **kw)
except Exception, e:
handle_exception(e)
return safe
def handle_exception(e):
# do Vista stuff
sys.exit()
Then decorate any function that could be called by the mainloop (since I presume that's where wxPython does its own catching).
A:
Try http://wiki.python.org/moin/CrashingPython
|
Prevent wxPython from showing 'Unhandled exception' dialog
|
I have complex GUI application written in Python and wxPython.
I want it to be certified for Windows Vista, so it has to crash in a way that causes Windows Error Reporting dialog (The one that asks "Do you want to send report to Microsoft?") to appear. This is relevant to test case no 32 from "Certified for Windows Vista Test Cases" document.
Unfortunately when I crash my app with ThreadHijacker tool wxPython shows message like:
Unhandled exception
---------------------------
An unhandled exception occurred. Press "Abort" to terminate the program,
"Retry" to exit the program normally and "Ignore" to try to continue.
---------------------------
Abort Retry Ignore
How can I prevent wxPython from showing this message? I have custom sys.excepthook, but it seems that this dialog is shown before my except hook can interfere.
EDIT:
wxWidgets docs says that wxAppConsole::OnExceptionInMainLoop is called and under MSW it displays some fancy dialog that allows user to choose between the different options. It seems however, that wxPython doesn't allow overloading that function... Does anyone know how to change default behaviour of wxAppConsole::OnExceptionInMainLoop in wxPython?
I prefer solutions that are on Python level over those that go into C/C++
EDIT2:
All in all, I asked at wxPython mailing list, and Robin Dunn answered that he'll look into making wxAppConsole::OnExceptionInMainLoop overridable in next releases of wxPython. Since I couldn't wait, I had to compile my own version of wxPython which does not include that function. It turned out that the presence of wxAppConsole::OnExceptionInMainLoop function can be enabled/disabled by proper setting of compilation flags.
|
[
"It all ended up with compiling my own wxWidgets and wxPython, with just one compilation flag changed: wxUSE_EXCEPTIONS should be set to 0.\nRobin Dunn wrote that he will try to patch wxPython, so this behaviour could be modified without recompiling of the whole library.\n",
"If I remember correctly, this is a catch(...) at top level (wxApp) in wxWidgets. You can either use a vectored Exception Handler or _set_se_translator() to get a first shot at the Structured Exception, and exit to WER, i.e. ReportFault() from there.\n",
"Is it possible for you to just handle everything? You would have to, I guess, put a try:except: block around every method bound to a widget. You could write a decorator:\ndef catch_exception(f):\n def safe(*args, **kw):\n try:\n f(*args, **kw)\n except Exception, e:\n handle_exception(e)\n return safe\n\ndef handle_exception(e):\n # do Vista stuff\n sys.exit()\n\nThen decorate any function that could be called by the mainloop (since I presume that's where wxPython does its own catching).\n",
"Try http://wiki.python.org/moin/CrashingPython\n"
] |
[
2,
1,
1,
0
] |
[] |
[] |
[
"error_reporting",
"python",
"windows",
"wxpython"
] |
stackoverflow_0000618429_error_reporting_python_windows_wxpython.txt
|
Q:
How do I have signed fields in Django?
class MyTable(models.Model):
lat = models.FloatField(blank=True)
long = models.FloatField(blank=True)
How do I make them signed? Able to accept negative .
A:
FloatField can accept floating point numbers, negatives included.
If you need positive-only integers, there's PositiveIntegerField. Positive-only floats are a much rarer need, so I don't think they're natively supported - but you can, of course, implement this restriction programatically.
|
How do I have signed fields in Django?
|
class MyTable(models.Model):
lat = models.FloatField(blank=True)
long = models.FloatField(blank=True)
How do I make them signed? Able to accept negative .
|
[
"FloatField can accept floating point numbers, negatives included.\nIf you need positive-only integers, there's PositiveIntegerField. Positive-only floats are a much rarer need, so I don't think they're natively supported - but you can, of course, implement this restriction programatically.\n"
] |
[
11
] |
[] |
[] |
[
"database",
"django",
"mysql",
"python"
] |
stackoverflow_0002537319_database_django_mysql_python.txt
|
Q:
Some jQuery-powered features not working in Chrome
I'm using a jCarouselLite plugin for creating two image galleries on the main page of my Django-powered site. The code of elements with navigation arrows is generating dynamically like this:
$(document).ready(function ()
{
$('[jq\\:corner]').each(function(index, item)
{
item = $(item); item.corner(item.attr('jq:corner'))
})
$('[jq\\:menu]').each(function (index, item)
{
item = $(item); item.menu(item.attr('jq:menu'))
})
$('[jq\\:carousel]').each(function(index, item)
{
item = $(item); var args = item.attr('jq:carousel').split(/\s+/)
lister = item.parent().attr('class') + '_lister'
item.parent().append('<div id="'+ lister +'"></div>');
$('#' + lister).append("<a class='nav left' href='#'></a><a class='nav right' href='#'></a>");
toparrow = $(item).position().top + $(item).height() - 50;
widtharrow = $(item).width();
$('#' + lister).css({
'display': 'inline-block',
'z-index': 10,
'position': 'absolute',
'margin-left': '-22px',
'top': toparrow,
'width': widtharrow
})
$('#' + lister + ' .nav.right').css({
'margin-left': $('#' + lister).width() + 22
})
item.jCarouselLite({
btnNext: '#' + lister + ' .nav.right',
btnPrev: '#' + lister + ' .nav.left',
visible: parseInt(args[0])
})
})
The problem is that if page is loaded through an url, typed in the adress bar, some functions doesn't work and the second gallery appears with the wrong parameters, but if I came to this page via clicking link - everything works perfectly. It happends only in Google Chrome (Ubuntu, stable 5.0.360.0), but not in Firefox or Opera.
What could be the reason?
A:
No idea if this matches your issues, but I've been running the dev channel of chrome for linux and this weekend had issues with it working with the jquery ui 1.8 release button plugin. Come to find out it was a Chrome bug and updating solved the issue.
|
Some jQuery-powered features not working in Chrome
|
I'm using a jCarouselLite plugin for creating two image galleries on the main page of my Django-powered site. The code of elements with navigation arrows is generating dynamically like this:
$(document).ready(function ()
{
$('[jq\\:corner]').each(function(index, item)
{
item = $(item); item.corner(item.attr('jq:corner'))
})
$('[jq\\:menu]').each(function (index, item)
{
item = $(item); item.menu(item.attr('jq:menu'))
})
$('[jq\\:carousel]').each(function(index, item)
{
item = $(item); var args = item.attr('jq:carousel').split(/\s+/)
lister = item.parent().attr('class') + '_lister'
item.parent().append('<div id="'+ lister +'"></div>');
$('#' + lister).append("<a class='nav left' href='#'></a><a class='nav right' href='#'></a>");
toparrow = $(item).position().top + $(item).height() - 50;
widtharrow = $(item).width();
$('#' + lister).css({
'display': 'inline-block',
'z-index': 10,
'position': 'absolute',
'margin-left': '-22px',
'top': toparrow,
'width': widtharrow
})
$('#' + lister + ' .nav.right').css({
'margin-left': $('#' + lister).width() + 22
})
item.jCarouselLite({
btnNext: '#' + lister + ' .nav.right',
btnPrev: '#' + lister + ' .nav.left',
visible: parseInt(args[0])
})
})
The problem is that if page is loaded through an url, typed in the adress bar, some functions doesn't work and the second gallery appears with the wrong parameters, but if I came to this page via clicking link - everything works perfectly. It happends only in Google Chrome (Ubuntu, stable 5.0.360.0), but not in Firefox or Opera.
What could be the reason?
|
[
"No idea if this matches your issues, but I've been running the dev channel of chrome for linux and this weekend had issues with it working with the jquery ui 1.8 release button plugin. Come to find out it was a Chrome bug and updating solved the issue. \n"
] |
[
0
] |
[] |
[] |
[
"django",
"javascript",
"jquery",
"python"
] |
stackoverflow_0002537096_django_javascript_jquery_python.txt
|
Q:
Exception Handling in google app engine
i am raising exception using
if UserId == '' and Password == '':
raise Exception.MyException , "wrong userId or password"
but i want print the error message on same page
class MyException(Exception):
def __init__(self,msg):
Exception.__init__(self,msg)
A:
You are not using the Users API? Assuming you are handling a POST request, how about this:
class LoginError(Exception):
CODES = { 'mismatch': 'Wrong credentials', 'disabled': 'Account disabled' }
...
try:
// your authentication code
raise LoginError('mismatch')
...
raise LoginError('disabled')
except LoginError as e:
self.redirect(your_login_url + '?err=' + e)
# In login page you must not print arbitrary GET parameter directly
err_reason = LoginError.CODES[self.request.get('err')]`
(Login request should be using POST method because it changes the server's state, and it's good habit to redirect after a POST, thus a redirect.)
A:
Why raising an exception instead of just stop function execution and redirect to new page using return statement
|
Exception Handling in google app engine
|
i am raising exception using
if UserId == '' and Password == '':
raise Exception.MyException , "wrong userId or password"
but i want print the error message on same page
class MyException(Exception):
def __init__(self,msg):
Exception.__init__(self,msg)
|
[
"You are not using the Users API? Assuming you are handling a POST request, how about this:\nclass LoginError(Exception):\n CODES = { 'mismatch': 'Wrong credentials', 'disabled': 'Account disabled' }\n ...\n\ntry:\n // your authentication code\n raise LoginError('mismatch')\n ...\n raise LoginError('disabled')\nexcept LoginError as e:\n self.redirect(your_login_url + '?err=' + e)\n\n# In login page you must not print arbitrary GET parameter directly\nerr_reason = LoginError.CODES[self.request.get('err')]`\n\n(Login request should be using POST method because it changes the server's state, and it's good habit to redirect after a POST, thus a redirect.)\n",
"Why raising an exception instead of just stop function execution and redirect to new page using return statement\n"
] |
[
1,
0
] |
[] |
[] |
[
"exception_handling",
"google_app_engine",
"python"
] |
stackoverflow_0002537357_exception_handling_google_app_engine_python.txt
|
Q:
django views getid
class host(models.Model):
emp = models.ForeignKey(getname)
def __unicode__(self):
return self.topic
In views there is the code as,
real =[]
for emp in my_emp:
real.append(host.objects.filter(emp=emp.id))
This above results only the values of emp,My question is that how to get the ids along with emp values.
Thanks..
A:
Just add them to the list when you are processing my_emp list, something like that:
real = []
for emp in my_emp:
real.append((emp.id, host.objects.filter(emp=emp.id)))
Later
for emp_id, host in real:
# do something usefull
You can also get list of all emp objects for given host object by:
emp_list = host.emp_set.all()
A:
You probably want to do this whole thing in a single query:
Host.objects.filter(emp__in=my_emp)
which will get you queryset of all Host objects for your list of emp ids.
|
django views getid
|
class host(models.Model):
emp = models.ForeignKey(getname)
def __unicode__(self):
return self.topic
In views there is the code as,
real =[]
for emp in my_emp:
real.append(host.objects.filter(emp=emp.id))
This above results only the values of emp,My question is that how to get the ids along with emp values.
Thanks..
|
[
"Just add them to the list when you are processing my_emp list, something like that:\nreal = []\nfor emp in my_emp:\n real.append((emp.id, host.objects.filter(emp=emp.id)))\n\nLater\nfor emp_id, host in real:\n # do something usefull\n\nYou can also get list of all emp objects for given host object by:\nemp_list = host.emp_set.all()\n\n",
"You probably want to do this whole thing in a single query:\nHost.objects.filter(emp__in=my_emp)\n\nwhich will get you queryset of all Host objects for your list of emp ids.\n"
] |
[
1,
1
] |
[] |
[] |
[
"django",
"django_models",
"django_views",
"python"
] |
stackoverflow_0002537469_django_django_models_django_views_python.txt
|
Q:
How to best design a date/geographic proximity query on GAE?
I'm building a directory for finding athletic tournaments on GAE with
web2py and a Flex front end. The user selects a location, a radius, and a maximum
date from a set of choices. I have a basic version of this query implemented, but it's
inefficient and slow. One way I know I can improve it is by condensing
the many individual queries I'm using to assemble the objects into
bulk queries. I just learned that was possible. But I'm also thinking about a more extensive redesign that utilizes memcache.
The main problem is that I can't query the datastore by location
because GAE won't allow multiple numerical comparison statements
(<,<=,>=,>) in one query. I'm already using one for date, and I'd need
TWO to check both latitude and longitude, so it's a no go. Currently,
my algorithm looks like this:
1.) Query by date and select
2.) Use destination function from geopy's distance module to find the
max and min latitude and longitudes for supplied distance
3.) Loop through results and remove all with lat/lng outside max/min
4.) Loop through again and use distance function to check exact
distance, because step 2 will include some areas outside the radius.
Remove results outside supplied distance (is this 2/3/4 combination
inefficent?)
5.) Assemble many-to-many lists and attach to objects (this is where I
need to switch to bulk operations)
6.) Return to client
Here's my plan for using memcache.. let me know if I'm way out in left
field on this as I have no prior experience with memcache or server
caching in general.
-Keep a list in the cache filled with "geo objects" that represent all
my data. These have five properties: latitude, longitude, event_id,
event_type (in anticipation of expanding beyond tournaments), and
start_date. This list will be sorted by date.
-Also keep a dict of pointers in the cache which represent the start
and end indices in the cache for all the date ranges my app uses (next
week, 2 weeks, month, 3 months, 6 months, year, 2 years).
-Have a scheduled task that updates the pointers daily at 12am.
-Add new inserts to the cache as well as the datastore; update
pointers.
Using this design, the algorithm would now look like:
1.) Use pointers to slice off appropriate chunk of list based on
supplied date.
2-4.) Same as above algorithm, except with geo objects
5.) Use bulk operation to select full tournaments using remaining geo
objects' event_ids
6.) Assemble many-to-manys
7.) Return to client
Thoughts on this approach? Many thanks for reading and any advice you
can give.
-Dane
A:
GeoModel is the best I found. You may look how my GAE app return geospatial queries. For instance India http query is with optional cc (country code) using geomodel library lat=20.2095231&lon=79.560344&cc=IN
A:
You might be interested by geohash, which enables you to do an inequality query like this:
SELECT latitude, longitude, title FROM
myMarkers WHERE geohash >= :sw_geohash
AND geohash <= :ne_geohash
Have a look at this fine article which was featured in this month's Google App Engine App Engine Community Update blog post.
As a note on your proposed design, don't forget that entities in Memcache have no guarantee of staying in memory, and that you can not have them "sorted by date".
|
How to best design a date/geographic proximity query on GAE?
|
I'm building a directory for finding athletic tournaments on GAE with
web2py and a Flex front end. The user selects a location, a radius, and a maximum
date from a set of choices. I have a basic version of this query implemented, but it's
inefficient and slow. One way I know I can improve it is by condensing
the many individual queries I'm using to assemble the objects into
bulk queries. I just learned that was possible. But I'm also thinking about a more extensive redesign that utilizes memcache.
The main problem is that I can't query the datastore by location
because GAE won't allow multiple numerical comparison statements
(<,<=,>=,>) in one query. I'm already using one for date, and I'd need
TWO to check both latitude and longitude, so it's a no go. Currently,
my algorithm looks like this:
1.) Query by date and select
2.) Use destination function from geopy's distance module to find the
max and min latitude and longitudes for supplied distance
3.) Loop through results and remove all with lat/lng outside max/min
4.) Loop through again and use distance function to check exact
distance, because step 2 will include some areas outside the radius.
Remove results outside supplied distance (is this 2/3/4 combination
inefficent?)
5.) Assemble many-to-many lists and attach to objects (this is where I
need to switch to bulk operations)
6.) Return to client
Here's my plan for using memcache.. let me know if I'm way out in left
field on this as I have no prior experience with memcache or server
caching in general.
-Keep a list in the cache filled with "geo objects" that represent all
my data. These have five properties: latitude, longitude, event_id,
event_type (in anticipation of expanding beyond tournaments), and
start_date. This list will be sorted by date.
-Also keep a dict of pointers in the cache which represent the start
and end indices in the cache for all the date ranges my app uses (next
week, 2 weeks, month, 3 months, 6 months, year, 2 years).
-Have a scheduled task that updates the pointers daily at 12am.
-Add new inserts to the cache as well as the datastore; update
pointers.
Using this design, the algorithm would now look like:
1.) Use pointers to slice off appropriate chunk of list based on
supplied date.
2-4.) Same as above algorithm, except with geo objects
5.) Use bulk operation to select full tournaments using remaining geo
objects' event_ids
6.) Assemble many-to-manys
7.) Return to client
Thoughts on this approach? Many thanks for reading and any advice you
can give.
-Dane
|
[
"GeoModel is the best I found. You may look how my GAE app return geospatial queries. For instance India http query is with optional cc (country code) using geomodel library lat=20.2095231&lon=79.560344&cc=IN\n",
"You might be interested by geohash, which enables you to do an inequality query like this:\n\nSELECT latitude, longitude, title FROM\n myMarkers WHERE geohash >= :sw_geohash\n AND geohash <= :ne_geohash\n\nHave a look at this fine article which was featured in this month's Google App Engine App Engine Community Update blog post.\nAs a note on your proposed design, don't forget that entities in Memcache have no guarantee of staying in memory, and that you can not have them \"sorted by date\".\n"
] |
[
2,
1
] |
[] |
[] |
[
"caching",
"google_app_engine",
"google_cloud_datastore",
"python",
"web2py"
] |
stackoverflow_0002525747_caching_google_app_engine_google_cloud_datastore_python_web2py.txt
|
Q:
In Google's Protocol Buffers, what is a suitable protocol file/model for Exceptions?
Protocol Buffers doesn't have a native Exception type. What would a suitable .proto file for cross-language exceptions look like?
A:
The technical lead of Protocol Buffers, Kenton Varda, says in comment 9 on this blog post:
If you need to return structured
errors, then the right way to do it is
to make your response type be able to
represent that information... We felt
that supporting exceptions explicitly
would add too much complication with
little real gain.
This makes sense, given that if you want to return detailed error information, the .proto declarations would differ depending on the situation. If you want very generic exceptions (just a string message) then an underlying RPC mechanism may be able to provide this already, e.g. HTTP status.
|
In Google's Protocol Buffers, what is a suitable protocol file/model for Exceptions?
|
Protocol Buffers doesn't have a native Exception type. What would a suitable .proto file for cross-language exceptions look like?
|
[
"The technical lead of Protocol Buffers, Kenton Varda, says in comment 9 on this blog post:\n\nIf you need to return structured\n errors, then the right way to do it is\n to make your response type be able to\n represent that information... We felt\n that supporting exceptions explicitly\n would add too much complication with\n little real gain.\n\nThis makes sense, given that if you want to return detailed error information, the .proto declarations would differ depending on the situation. If you want very generic exceptions (just a string message) then an underlying RPC mechanism may be able to provide this already, e.g. HTTP status.\n"
] |
[
5
] |
[] |
[] |
[
"exception",
"java",
"php",
"protocol_buffers",
"python"
] |
stackoverflow_0002532236_exception_java_php_protocol_buffers_python.txt
|
Q:
How can I format strings to query with mysqldb in Python?
How do I do this correctly:
I want to do a query like this:
query = """SELECT * FROM sometable
order by %s %s
limit %s, %s;"""
conn = app_globals.pool.connection()
cur = conn.cursor()
cur.execute(query, (sortname, sortorder, limit1, limit2) )
results = cur.fetchall()
All works fine but the order by %s %s is not putting the strings in correctly. It is putting the two substitutions in with quotes around them.
So it ends up like:
ORDER BY 'somecol' 'DESC'
Which is wrong should be:
ORDER BY somecol DESC
Any help greatly appreciated!
A:
paramstyle
Parameter placeholders can only be used to insert column values. They can not be used for other parts of SQL, such as table names, statements, etc.
A:
%s placeholders inside query string are reserved for parameters. %s in 'order by %s %s' are not parameters. You should make query string in 2 steps:
query = """SELECT * FROM sometable order by %s %s limit %%s, %%s;"""
query = query % ('somecol', 'DESC')
conn = app_globals.pool.connection()
cur = conn.cursor()
cur.execute(query, (limit1, limit2) )
results = cur.fetchall()
DO NOT FORGET to filter first substitution to prevent SQL-injection possibilities
A:
Not all parts of an SQL query can be parametrized. The DESC keyword for example is not
a parameter. Try
query = """SELECT * FROM sometable
order by %s """ + sortorder + """
limit %s, %s"""
cur.execute(query, (sortname, limit1, limit2) )
|
How can I format strings to query with mysqldb in Python?
|
How do I do this correctly:
I want to do a query like this:
query = """SELECT * FROM sometable
order by %s %s
limit %s, %s;"""
conn = app_globals.pool.connection()
cur = conn.cursor()
cur.execute(query, (sortname, sortorder, limit1, limit2) )
results = cur.fetchall()
All works fine but the order by %s %s is not putting the strings in correctly. It is putting the two substitutions in with quotes around them.
So it ends up like:
ORDER BY 'somecol' 'DESC'
Which is wrong should be:
ORDER BY somecol DESC
Any help greatly appreciated!
|
[
"\nparamstyle\n Parameter placeholders can only be used to insert column values. They can not be used for other parts of SQL, such as table names, statements, etc.\n\n",
"%s placeholders inside query string are reserved for parameters. %s in 'order by %s %s' are not parameters. You should make query string in 2 steps:\nquery = \"\"\"SELECT * FROM sometable order by %s %s limit %%s, %%s;\"\"\"\nquery = query % ('somecol', 'DESC')\nconn = app_globals.pool.connection()\ncur = conn.cursor()\ncur.execute(query, (limit1, limit2) ) \nresults = cur.fetchall()\n\nDO NOT FORGET to filter first substitution to prevent SQL-injection possibilities \n",
"Not all parts of an SQL query can be parametrized. The DESC keyword for example is not \na parameter. Try \nquery = \"\"\"SELECT * FROM sometable \n order by %s \"\"\" + sortorder + \"\"\"\n limit %s, %s\"\"\"\n\ncur.execute(query, (sortname, limit1, limit2) ) \n\n"
] |
[
9,
6,
0
] |
[
"You could try this alternatively...\nquery = \"\"\"SELECT * FROM sometable \n order by {0} {1} \n limit {2}, {3};\"\"\"\n\nsortname = 'somecol'\nsortorder = 'DESC'\nlimit1 = 'limit1'\nlimit2 = 'limit2'\n\nprint(query.format(sortname, sortorder, limit1, limit2))\n\n"
] |
[
-1
] |
[
"mysql",
"python",
"string"
] |
stackoverflow_0002538311_mysql_python_string.txt
|
Q:
Rearranging a sequence
I'm have trouble rearranging sequences so the amount of letters in the given original sequence are the same in the random generated sequences. For example:
If i have a string 'AAAC'
I need that string rearranged randomly so the amount of A's and C's are the same.
A:
import random
chars = list("AAAC")
random.shuffle(chars)
return ''.join(chars)
|
Rearranging a sequence
|
I'm have trouble rearranging sequences so the amount of letters in the given original sequence are the same in the random generated sequences. For example:
If i have a string 'AAAC'
I need that string rearranged randomly so the amount of A's and C's are the same.
|
[
"import random\nchars = list(\"AAAC\")\nrandom.shuffle(chars)\nreturn ''.join(chars)\n\n"
] |
[
6
] |
[] |
[] |
[
"python",
"random"
] |
stackoverflow_0002538538_python_random.txt
|
Q:
virtualenv does not copy standard modules like shutil and urllib2
When I create a new virtualenv, virtualenv .virtualenvs/my_env, there is only a subset of the standard python modules copied/linked to the new virtualenv.
For example, when I do ls -l in .virtualenvs/my_env/lib/python2.6, I see:
...
... os.py -> /usr/lib/python2.6/os.py
... os.pyc -> /usr/lib/python2.6/os.pyc
but modules like shutil and urllib2 are not copied even if they are in /usr/lib/python2.6/shutil.py. I am using Ubuntu 9.10.
Is this the expected behavior? How can I install modules such as shutil in a virtualenv (I could not find these modules on pypi)?
A:
virtualenv munges sys.path to insert your virtual environment in front of the system libraries, but the system libraries are still on the path, so they should still be accessible.
So, for instance, do:
>>> import os
>>> os
<module 'posixpath' from '/environments/userpython/lib/python2.6/posixpath.pyc'>
>>> import shutil
>>> shutil
<module 'shutil' from '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/shutil.pyc'>
My os module is from my virtual environment, but the shutil module is coming from my system Python.
|
virtualenv does not copy standard modules like shutil and urllib2
|
When I create a new virtualenv, virtualenv .virtualenvs/my_env, there is only a subset of the standard python modules copied/linked to the new virtualenv.
For example, when I do ls -l in .virtualenvs/my_env/lib/python2.6, I see:
...
... os.py -> /usr/lib/python2.6/os.py
... os.pyc -> /usr/lib/python2.6/os.pyc
but modules like shutil and urllib2 are not copied even if they are in /usr/lib/python2.6/shutil.py. I am using Ubuntu 9.10.
Is this the expected behavior? How can I install modules such as shutil in a virtualenv (I could not find these modules on pypi)?
|
[
"virtualenv munges sys.path to insert your virtual environment in front of the system libraries, but the system libraries are still on the path, so they should still be accessible.\nSo, for instance, do:\n>>> import os\n>>> os\n<module 'posixpath' from '/environments/userpython/lib/python2.6/posixpath.pyc'>\n>>> import shutil\n>>> shutil\n<module 'shutil' from '/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/shutil.pyc'>\n\nMy os module is from my virtual environment, but the shutil module is coming from my system Python.\n"
] |
[
7
] |
[] |
[] |
[
"python",
"virtualenv"
] |
stackoverflow_0002538523_python_virtualenv.txt
|
Q:
Django says the "id may not be NULL" but why is it?
I'm going crazy today. I just tried to insert a new record and it threw back a "post_blogpost.id may not be NULL" error. Here's my model:
class BlogPost(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
who = models.ForeignKey(User, default=1)
when = models.DateTimeField()
intro = models.TextField(blank=True, null=True)
content = models.TextField(blank=True, null=True)
counter = models.PositiveIntegerField(default=0)
published = models.BooleanField(default=False)
css = models.TextField(blank=True, null=True)
class Meta:
ordering = ('-when', 'id')
There are a number of functions beneath the model too but I won't include them in full here. Their names are: content_cache_key, clear_cache, __unicode__, reads, read, processed_content.
I'm adding through the admin... And I'm running out of hair.
A:
The only thing I can think of is that the table schema has become desynchronized from the model in that someone removed the AUTOINCREMENT attribute from the PK of the table.
A:
I've also experienced odd editing results in the admin. Usually they were related to foreign keys. When the edit page has a bunch of empty model instances on one page so that you can easily create new ones by filling them out, sometimes I managed to do something wrong such that an attempt would be made to save the empty instances. Maybe that applies for you.
You could verify that this adds fine by itself in a shell.
$ python manage.py shell
>>> from models import *
>>> b = BlogPost(title='Hello', slug='hello')
>>> b.save()
|
Django says the "id may not be NULL" but why is it?
|
I'm going crazy today. I just tried to insert a new record and it threw back a "post_blogpost.id may not be NULL" error. Here's my model:
class BlogPost(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
who = models.ForeignKey(User, default=1)
when = models.DateTimeField()
intro = models.TextField(blank=True, null=True)
content = models.TextField(blank=True, null=True)
counter = models.PositiveIntegerField(default=0)
published = models.BooleanField(default=False)
css = models.TextField(blank=True, null=True)
class Meta:
ordering = ('-when', 'id')
There are a number of functions beneath the model too but I won't include them in full here. Their names are: content_cache_key, clear_cache, __unicode__, reads, read, processed_content.
I'm adding through the admin... And I'm running out of hair.
|
[
"The only thing I can think of is that the table schema has become desynchronized from the model in that someone removed the AUTOINCREMENT attribute from the PK of the table.\n",
"I've also experienced odd editing results in the admin. Usually they were related to foreign keys. When the edit page has a bunch of empty model instances on one page so that you can easily create new ones by filling them out, sometimes I managed to do something wrong such that an attempt would be made to save the empty instances. Maybe that applies for you.\nYou could verify that this adds fine by itself in a shell.\n$ python manage.py shell\n>>> from models import *\n>>> b = BlogPost(title='Hello', slug='hello')\n>>> b.save()\n\n"
] |
[
6,
1
] |
[] |
[] |
[
"django",
"django_models",
"python"
] |
stackoverflow_0002538771_django_django_models_python.txt
|
Q:
python: image to 2-dimensional list
Is there a python lib that could make a 2-dimensional list of (R,G,B) data out of an image file?
A:
You might want to take a look at the Python Imaging Library. It has the ability to be directly converted to a 2 by 2 by 3 numpy array:
from PIL import Image
import numpy
im = Image.open( filename )
data = numpy.asarray( im )
A:
Or ImageMagick at http://wiki.python.org/moin/ImageMagick
|
python: image to 2-dimensional list
|
Is there a python lib that could make a 2-dimensional list of (R,G,B) data out of an image file?
|
[
"You might want to take a look at the Python Imaging Library. It has the ability to be directly converted to a 2 by 2 by 3 numpy array:\nfrom PIL import Image\nimport numpy\nim = Image.open( filename )\ndata = numpy.asarray( im )\n\n",
"Or ImageMagick at http://wiki.python.org/moin/ImageMagick\n"
] |
[
12,
3
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002539002_python.txt
|
Q:
Lightweight Object->Database in Python
I am in need of a lightweight way to store dictionaries of data into a database. What I need is something that:
Creates a database table from a simple type description (int, float, datetime etc)
Takes a dictionary object and inserts it into the database (including handling datetime objects!)
If possible: Can handle basic references, so the dictionary can reference other tables
I would prefer something that doesn't do a lot of magic. I just need an easy way to setup and get data into an SQL database.
What would you suggest? There seems to be a lot of ORM software around, but I find it hard to evaluate them.
A:
SQLAlchemy's SQL expression layer can easily cover the first two requirements. If you also want reference handling then you'll need to use the ORM, but this might fail your lightweight requirement depending on your definition of lightweight.
A:
SQLAlchemy offers an ORM much like django, but does not require that you work within a web framework.
A:
From it's description, perhaps Axiom is a pythonic tool for this .
A:
Seeing as you have mentioned sql, python and orm in your tags, are you looking for Django? Of all the web frameworks I've tried, I like this one the best. You'd be looking at models, specifically. This could be too fancy for your needs, perhaps, but that shouldn't stop you looking at the code of Django itself and learning from it.
|
Lightweight Object->Database in Python
|
I am in need of a lightweight way to store dictionaries of data into a database. What I need is something that:
Creates a database table from a simple type description (int, float, datetime etc)
Takes a dictionary object and inserts it into the database (including handling datetime objects!)
If possible: Can handle basic references, so the dictionary can reference other tables
I would prefer something that doesn't do a lot of magic. I just need an easy way to setup and get data into an SQL database.
What would you suggest? There seems to be a lot of ORM software around, but I find it hard to evaluate them.
|
[
"SQLAlchemy's SQL expression layer can easily cover the first two requirements. If you also want reference handling then you'll need to use the ORM, but this might fail your lightweight requirement depending on your definition of lightweight.\n",
"SQLAlchemy offers an ORM much like django, but does not require that you work within a web framework.\n",
"From it's description, perhaps Axiom is a pythonic tool for this .\n",
"Seeing as you have mentioned sql, python and orm in your tags, are you looking for Django? Of all the web frameworks I've tried, I like this one the best. You'd be looking at models, specifically. This could be too fancy for your needs, perhaps, but that shouldn't stop you looking at the code of Django itself and learning from it.\n"
] |
[
4,
3,
1,
0
] |
[] |
[] |
[
"orm",
"python",
"sql"
] |
stackoverflow_0002539147_orm_python_sql.txt
|
Q:
What is the easiest way to ping/notify a .NET Windows Service?
What is the easiest way to ping/notify a .NET Windows Service? Do I have to use WCF for this? Or is there an easier way?
I would like to be able to wake up the service using a Python (or an Iron Python) script from anywhere.
Also is there a way I can be notified (by email) if that the service has stopped?
A:
There is a command line tool SC which can be used start stop and query the service.
I don't know if there is an easy way to use WMI from python but WMI provides the ability to control services remotely as well.
If you want to use .net use the ServiceController Class.
A:
If you want to go to the low level .NET socket stuff, you could use the framework's TcpListener class. See an involved tutorial here. To host it in a Windows Service, check out this article.
A:
I had to host a WCF in the windows service to allow it to be notified remotely. Just to keep deploying the solution as simple as possible. using the ServiceController would require the correct setup of permissions
|
What is the easiest way to ping/notify a .NET Windows Service?
|
What is the easiest way to ping/notify a .NET Windows Service? Do I have to use WCF for this? Or is there an easier way?
I would like to be able to wake up the service using a Python (or an Iron Python) script from anywhere.
Also is there a way I can be notified (by email) if that the service has stopped?
|
[
"\nThere is a command line tool SC which can be used start stop and query the service. \nI don't know if there is an easy way to use WMI from python but WMI provides the ability to control services remotely as well. \nIf you want to use .net use the ServiceController Class.\n\n",
"If you want to go to the low level .NET socket stuff, you could use the framework's TcpListener class. See an involved tutorial here. To host it in a Windows Service, check out this article.\n",
"I had to host a WCF in the windows service to allow it to be notified remotely. Just to keep deploying the solution as simple as possible. using the ServiceController would require the correct setup of permissions\n"
] |
[
1,
1,
0
] |
[] |
[] |
[
".net",
"ironpython",
"python",
"windows_services"
] |
stackoverflow_0002436927_.net_ironpython_python_windows_services.txt
|
Q:
django: grouping in an order_by query?
I want to allocate rankings to users, based on a points field.
Easy enough you'd think with an order_by query. But how do I deal with the situation where two users have the same number of points and need to share the same ranking? Should I use annotate to find users with the same number of points?
My current code, and a pseudocode description of what I'd like to do, are below.
top_users = User.objects.filter(problem_user=False).order_by('-points_total')
# Wrong - in pseudocode, this should be
# Get the highest points_total, find all the users with that points_total,
# if there is more than one user, set status to 'Joint first prize',
# otherwise set status to 'First prize'
top_users[0].status = "First prize"
if (top_users[1]):
top_users[1].status = "Second prize"
if (top_users[2]):
top_users[2].status = "Third prize"
if (top_users[3]):
top_users[3:].status = "Highly commended"
The code above doesn't deal with the situation where two users have the same number of points and need to share second prize. I guess I need to create a query that looks for unique values of points_total, and does some kind of nested ranking?
It also doesn't cope with the fact that sometimes there are fewer than 4 users - does anyone know how I can do (in pseudocode) 'if top_users[1] is not null...' in Python?
A:
I'd just use itertools.groupby. Something like:
top_users = [(k, list(g)) for k,g in groupby(top_users, key=lambda x: x.score))]
for u in top_users[0][1]:
u.status = 'First prize'
for u in top_users[1][1]:
u.status = 'Second prize'
for u in top_users[2][1]:
u.status = 'Third prize'
for score, users in top_users[3:]:
for u in users:
u.status = 'Highly recommended'
Or even better, use itertools.count instead of the 4 loops:
top_users = [(k, list(g)) for k,g in groupby(top_users, key=lambda x: x.score))]
for c, (score, group) in zip(count(0), top_users):
if c == 0:
prize = 'First prize'
elif c == 1:
prize = 'Second prize'
elif c == 2:
prize = 'Third prize'
else:
prize = 'Highly recommended'
map(lambda x: setattr(x, 'status', prize), group)
And the last refinement, maybe keep a prize list instead of the if statements.
top_users = [(k, list(g)) for k,g in groupby(top_users, key=lambda x: x.score))]
prize_list = ['First prize', 'Second prize', 'Third prize', 'Highly recommended']
for c, (score, group) in zip(count(0), top_users):
prize = prize_list[c] if c < len(prize_list) else prize_list[-1]
map(lambda x: setattr(x, 'status', prize), group)
The caveat of this approach is that you're not doing the grouping in the database, but instead you'd be doing it in memory. This may be a problem if there are a lot of users. See How to query as GROUP BY in django? for some guidance on how to do this in the database.
A:
Quick & untested code, hopefully you get the idea:
top_users = User.objects.filter(...)
prizes = ['First prize', 'Second', 'Third', ...]
prize = 0
previous_points = None
try:
for user in top_users:
if user.points_total < previous_points:
# always skipped in first iteration
prize += 1
user.status = prizes[prize] # raise IndexError when out of prizes
previous_points = user.points_total
except IndexError:
pass
More elegant solutions welcomed!
|
django: grouping in an order_by query?
|
I want to allocate rankings to users, based on a points field.
Easy enough you'd think with an order_by query. But how do I deal with the situation where two users have the same number of points and need to share the same ranking? Should I use annotate to find users with the same number of points?
My current code, and a pseudocode description of what I'd like to do, are below.
top_users = User.objects.filter(problem_user=False).order_by('-points_total')
# Wrong - in pseudocode, this should be
# Get the highest points_total, find all the users with that points_total,
# if there is more than one user, set status to 'Joint first prize',
# otherwise set status to 'First prize'
top_users[0].status = "First prize"
if (top_users[1]):
top_users[1].status = "Second prize"
if (top_users[2]):
top_users[2].status = "Third prize"
if (top_users[3]):
top_users[3:].status = "Highly commended"
The code above doesn't deal with the situation where two users have the same number of points and need to share second prize. I guess I need to create a query that looks for unique values of points_total, and does some kind of nested ranking?
It also doesn't cope with the fact that sometimes there are fewer than 4 users - does anyone know how I can do (in pseudocode) 'if top_users[1] is not null...' in Python?
|
[
"I'd just use itertools.groupby. Something like:\ntop_users = [(k, list(g)) for k,g in groupby(top_users, key=lambda x: x.score))]\nfor u in top_users[0][1]:\n u.status = 'First prize'\nfor u in top_users[1][1]:\n u.status = 'Second prize'\nfor u in top_users[2][1]:\n u.status = 'Third prize'\nfor score, users in top_users[3:]:\n for u in users:\n u.status = 'Highly recommended'\n\nOr even better, use itertools.count instead of the 4 loops:\ntop_users = [(k, list(g)) for k,g in groupby(top_users, key=lambda x: x.score))]\nfor c, (score, group) in zip(count(0), top_users):\n if c == 0:\n prize = 'First prize'\n elif c == 1:\n prize = 'Second prize'\n elif c == 2:\n prize = 'Third prize'\n else:\n prize = 'Highly recommended'\n map(lambda x: setattr(x, 'status', prize), group)\n\nAnd the last refinement, maybe keep a prize list instead of the if statements.\ntop_users = [(k, list(g)) for k,g in groupby(top_users, key=lambda x: x.score))]\nprize_list = ['First prize', 'Second prize', 'Third prize', 'Highly recommended']\nfor c, (score, group) in zip(count(0), top_users):\n prize = prize_list[c] if c < len(prize_list) else prize_list[-1]\n map(lambda x: setattr(x, 'status', prize), group)\n\nThe caveat of this approach is that you're not doing the grouping in the database, but instead you'd be doing it in memory. This may be a problem if there are a lot of users. See How to query as GROUP BY in django? for some guidance on how to do this in the database.\n",
"Quick & untested code, hopefully you get the idea:\ntop_users = User.objects.filter(...)\nprizes = ['First prize', 'Second', 'Third', ...]\nprize = 0\nprevious_points = None\ntry:\n for user in top_users:\n if user.points_total < previous_points:\n # always skipped in first iteration\n prize += 1\n user.status = prizes[prize] # raise IndexError when out of prizes\n previous_points = user.points_total\nexcept IndexError:\n pass\n\nMore elegant solutions welcomed!\n"
] |
[
1,
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002538096_django_python.txt
|
Q:
Sunrise / set calculations
I'm trying to calculate the sunset / rise times using python based on the link provided below.
My results done through excel and python do not match the real values. Any ideas on what I could be doing wrong?
My Excel sheet can be found under .. http://transpotools.com/sun_time.xls
# Created on 2010-03-28
# @author: dassouki
# @source: [http://williams.best.vwh.net/sunrise_sunset_algorithm.htm][2]
# @summary: this is based on the Nautical Almanac Office, United States Naval
# Observatory.
import math, sys
class TimeOfDay(object):
def calculate_time(self, in_day, in_month, in_year,
lat, long, is_rise, utc_time_zone):
# is_rise is a bool when it's true it indicates rise,
# and if it's false it indicates setting time
#set Zenith
zenith = 96
# offical = 90 degrees 50'
# civil = 96 degrees
# nautical = 102 degrees
# astronomical = 108 degrees
#1- calculate the day of year
n1 = math.floor( 275 * in_month / 9 )
n2 = math.floor( ( in_month + 9 ) / 12 )
n3 = ( 1 + math.floor( in_year - 4 * math.floor( in_year / 4 ) + 2 ) / 3 )
new_day = n1 - ( n2 * n3 ) + in_day - 30
print "new_day ", new_day
#2- calculate rising / setting time
if is_rise:
rise_or_set_time = new_day + ( ( 6 - ( long / 15 ) ) / 24 )
else:
rise_or_set_time = new_day + ( ( 18 - ( long/ 15 ) ) / 24 )
print "rise / set", rise_or_set_time
#3- calculate sun mean anamoly
sun_mean_anomaly = ( 0.9856 * rise_or_set_time ) - 3.289
print "sun mean anomaly", sun_mean_anomaly
#4 calculate true longitude
true_long = ( sun_mean_anomaly +
( 1.916 * math.sin( math.radians( sun_mean_anomaly ) ) ) +
( 0.020 * math.sin( 2 * math.radians( sun_mean_anomaly ) ) ) +
282.634 )
print "true long ", true_long
# make sure true_long is within 0, 360
if true_long < 0:
true_long = true_long + 360
elif true_long > 360:
true_long = true_long - 360
else:
true_long
print "true long (360 if) ", true_long
#5 calculate s_r_a (sun_right_ascenstion)
s_r_a = math.degrees( math.atan( 0.91764 * math.tan( math.radians( true_long ) ) ) )
print "s_r_a is ", s_r_a
#make sure it's between 0 and 360
if s_r_a < 0:
s_r_a = s_r_a + 360
elif true_long > 360:
s_r_a = s_r_a - 360
else:
s_r_a
print "s_r_a (modified) is ", s_r_a
# s_r_a has to be in the same Quadrant as true_long
true_long_quad = ( math.floor( true_long / 90 ) ) * 90
s_r_a_quad = ( math.floor( s_r_a / 90 ) ) * 90
s_r_a = s_r_a + ( true_long_quad - s_r_a_quad )
print "s_r_a (quadrant) is ", s_r_a
# convert s_r_a to hours
s_r_a = s_r_a / 15
print "s_r_a (to hours) is ", s_r_a
#6- calculate sun diclanation in terms of cos and sin
sin_declanation = 0.39782 * math.sin( math.radians ( true_long ) )
cos_declanation = math.cos( math.asin( sin_declanation ) )
print " sin/cos declanations ", sin_declanation, ", ", cos_declanation
# sun local hour
cos_hour = ( math.cos( math.radians( zenith ) ) -
( sin_declanation * math.sin( math.radians ( lat ) ) ) /
( cos_declanation * math.cos( math.radians ( lat ) ) ) )
print "cos_hour ", cos_hour
# extreme north / south
if cos_hour > 1:
print "Sun Never Rises at this location on this date, exiting"
# sys.exit()
elif cos_hour < -1:
print "Sun Never Sets at this location on this date, exiting"
# sys.exit()
print "cos_hour (2)", cos_hour
#7- sun/set local time calculations
if is_rise:
sun_local_hour = ( 360 - math.degrees(math.acos( cos_hour ) ) ) / 15
else:
sun_local_hour = math.degrees( math.acos( cos_hour ) ) / 15
print "sun local hour ", sun_local_hour
sun_event_time = sun_local_hour + s_r_a - ( 0.06571 *
rise_or_set_time ) - 6.622
print "sun event time ", sun_event_time
#final result
time_in_utc = sun_event_time - ( long / 15 ) + utc_time_zone
return time_in_utc
#test through main
def main():
print "Time of day App "
# test: fredericton, NB
# answer: 7:34 am
long = 66.6
lat = -45.9
utc_time = -4
d = 3
m = 3
y = 2010
is_rise = True
tod = TimeOfDay()
print "TOD is ", tod.calculate_time(d, m, y, lat, long, is_rise, utc_time)
if __name__ == "__main__":
main()
A:
You could use ephem python module:
#!/usr/bin/env python
import datetime
import ephem # to install, type$ pip install pyephem
def calculate_time(d, m, y, lat, long, is_rise, utc_time):
o = ephem.Observer()
o.lat, o.long, o.date = lat, long, datetime.date(y, m, d)
sun = ephem.Sun(o)
next_event = o.next_rising if is_rise else o.next_setting
return ephem.Date(next_event(sun, start=o.date) + utc_time*ephem.hour
).datetime().strftime('%H:%M')
Example:
for town, kwarg in { "Fredericton": dict(d=3, m=3, y=2010,
lat='45.959045', long='-66.640509',
is_rise=True,
utc_time=20),
"Beijing": dict(d=29, m=3, y=2010,
lat='39:55', long='116:23',
is_rise=True,
utc_time=+8),
"Berlin": dict(d=4, m=4, y=2010,
lat='52:30:2', long='13:23:56',
is_rise=False,
utc_time=+2) ,
"Moscow": dict(d=4, m=4, y=2010,
lat='55.753975', long='37.625427',
is_rise=True,
utc_time=4) }.items():
print town, calculate_time(**kwarg)
Output:
Beijing 06:02
Berlin 19:45
Moscow 06:53
Fredericton 07:01
A:
Why all the calls to radians and degrees? I thought the input data was already in decimal degrees.
I get a result of 7:37am if I:
strip out all of the calls to radians and degrees
correct the lat / long to: 45.9 and -66.6 respectively
correct time_in_utc to fall within 0 and 24.
Edit:
As J. F. Sebastian points out, the answer for the sunrise time at this location according to the spreadsheet linked in the question and the answer provided by using the Observer class of the ephem are in the region of 07:01-07:02.
I stopped looking for errors in dassouki's implementation of the US Naval Observatory's algorithm once I got a figure in the right ballpark (07:34 in the comments in the implementation).
Looking into it, this algorithm makes some simplifications and there is variation about what constitutes 'sunrise', some of this is discussed here. However, in my opinion from what I've recently learnt on this matter, these variations should only lead to a difference of a few minutes in sunrise time, rather than over half an hour.
A:
I suspect this has something to do with not actually performing floating point division. In python if a and b are both integers, a / b is also an integer:
$ python
>>> 1 / 2
0
Your options are either to coerce to float one of your arguments (that is, instead of a/b do a float(a) / b) or to make sure the '/' behaves properly in a Python 3K way:
$ python
>>> from __future__ import division
>>> 1 / 2
0.5
So if you stick that import statement at the top of your file, it may fix your problem. Now / will always produce a float, and to get the old behaviour you can use // instead.
|
Sunrise / set calculations
|
I'm trying to calculate the sunset / rise times using python based on the link provided below.
My results done through excel and python do not match the real values. Any ideas on what I could be doing wrong?
My Excel sheet can be found under .. http://transpotools.com/sun_time.xls
# Created on 2010-03-28
# @author: dassouki
# @source: [http://williams.best.vwh.net/sunrise_sunset_algorithm.htm][2]
# @summary: this is based on the Nautical Almanac Office, United States Naval
# Observatory.
import math, sys
class TimeOfDay(object):
def calculate_time(self, in_day, in_month, in_year,
lat, long, is_rise, utc_time_zone):
# is_rise is a bool when it's true it indicates rise,
# and if it's false it indicates setting time
#set Zenith
zenith = 96
# offical = 90 degrees 50'
# civil = 96 degrees
# nautical = 102 degrees
# astronomical = 108 degrees
#1- calculate the day of year
n1 = math.floor( 275 * in_month / 9 )
n2 = math.floor( ( in_month + 9 ) / 12 )
n3 = ( 1 + math.floor( in_year - 4 * math.floor( in_year / 4 ) + 2 ) / 3 )
new_day = n1 - ( n2 * n3 ) + in_day - 30
print "new_day ", new_day
#2- calculate rising / setting time
if is_rise:
rise_or_set_time = new_day + ( ( 6 - ( long / 15 ) ) / 24 )
else:
rise_or_set_time = new_day + ( ( 18 - ( long/ 15 ) ) / 24 )
print "rise / set", rise_or_set_time
#3- calculate sun mean anamoly
sun_mean_anomaly = ( 0.9856 * rise_or_set_time ) - 3.289
print "sun mean anomaly", sun_mean_anomaly
#4 calculate true longitude
true_long = ( sun_mean_anomaly +
( 1.916 * math.sin( math.radians( sun_mean_anomaly ) ) ) +
( 0.020 * math.sin( 2 * math.radians( sun_mean_anomaly ) ) ) +
282.634 )
print "true long ", true_long
# make sure true_long is within 0, 360
if true_long < 0:
true_long = true_long + 360
elif true_long > 360:
true_long = true_long - 360
else:
true_long
print "true long (360 if) ", true_long
#5 calculate s_r_a (sun_right_ascenstion)
s_r_a = math.degrees( math.atan( 0.91764 * math.tan( math.radians( true_long ) ) ) )
print "s_r_a is ", s_r_a
#make sure it's between 0 and 360
if s_r_a < 0:
s_r_a = s_r_a + 360
elif true_long > 360:
s_r_a = s_r_a - 360
else:
s_r_a
print "s_r_a (modified) is ", s_r_a
# s_r_a has to be in the same Quadrant as true_long
true_long_quad = ( math.floor( true_long / 90 ) ) * 90
s_r_a_quad = ( math.floor( s_r_a / 90 ) ) * 90
s_r_a = s_r_a + ( true_long_quad - s_r_a_quad )
print "s_r_a (quadrant) is ", s_r_a
# convert s_r_a to hours
s_r_a = s_r_a / 15
print "s_r_a (to hours) is ", s_r_a
#6- calculate sun diclanation in terms of cos and sin
sin_declanation = 0.39782 * math.sin( math.radians ( true_long ) )
cos_declanation = math.cos( math.asin( sin_declanation ) )
print " sin/cos declanations ", sin_declanation, ", ", cos_declanation
# sun local hour
cos_hour = ( math.cos( math.radians( zenith ) ) -
( sin_declanation * math.sin( math.radians ( lat ) ) ) /
( cos_declanation * math.cos( math.radians ( lat ) ) ) )
print "cos_hour ", cos_hour
# extreme north / south
if cos_hour > 1:
print "Sun Never Rises at this location on this date, exiting"
# sys.exit()
elif cos_hour < -1:
print "Sun Never Sets at this location on this date, exiting"
# sys.exit()
print "cos_hour (2)", cos_hour
#7- sun/set local time calculations
if is_rise:
sun_local_hour = ( 360 - math.degrees(math.acos( cos_hour ) ) ) / 15
else:
sun_local_hour = math.degrees( math.acos( cos_hour ) ) / 15
print "sun local hour ", sun_local_hour
sun_event_time = sun_local_hour + s_r_a - ( 0.06571 *
rise_or_set_time ) - 6.622
print "sun event time ", sun_event_time
#final result
time_in_utc = sun_event_time - ( long / 15 ) + utc_time_zone
return time_in_utc
#test through main
def main():
print "Time of day App "
# test: fredericton, NB
# answer: 7:34 am
long = 66.6
lat = -45.9
utc_time = -4
d = 3
m = 3
y = 2010
is_rise = True
tod = TimeOfDay()
print "TOD is ", tod.calculate_time(d, m, y, lat, long, is_rise, utc_time)
if __name__ == "__main__":
main()
|
[
"You could use ephem python module:\n#!/usr/bin/env python\nimport datetime\nimport ephem # to install, type$ pip install pyephem\n\ndef calculate_time(d, m, y, lat, long, is_rise, utc_time):\n o = ephem.Observer()\n o.lat, o.long, o.date = lat, long, datetime.date(y, m, d)\n sun = ephem.Sun(o)\n next_event = o.next_rising if is_rise else o.next_setting\n return ephem.Date(next_event(sun, start=o.date) + utc_time*ephem.hour\n ).datetime().strftime('%H:%M')\n\nExample:\nfor town, kwarg in { \"Fredericton\": dict(d=3, m=3, y=2010,\n lat='45.959045', long='-66.640509',\n is_rise=True,\n utc_time=20),\n\n \"Beijing\": dict(d=29, m=3, y=2010,\n lat='39:55', long='116:23',\n is_rise=True,\n utc_time=+8),\n\n \"Berlin\": dict(d=4, m=4, y=2010,\n lat='52:30:2', long='13:23:56',\n is_rise=False,\n utc_time=+2) ,\n\n \"Moscow\": dict(d=4, m=4, y=2010,\n lat='55.753975', long='37.625427',\n is_rise=True,\n utc_time=4) }.items():\n print town, calculate_time(**kwarg)\n\nOutput:\nBeijing 06:02\nBerlin 19:45\nMoscow 06:53\nFredericton 07:01\n\n",
"Why all the calls to radians and degrees? I thought the input data was already in decimal degrees.\nI get a result of 7:37am if I:\n\nstrip out all of the calls to radians and degrees\ncorrect the lat / long to: 45.9 and -66.6 respectively\ncorrect time_in_utc to fall within 0 and 24.\n\n\nEdit:\nAs J. F. Sebastian points out, the answer for the sunrise time at this location according to the spreadsheet linked in the question and the answer provided by using the Observer class of the ephem are in the region of 07:01-07:02.\nI stopped looking for errors in dassouki's implementation of the US Naval Observatory's algorithm once I got a figure in the right ballpark (07:34 in the comments in the implementation).\nLooking into it, this algorithm makes some simplifications and there is variation about what constitutes 'sunrise', some of this is discussed here. However, in my opinion from what I've recently learnt on this matter, these variations should only lead to a difference of a few minutes in sunrise time, rather than over half an hour.\n",
"I suspect this has something to do with not actually performing floating point division. In python if a and b are both integers, a / b is also an integer:\n $ python\n >>> 1 / 2\n 0\n\nYour options are either to coerce to float one of your arguments (that is, instead of a/b do a float(a) / b) or to make sure the '/' behaves properly in a Python 3K way:\n $ python\n >>> from __future__ import division\n >>> 1 / 2\n 0.5\n\nSo if you stick that import statement at the top of your file, it may fix your problem. Now / will always produce a float, and to get the old behaviour you can use // instead.\n"
] |
[
10,
3,
1
] |
[] |
[] |
[
"astronomy",
"math",
"python"
] |
stackoverflow_0002538190_astronomy_math_python.txt
|
Q:
Drawing a clamped uniform cubic B-spline using Cairo
I have a bunch of coordinates which are the control points of a clamped uniform cubic B-spline on the 2D plane. I would like to draw this curve using Cairo calls (in Python, using Cairo's Python bindings), but as far as I know, Cairo supports Bézier curves only. I also know that the segments of a B-spline between two control points can be drawn using Bézier curves, but I can't find the exact formulae anywhere. Given the coordinates of the control points, how can I derive the control points of the corresponding Bézier curves? Is there any efficient algorithm for that?
A:
Okay, so I searched a lot using Google and I think I came up with a reasonable solution that is suitable for my purposes. I'm posting it here - maybe it will be useful to someone else as well.
First, let's start with a simple Point class:
from collections import namedtuple
class Point(namedtuple("Point", "x y")):
__slots__ = ()
def interpolate(self, other, ratio = 0.5):
return Point(x = self.x * (1.0-ratio) + other.x * float(ratio), \
y = self.y * (1.0-ratio) + other.y * float(ratio))
A cubic B-spline is nothing more than a collection of Point objects:
class CubicBSpline(object):
__slots__ = ("points", )
def __init__(self, points):
self.points = [Point(*coords) for coords in points]
Now, assume that we have an open uniform cubic B-spline instead of a clamped one. Four consecutive control points of a cubic B-spline define a single Bézier segment, so control points 0 to 3 define the first Bézier segment, control points 1 to 4 define the second segment and so on. The control points of the Bézier spline can be determined by linearly interpolating between the control points of the B-spline in an appropriate way. Let A, B, C and D be the four control points of the B-spline. Calculate the following auxiliary points:
Find the point which divides the A-B line in a ratio of 2:1, let it be A'.
Find the point which divides the C-D line in a ratio of 1:2, let it be D'.
Divide the B-C line into three equal parts, let the two points be F and G.
Find the point halfway between A' and F, this will be E.
Find the point halfway between G and D', this will be H.
A Bézier curve from E to H with control points F and G is equivalent to an open B-spline between points A, B, C and D. See sections 1-5 of this excellent document. By the way, the above method is called Böhm's algorithm, and it is much more complicated if formulated in a proper mathematic way that accounts for non-uniform or non-cubic B-splines as well.
We have to repeat the above procedure for each group of 4 consecutive points of the B-spline, so in the end we will need the 1:2 and 2:1 division points between almost any consecutive control point pairs. This is what the following BSplineDrawer class does before drawing the curves:
class BSplineDrawer(object):
def __init__(self, context):
self.ctx = context
def draw(self, bspline):
pairs = zip(bspline.points[:-1], bspline.points[1:])
one_thirds = [p1.interpolate(p2, 1/3.) for p1, p2 in pairs]
two_thirds = [p2.interpolate(p1, 1/3.) for p1, p2 in pairs]
coords = [None] * 6
for i in xrange(len(bspline.points) - 3):
start = two_thirds[i].interpolate(one_thirds[i+1])
coords[0:2] = one_thirds[i+1]
coords[2:4] = two_thirds[i+1]
coords[4:6] = two_thirds[i+1].interpolate(one_thirds[i+2])
self.context.move_to(*start)
self.context.curve_to(*coords)
self.context.stroke()
Finally, if we want to draw clamped B-splines instead of open B-splines, we simply have to repeat both endpoints of the clamped B-spline three more times:
class CubicBSpline(object):
[...]
def clamped(self):
new_points = [self.points[0]] * 3 + self.points + [self.points[-1]] * 3
return CubicBSpline(new_points)
Finally, this is how the code should be used:
import cairo
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 600, 400)
ctx = cairo.Context(surface)
points = [(100,100), (200,100), (200,200), (100,200), (100,400), (300,400)]
spline = CubicBSpline(points).clamped()
ctx.set_source_rgb(0., 0., 1.)
ctx.set_line_width(5)
BSplineDrawer(ctx).draw(spline)
A:
Does Converting B-spline curve to Bezier spline curve help?
|
Drawing a clamped uniform cubic B-spline using Cairo
|
I have a bunch of coordinates which are the control points of a clamped uniform cubic B-spline on the 2D plane. I would like to draw this curve using Cairo calls (in Python, using Cairo's Python bindings), but as far as I know, Cairo supports Bézier curves only. I also know that the segments of a B-spline between two control points can be drawn using Bézier curves, but I can't find the exact formulae anywhere. Given the coordinates of the control points, how can I derive the control points of the corresponding Bézier curves? Is there any efficient algorithm for that?
|
[
"Okay, so I searched a lot using Google and I think I came up with a reasonable solution that is suitable for my purposes. I'm posting it here - maybe it will be useful to someone else as well.\nFirst, let's start with a simple Point class:\nfrom collections import namedtuple\n\nclass Point(namedtuple(\"Point\", \"x y\")):\n __slots__ = ()\n\n def interpolate(self, other, ratio = 0.5):\n return Point(x = self.x * (1.0-ratio) + other.x * float(ratio), \\\n y = self.y * (1.0-ratio) + other.y * float(ratio))\n\nA cubic B-spline is nothing more than a collection of Point objects:\nclass CubicBSpline(object):\n __slots__ = (\"points\", )\n\n def __init__(self, points):\n self.points = [Point(*coords) for coords in points]\n\nNow, assume that we have an open uniform cubic B-spline instead of a clamped one. Four consecutive control points of a cubic B-spline define a single Bézier segment, so control points 0 to 3 define the first Bézier segment, control points 1 to 4 define the second segment and so on. The control points of the Bézier spline can be determined by linearly interpolating between the control points of the B-spline in an appropriate way. Let A, B, C and D be the four control points of the B-spline. Calculate the following auxiliary points:\n\nFind the point which divides the A-B line in a ratio of 2:1, let it be A'.\nFind the point which divides the C-D line in a ratio of 1:2, let it be D'.\nDivide the B-C line into three equal parts, let the two points be F and G.\nFind the point halfway between A' and F, this will be E.\nFind the point halfway between G and D', this will be H.\n\nA Bézier curve from E to H with control points F and G is equivalent to an open B-spline between points A, B, C and D. See sections 1-5 of this excellent document. By the way, the above method is called Böhm's algorithm, and it is much more complicated if formulated in a proper mathematic way that accounts for non-uniform or non-cubic B-splines as well.\nWe have to repeat the above procedure for each group of 4 consecutive points of the B-spline, so in the end we will need the 1:2 and 2:1 division points between almost any consecutive control point pairs. This is what the following BSplineDrawer class does before drawing the curves:\nclass BSplineDrawer(object):\n def __init__(self, context):\n self.ctx = context\n\n def draw(self, bspline):\n pairs = zip(bspline.points[:-1], bspline.points[1:])\n one_thirds = [p1.interpolate(p2, 1/3.) for p1, p2 in pairs]\n two_thirds = [p2.interpolate(p1, 1/3.) for p1, p2 in pairs]\n\n coords = [None] * 6\n for i in xrange(len(bspline.points) - 3):\n start = two_thirds[i].interpolate(one_thirds[i+1])\n coords[0:2] = one_thirds[i+1]\n coords[2:4] = two_thirds[i+1]\n coords[4:6] = two_thirds[i+1].interpolate(one_thirds[i+2])\n\n self.context.move_to(*start)\n self.context.curve_to(*coords)\n self.context.stroke()\n\nFinally, if we want to draw clamped B-splines instead of open B-splines, we simply have to repeat both endpoints of the clamped B-spline three more times:\nclass CubicBSpline(object):\n [...]\n def clamped(self):\n new_points = [self.points[0]] * 3 + self.points + [self.points[-1]] * 3\n return CubicBSpline(new_points)\n\nFinally, this is how the code should be used:\nimport cairo\n\nsurface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 600, 400)\nctx = cairo.Context(surface)\n\npoints = [(100,100), (200,100), (200,200), (100,200), (100,400), (300,400)]\nspline = CubicBSpline(points).clamped()\n\nctx.set_source_rgb(0., 0., 1.)\nctx.set_line_width(5)\nBSplineDrawer(ctx).draw(spline)\n\n",
"Does Converting B-spline curve to Bezier spline curve help?\n"
] |
[
7,
2
] |
[] |
[] |
[
"bezier",
"cairo",
"python"
] |
stackoverflow_0002534786_bezier_cairo_python.txt
|
Q:
Return current 11-digit timestamp in Python
How can I return the current time of the local machine?
A:
Do you mean this: time.time()?
From the docs:
Return the time as a floating point number expressed in seconds since the epoch, in UTC
>>> import time
>>> time.time()
1269884900.480978
>>>
|
Return current 11-digit timestamp in Python
|
How can I return the current time of the local machine?
|
[
"Do you mean this: time.time()?\nFrom the docs:\nReturn the time as a floating point number expressed in seconds since the epoch, in UTC\n>>> import time\n>>> time.time()\n1269884900.480978\n>>> \n\n"
] |
[
41
] |
[] |
[] |
[
"python",
"timestamp"
] |
stackoverflow_0002540043_python_timestamp.txt
|
Q:
Suppose I have a dictionary. How do I strip out all the keys? Edit: This is a nested dictionary
And have a big blob of values, with a space in between?
Edit: What if I have nested dictionaries? The current solutions work if my values are all strings. But what if my values are nested dictionaries?
A:
Assuming the values are already strings:
>>> d = { 1 : 'foo', 2 : 'bar' }
>>> ' '.join(d.values())
'foo bar'
If not, you can try to convert them to strings using for example str:
>>> d = { 1 : 2, 3: 4 }
>>> ' '.join(str(v) for v in d.values())
'2 4'
A:
>>> a = {1: 'hello', 2: 'world'}
>>> a.values()
['hello', 'world']
>>> ' '.join(a.values())
'hello world'
A:
if you want the values from a dictionary that contains dictionaries as values, try something like this:
In [1]: from itertools import chain
In [2]: d = {'A': {1: 'pants', 2: 'trowsers'}, 'B': {'1': 'spam', '2': 'eggs'}}
In [3]: values = ' '.join(chain.from_iterable(dic.itervalues() for dic in d.itervalues()))
In [4]: values
Out[4]: 'pants trowsers spam eggs'
|
Suppose I have a dictionary. How do I strip out all the keys? Edit: This is a nested dictionary
|
And have a big blob of values, with a space in between?
Edit: What if I have nested dictionaries? The current solutions work if my values are all strings. But what if my values are nested dictionaries?
|
[
"Assuming the values are already strings:\n>>> d = { 1 : 'foo', 2 : 'bar' }\n>>> ' '.join(d.values())\n'foo bar'\n\nIf not, you can try to convert them to strings using for example str:\n>>> d = { 1 : 2, 3: 4 }\n>>> ' '.join(str(v) for v in d.values())\n'2 4'\n\n",
">>> a = {1: 'hello', 2: 'world'}\n>>> a.values()\n['hello', 'world']\n>>> ' '.join(a.values())\n'hello world'\n\n",
"if you want the values from a dictionary that contains dictionaries as values, try something like this:\nIn [1]: from itertools import chain\nIn [2]: d = {'A': {1: 'pants', 2: 'trowsers'}, 'B': {'1': 'spam', '2': 'eggs'}} \nIn [3]: values = ' '.join(chain.from_iterable(dic.itervalues() for dic in d.itervalues()))\nIn [4]: values\nOut[4]: 'pants trowsers spam eggs'\n\n"
] |
[
2,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002536336_python.txt
|
Q:
Timezones and the DateTimeField - Django
I'm trying to implement a "time ago" feature, for the displaying of items on a site.
As I'm caching the pages I wish to use javascript in order to render the "time ago".
Javascript knows local time and problably the Timezone of the local machine so I could play with that, but that would require to hard code the server's timezone.
Therefore I'm trying to figure out a simple way to pass a ISO 8601 timestamp, in GMT time. Is there any simple and straight forward way for doing this?
Help would be much appreciated! =)
A:
The python datetime objects has a method for outputting an ISO 8601 timestamp here.
That page also has information on timezone manipulation. The timedelta object should also be useful for you.
A:
I wouldn't use javascript to do this personally. Yes it has their local time, but it also means that the user will then see the timestamps will change when the javascript finally renders on the page.
That is, assuming you're properly not executing your javascript until the page is loaded.
|
Timezones and the DateTimeField - Django
|
I'm trying to implement a "time ago" feature, for the displaying of items on a site.
As I'm caching the pages I wish to use javascript in order to render the "time ago".
Javascript knows local time and problably the Timezone of the local machine so I could play with that, but that would require to hard code the server's timezone.
Therefore I'm trying to figure out a simple way to pass a ISO 8601 timestamp, in GMT time. Is there any simple and straight forward way for doing this?
Help would be much appreciated! =)
|
[
"The python datetime objects has a method for outputting an ISO 8601 timestamp here.\nThat page also has information on timezone manipulation. The timedelta object should also be useful for you.\n",
"I wouldn't use javascript to do this personally. Yes it has their local time, but it also means that the user will then see the timestamps will change when the javascript finally renders on the page.\nThat is, assuming you're properly not executing your javascript until the page is loaded.\n"
] |
[
2,
0
] |
[] |
[] |
[
"django",
"iso8601",
"javascript",
"python",
"timezone"
] |
stackoverflow_0002540298_django_iso8601_javascript_python_timezone.txt
|
Q:
Python NLTK figure out tense
I have a web application that translates sentences into English; the user chooses options from drop downs that basically provide the context. Now I want to turn the word and the context into an English sentence.
One case is that the user chooses 'who' and 'when', 'who' could be: I, you, you two, he, she, we, they. 'When' could be: 'did it', 'will do it', 'might do it', 'does it', 'do it!'. So in the end I would have the word that the user put in, as well as who and when. ex. 'sing', 'you', 'did it' would get the English sentence "You sang".
Another case is with transitive verbs like "chase", there would still be 'who' and 'when' but also another option of 'done to' which is basically another 'who' menu. ex. 'chase', 'I', 'will do it', 'they' would get the English sentence "I am going to chase them".
I'm new to the NLTK so I don't really know where to start with this problem. Can anyone point me in the general direction of where to start with this?
A:
NLTK is a fairly large project containing a lot of useful tools. I'd suggest starting out by reading the NLTK Book, which is very well done. You can probably skim the first few chapters.
The stuff you're looking for is in chapters 7 and beyond.
|
Python NLTK figure out tense
|
I have a web application that translates sentences into English; the user chooses options from drop downs that basically provide the context. Now I want to turn the word and the context into an English sentence.
One case is that the user chooses 'who' and 'when', 'who' could be: I, you, you two, he, she, we, they. 'When' could be: 'did it', 'will do it', 'might do it', 'does it', 'do it!'. So in the end I would have the word that the user put in, as well as who and when. ex. 'sing', 'you', 'did it' would get the English sentence "You sang".
Another case is with transitive verbs like "chase", there would still be 'who' and 'when' but also another option of 'done to' which is basically another 'who' menu. ex. 'chase', 'I', 'will do it', 'they' would get the English sentence "I am going to chase them".
I'm new to the NLTK so I don't really know where to start with this problem. Can anyone point me in the general direction of where to start with this?
|
[
"NLTK is a fairly large project containing a lot of useful tools. I'd suggest starting out by reading the NLTK Book, which is very well done. You can probably skim the first few chapters.\nThe stuff you're looking for is in chapters 7 and beyond.\n"
] |
[
3
] |
[] |
[] |
[
"nltk",
"python"
] |
stackoverflow_0002539782_nltk_python.txt
|
Q:
Python mechanize to follow image links?
mechanize's Browser class is great and it's follow_link() function is great too. But what to do with this kind of links:
<a href="http://example.com"><img src="…"></a>
Is there any way to follow such links? The text attribute of this type of links is simply '[IMG]', so AFAIK, there is no way to differentiate such links. Any help would be appreciated.
A:
To follow such links you need to add nr parameter to follow_link() method.
Try this:
import mechanize
br = mechanize.Browser()
br.open('http://www.systempuntoout.com')
for link in br.links():
print(link)
br.follow_link(text='[IMG]', nr=0)
print br
>>><Browser visiting http://www.systempuntoout.com/quiz>
br.back()
br.follow_link(text='[IMG]', nr=1)
>>><Browser visiting http://www.systempuntoout.com/about>
|
Python mechanize to follow image links?
|
mechanize's Browser class is great and it's follow_link() function is great too. But what to do with this kind of links:
<a href="http://example.com"><img src="…"></a>
Is there any way to follow such links? The text attribute of this type of links is simply '[IMG]', so AFAIK, there is no way to differentiate such links. Any help would be appreciated.
|
[
"To follow such links you need to add nr parameter to follow_link() method.\nTry this:\nimport mechanize\nbr = mechanize.Browser()\nbr.open('http://www.systempuntoout.com')\nfor link in br.links():\n print(link)\nbr.follow_link(text='[IMG]', nr=0)\nprint br\n>>><Browser visiting http://www.systempuntoout.com/quiz>\nbr.back()\nbr.follow_link(text='[IMG]', nr=1)\n>>><Browser visiting http://www.systempuntoout.com/about>\n\n"
] |
[
5
] |
[] |
[] |
[
"hyperlink",
"image",
"mechanize",
"python"
] |
stackoverflow_0002539498_hyperlink_image_mechanize_python.txt
|
Q:
How to URL encode this so I can pass it to Facebook Share?
This is the URL I want to share:
http://mydomain.com/#url=http://stackoverflow.com
Inside my site, I do this in Django so that everything will work:
http://mydomain.com/#url={{external|urlencode}}
However, when I pass it to Facebook Share, everything gets messed up.
http://www.facebook.com/sharer.php?u=<url to share>&t=<title of content>
I tried to urlencode the #url part, and also the full url, but it's not working, and my #url is not holding up when there are & and ? signs everywhere.
A:
I think the problem is, that you first urlencode the last part of url, which you then include into another url.
try use urllib for that:
import urllib
urllib.quote("http://mydomain.com/#url=http://stackoverflow.com")
or when you have to unquote something:
urllib.unquote("http%3A//mydomain.com/%23url%3Dhttp%3A//stackoverflow.com")
kind regards
|
How to URL encode this so I can pass it to Facebook Share?
|
This is the URL I want to share:
http://mydomain.com/#url=http://stackoverflow.com
Inside my site, I do this in Django so that everything will work:
http://mydomain.com/#url={{external|urlencode}}
However, when I pass it to Facebook Share, everything gets messed up.
http://www.facebook.com/sharer.php?u=<url to share>&t=<title of content>
I tried to urlencode the #url part, and also the full url, but it's not working, and my #url is not holding up when there are & and ? signs everywhere.
|
[
"I think the problem is, that you first urlencode the last part of url, which you then include into another url.\ntry use urllib for that:\nimport urllib\nurllib.quote(\"http://mydomain.com/#url=http://stackoverflow.com\")\n\nor when you have to unquote something:\nurllib.unquote(\"http%3A//mydomain.com/%23url%3Dhttp%3A//stackoverflow.com\")\n\nkind regards \n"
] |
[
0
] |
[] |
[] |
[
"django",
"encoding",
"html",
"javascript",
"python"
] |
stackoverflow_0002540944_django_encoding_html_javascript_python.txt
|
Q:
Return template as string - Django
I'm still not sure this is the correct way to go about this, maybe not, but I'll ask anyway. I'd like to re-write wordpress (justification: because I can) albeit more simply myself in Django and I'm looking to be able to configure elements in different ways on the page. So for example I might have:
Blog models
A site update message model
A latest comments model.
Now, for each page on the site I want the user to be able to choose the order of and any items that go on it. In my thought process, this would work something like:
class Page(models.Model)
Slug = models.CharField(max_length=100)
class PageItem(models.Model)
Page = models.ForeignKey(Page)
ItemType = models.CharField(max_length=100) # tells me which model to display
InstanceNum = models.IntegerField() # tells me which instance of which model...
Then, ideally, my template would loop through all the PageItems in a page which is easy enough to do.
But what if my page item is a site update as opposed to a blog post? Basically, I am thinking I'd like to pull different item types back in different orders and display them using the appropriate templates. Now, I thought one way to do this would be to, in views.py, to loop through all of the objects and call the appropriate view function, return a bit of html as a string and then pipe that into the resultant template.
My question is - is this the best way to go about doing things? If so, how do I do it? If not, which way should I be going? I'm pretty new to Django so I'm still learning what it can and can't do, so please bear with me. I've checked SO for dupes and don't think this has been asked before...
I've also looked at Django-cms to see if that helps, but I couldn't get to grips with it.
Any suggestions?
A:
First, some puzzelement.
InstanceNum = models.IntegerField() # all models have primary keys.
In Django, all model are assigned an integer primary key.
The comment doesn't make sense, since you don't need to add a primary key like this. The PageItem already has a primary key.
Also, please use lower case letters for attributes. Only Use Upper Case for Class Names. Please.
"But what if my page item is a site update as opposed to a blog post? Basically, I am thinking I'd like to
pull different item types back in
different orders and display them
using the appropriate templates"
Different types usually means different models. Rather than a vague "PageItem", you probably want to have "Site Update" and "Blog Post" as separate models.
You can then iterate through these various objects and display them in the template.
You can easily have your various Models defined with a method to return HTML information. You don't (generally) want to return fully-baked HTML. But CSS ID or Class information is sometimes helpful.
class SiteUpdate( models.Model ):
page = models.ForeignKey(Page)
item_text = models.CharField(max_length=100)
item_css_class = models.CharField(max_length=64)
Now you can generate this into the template with a simple <div class="{{item.item_css_class}}">{{item.item_text}}</div> and use CSS to handle the formatting details that distinguish site update as opposed to a blog post.
A:
The include template tag can take a variable containing the template to include, so you could loop through a sequence containing the various sub-templates and include them in turn, maybe using a dict to map friendly names to template filenames.
|
Return template as string - Django
|
I'm still not sure this is the correct way to go about this, maybe not, but I'll ask anyway. I'd like to re-write wordpress (justification: because I can) albeit more simply myself in Django and I'm looking to be able to configure elements in different ways on the page. So for example I might have:
Blog models
A site update message model
A latest comments model.
Now, for each page on the site I want the user to be able to choose the order of and any items that go on it. In my thought process, this would work something like:
class Page(models.Model)
Slug = models.CharField(max_length=100)
class PageItem(models.Model)
Page = models.ForeignKey(Page)
ItemType = models.CharField(max_length=100) # tells me which model to display
InstanceNum = models.IntegerField() # tells me which instance of which model...
Then, ideally, my template would loop through all the PageItems in a page which is easy enough to do.
But what if my page item is a site update as opposed to a blog post? Basically, I am thinking I'd like to pull different item types back in different orders and display them using the appropriate templates. Now, I thought one way to do this would be to, in views.py, to loop through all of the objects and call the appropriate view function, return a bit of html as a string and then pipe that into the resultant template.
My question is - is this the best way to go about doing things? If so, how do I do it? If not, which way should I be going? I'm pretty new to Django so I'm still learning what it can and can't do, so please bear with me. I've checked SO for dupes and don't think this has been asked before...
I've also looked at Django-cms to see if that helps, but I couldn't get to grips with it.
Any suggestions?
|
[
"First, some puzzelement.\n InstanceNum = models.IntegerField() # all models have primary keys.\n\nIn Django, all model are assigned an integer primary key. \nThe comment doesn't make sense, since you don't need to add a primary key like this. The PageItem already has a primary key.\nAlso, please use lower case letters for attributes. Only Use Upper Case for Class Names. Please.\n\n\"But what if my page item is a site update as opposed to a blog post? Basically, I am thinking I'd like to\n pull different item types back in\n different orders and display them\n using the appropriate templates\"\n\nDifferent types usually means different models. Rather than a vague \"PageItem\", you probably want to have \"Site Update\" and \"Blog Post\" as separate models.\nYou can then iterate through these various objects and display them in the template.\nYou can easily have your various Models defined with a method to return HTML information. You don't (generally) want to return fully-baked HTML. But CSS ID or Class information is sometimes helpful.\nclass SiteUpdate( models.Model ):\n page = models.ForeignKey(Page)\n item_text = models.CharField(max_length=100)\n item_css_class = models.CharField(max_length=64)\n\nNow you can generate this into the template with a simple <div class=\"{{item.item_css_class}}\">{{item.item_text}}</div> and use CSS to handle the formatting details that distinguish site update as opposed to a blog post.\n",
"The include template tag can take a variable containing the template to include, so you could loop through a sequence containing the various sub-templates and include them in turn, maybe using a dict to map friendly names to template filenames.\n"
] |
[
2,
1
] |
[] |
[] |
[
"django",
"django_models",
"django_templates",
"django_views",
"python"
] |
stackoverflow_0002541485_django_django_models_django_templates_django_views_python.txt
|
Q:
Exposing a pointer in Boost.Python
I have this very simple C++ class:
class Tree {
public:
Node *head;
};
BOOST_PYTHON_MODULE(myModule)
{
class_<Tree>("Tree")
.def_readwrite("head",&Tree::head)
;
}
I want to access the head variable from Python, but the message I see is:
No to_python (by-value) converter found for C++ type: Node*
From what I understand, this happens because Python is freaking out because it has no concept of pointers. How can I access the head variable from Python?
I understand I should use encapsulation, but I'm currently stuck with needing a non-encapsulation solution.
A:
Of course, I find the answer ten minutes after asking the question...here's how it's done:
class_<Tree>("Tree")
.add_property("head",
make_getter(&Tree::head, return_value_policy<reference_existing_object>()),
make_setter(&Tree::head, return_value_policy<reference_existing_object>()))
;
|
Exposing a pointer in Boost.Python
|
I have this very simple C++ class:
class Tree {
public:
Node *head;
};
BOOST_PYTHON_MODULE(myModule)
{
class_<Tree>("Tree")
.def_readwrite("head",&Tree::head)
;
}
I want to access the head variable from Python, but the message I see is:
No to_python (by-value) converter found for C++ type: Node*
From what I understand, this happens because Python is freaking out because it has no concept of pointers. How can I access the head variable from Python?
I understand I should use encapsulation, but I'm currently stuck with needing a non-encapsulation solution.
|
[
"Of course, I find the answer ten minutes after asking the question...here's how it's done:\nclass_<Tree>(\"Tree\")\n .add_property(\"head\",\n make_getter(&Tree::head, return_value_policy<reference_existing_object>()),\n make_setter(&Tree::head, return_value_policy<reference_existing_object>()))\n;\n\n"
] |
[
21
] |
[] |
[] |
[
"boost",
"boost_python",
"c++",
"python"
] |
stackoverflow_0002541446_boost_boost_python_c++_python.txt
|
Q:
Python - compare nested lists and append matches to new list?
I wish to compare to nested lists of unequal length. I am interested only in a match between the first element of each sub list. Should a match exist, I wish to add the match to another list for subsequent transformation into a tab delimited file. Here is an example of what I am working with:
x = [['1', 'a', 'b'], ['2', 'c', 'd']]
y = [['1', 'z', 'x'], ['4', 'z', 'x']]
match = []
def find_match():
for i in x:
for j in y:
if i[0] == j[0]:
match.append(j)
return match
This returns:
[['1', 'x'], ['1', 'y'], ['1', 'x'], ['1', 'y'], ['1', 'z', 'x']]
Would it be good practise to reprocess the list to remove duplicates or can this be done in a simpler fashion?
Also, is it better to use tuples and/or tuples of tuples for the purposes of comparison?
Any help is greatly appreciated.
Regards,
Seafoid.
A:
Use sets to obtain collections with no duplicates.
You'll have to use tuples instead of lists as the items because set items must be hashable.
The code you posted doesn't seem to generate the output you posted. I do not have any idea how you are supposed to generate that output from that input. For example, the output has 'y' and the input does not.
I think the design of your function could be much improved. Currently you define x, y, and match as the module level and read and mutate them explicitly. This is not how you want to design functions—as a general rule, a function shouldn't mutate something at the global level. It should be explicitly passed everything it needs and return a result, not implicitly receive information and change something outside itself.
I would change
x = some list
y = some list
match = []
def find_match():
for i in x:
for j in y:
if i[0] == j[0]:
match.append(j)
return match # This is the only line I changed. I think you meant
# your return to be over here?
find_match()
to
x = some list
y = some list
def find_match(x, y):
match = []
for i in x:
for j in y:
if i[0] == j[0]:
match.append(j)
return match
match = find_match(x, y)
To take that last change to the next level, I usually replace the pattern
def f(...):
return_value = []
for...
return_value.append(foo)
return return_value
with the similar generator
def f(...):
for...
yield foo
which would make the above function
def find_match(x, y):
for i in x:
for j in y:
if i[0] == j[0]:
yield j
another way to express this generator's effect is with the generator expression (j for i in x for j in y if i[0] == j[0]).
A:
I don't know if I interpret your question correctly, but given your example it seems that you might be using a wrong index:
change
if i[1] == j[1]:
into
if i[0] == j[0]:
A:
You can do this a lot more simply by using sets.
set_x = set([i[0] for i in x])
set_y = set([i[0] for i in y])
matches = list(set_x & set_y)
A:
if i[1] == j[1]
checks whether the second elements of the arrays are identical. You want if i[0] == j[0].
Otherwise, I find your code quite readable and wouldn't necessarily change it.
A:
A simplier expression should work here too:
list_of_lists = filter(lambda l: l[0][0] == l[1][0], zip(x, y))
map(lambda l: l[1], list_of_lists)
|
Python - compare nested lists and append matches to new list?
|
I wish to compare to nested lists of unequal length. I am interested only in a match between the first element of each sub list. Should a match exist, I wish to add the match to another list for subsequent transformation into a tab delimited file. Here is an example of what I am working with:
x = [['1', 'a', 'b'], ['2', 'c', 'd']]
y = [['1', 'z', 'x'], ['4', 'z', 'x']]
match = []
def find_match():
for i in x:
for j in y:
if i[0] == j[0]:
match.append(j)
return match
This returns:
[['1', 'x'], ['1', 'y'], ['1', 'x'], ['1', 'y'], ['1', 'z', 'x']]
Would it be good practise to reprocess the list to remove duplicates or can this be done in a simpler fashion?
Also, is it better to use tuples and/or tuples of tuples for the purposes of comparison?
Any help is greatly appreciated.
Regards,
Seafoid.
|
[
"\nUse sets to obtain collections with no duplicates. \n\nYou'll have to use tuples instead of lists as the items because set items must be hashable.\n\nThe code you posted doesn't seem to generate the output you posted. I do not have any idea how you are supposed to generate that output from that input. For example, the output has 'y' and the input does not.\nI think the design of your function could be much improved. Currently you define x, y, and match as the module level and read and mutate them explicitly. This is not how you want to design functions—as a general rule, a function shouldn't mutate something at the global level. It should be explicitly passed everything it needs and return a result, not implicitly receive information and change something outside itself.\nI would change \nx = some list\ny = some list\nmatch = []\ndef find_match():\n for i in x:\n for j in y:\n if i[0] == j[0]:\n match.append(j)\n return match # This is the only line I changed. I think you meant \n # your return to be over here?\nfind_match()\n\nto\nx = some list\ny = some list\n\ndef find_match(x, y):\n match = []\n for i in x:\n for j in y:\n if i[0] == j[0]:\n match.append(j)\n return match\nmatch = find_match(x, y)\n\nTo take that last change to the next level, I usually replace the pattern\ndef f(...):\n return_value = []\n for...\n return_value.append(foo)\n return return_value\n\nwith the similar generator\ndef f(...):\n for...\n yield foo\n\nwhich would make the above function\ndef find_match(x, y):\n for i in x:\n for j in y:\n if i[0] == j[0]:\n yield j\n\nanother way to express this generator's effect is with the generator expression (j for i in x for j in y if i[0] == j[0]).\n\n",
"I don't know if I interpret your question correctly, but given your example it seems that you might be using a wrong index:\nchange\nif i[1] == j[1]:\n\ninto\nif i[0] == j[0]:\n\n",
"You can do this a lot more simply by using sets.\nset_x = set([i[0] for i in x])\nset_y = set([i[0] for i in y])\nmatches = list(set_x & set_y)\n\n",
"if i[1] == j[1]\n\nchecks whether the second elements of the arrays are identical. You want if i[0] == j[0].\nOtherwise, I find your code quite readable and wouldn't necessarily change it.\n",
"A simplier expression should work here too:\nlist_of_lists = filter(lambda l: l[0][0] == l[1][0], zip(x, y))\nmap(lambda l: l[1], list_of_lists)\n\n"
] |
[
6,
2,
2,
1,
0
] |
[] |
[] |
[
"compare",
"list",
"python"
] |
stackoverflow_0002538708_compare_list_python.txt
|
Q:
iterating through a list removing items, some items are not removed
I'm trying to transfer the contents of one list to another, but it's not working and I don't know why not. My code looks like this:
list1 = [1, 2, 3, 4, 5, 6]
list2 = []
for item in list1:
list2.append(item)
list1.remove(item)
But if I run it my output looks like this:
>>> list1
[2, 4, 6]
>>> list2
[1, 3, 5]
My question is threefold, I guess: Why is this happening, how do I make it work, and am I overlooking an incredibly simple solution like a 'move' statement or something?
A:
You're deleting items from list1 while you're iterating over it.
That's asking for trouble.
Try this:
>>> list1 = [1,2,3,4,5,6]
>>> list2 = []
>>> list2 = list1[:] # we copy every element from list1 using a slice
>>> del list1[:] # we delete every element from list1
A:
The reason is that you're (appending and) removing from the first list whereby it gets smaller. So the iterator stops before the whole list could be walked through.
To achieve what you want, do this:
list1 = [1, 2, 3, 4, 5, 6]
list2 = []
# You couldn't just make 'list1_copy = list1',
# because this would just copy (share) the reference.
# (i.e. when you change list1_copy, list1 will also change)
# this will make a (new) copy of list1
# so you can happily iterate over it ( without anything getting lost :)
list1_copy = list1[:]
for item in list1_copy:
list2.append(item)
list1.remove(item)
The list1[start:end:step] is the slicing syntax: when you leave start empty it defaults to 0, when you leave end empty it is the highest possible value. So list1[:] means everything in it. (thanks to Wallacoloo)
Like some dudes said, you could also use the extend-method of the list-object to just copy the one list to another, if this was your intention. (But I choosed the way above, because this is near to your approach.)
As you are new to python, I have something for you: Dive Into Python 3 - it's free and easy. - Have fun!
A:
Essential debugging skill: Add print statements. (or print functions in Python 3)
>>> list1= [1, 2, 3, 4, 5, 6]
>>> for item in list1:
... print item
... list1.remove(item)
... print list1
...
1
[2, 3, 4, 5, 6]
3
[2, 4, 5, 6]
5
[2, 4, 6]
Notice that Python is trying to step through the positions of the list, but you keep removing items from the list, making the positions become meaningless.
Python picks the item at position 0 from the list.
You then remove the item, changing the list.
Python then picks the item at position 1 from the list (appearing to skip an item)
You then remove that item, changing the list.
Python then picks the item at position 2 from the list (appearing to skip an item)
You then remove the item, changing the list.
Python would then like to pick the item at position 3, but there's no such item. So the loop stops.
A:
You shouldn't modify a list while you iterate over it. This causes the iterator to point at the wrong item. After the first item is handled, the iterator is pointing at index = 1, but because you've removed an item, the next item is now at index zero, so it will be skipped. This is why you are only handling every other item.
Try:
list2.extend(list1) # This appends all items from list1 to list2.
del list1[:] # From ChristopheD's post.
A:
Exactly as ChristopheD says.
Could do this:
list1 = [1, 2, 3, 4, 5, 6]
list2 = []
for item in list1:
list2.append(item)
list1 = []
That'll clear list1.
Edit He/she has updated their post. I'll leave this up as a slight alternative.
A:
Using a list comprehension:
list2 = [item for item in list1]
Bind the name list2 to the the same object as list1:
list2 = list1
(Note that if you modify the contents of list1, list2 will be change accordingly.)
Create a copy of list1 and bind it to the name list2:
list2 = list1[:]
In this case list1 and list2 are different objects.
A:
Try this instead:
list1 = [1, 2, 3, 4, 5, 6]
list2 = []
list2.extend(list1)
list1[:] = []
A:
There is also the humble copy function (or deepcopy if you have complex objects and not just integers in your list):
from copy import copy
list2 = copy(list1)
You might get a more appropriate answer if you explain what you're trying to accomplish (unless you're just learning about python lists).
"Variables" in Python are just names/references, so the destructive copy you seem to want to do seems kind of strange. If you want list2 to have the same values as list1 you can just do:
list2 = list1 # now they are both referring to the same list
And if after that you want to use list1 for something else, you can just do:
list1 = ['A', 'B', 'C']
A:
As you can see in other answers, you are trying to modify the list while iterating over it. This doesn't work. There are many ways to copy one list to another. I did some tests to see how fast each approach is:
>>> timeit.Timer('list2 = list1[:]', 'list1 = range(10**3)').timeit(10**6)
3.9134418964385986
>>> timeit.Timer('list2 = []; list2.extend(list1)', 'list1 = range(10**3)').timeit(10**6)
4.9082601070404053
>>> timeit.Timer('list2 = copy.copy(list1)', 'import copy; list1 = range(10**3)').timeit(10**6)
7.5023419857025146
>>> timeit.Timer('list2 = [i for i in list1]', 'list1 = range(10**3)').timeit(10**6)
95.697894811630249
The slice syntax is the fastest. It's much faster than using a list comprehension.
To clear a list, you can use:
del list1[:]
A:
@potatocubed: Many of the answers given solve the trivial example you gave ("move list1 to list2"), but don't really explain the "why" of the deeper problem, which is modifying a list as you iterate over it. Study S.Lott's answer...
|
iterating through a list removing items, some items are not removed
|
I'm trying to transfer the contents of one list to another, but it's not working and I don't know why not. My code looks like this:
list1 = [1, 2, 3, 4, 5, 6]
list2 = []
for item in list1:
list2.append(item)
list1.remove(item)
But if I run it my output looks like this:
>>> list1
[2, 4, 6]
>>> list2
[1, 3, 5]
My question is threefold, I guess: Why is this happening, how do I make it work, and am I overlooking an incredibly simple solution like a 'move' statement or something?
|
[
"You're deleting items from list1 while you're iterating over it.\nThat's asking for trouble.\nTry this:\n>>> list1 = [1,2,3,4,5,6]\n>>> list2 = []\n>>> list2 = list1[:] # we copy every element from list1 using a slice\n>>> del list1[:] # we delete every element from list1\n\n",
"The reason is that you're (appending and) removing from the first list whereby it gets smaller. So the iterator stops before the whole list could be walked through.\nTo achieve what you want, do this:\nlist1 = [1, 2, 3, 4, 5, 6]\nlist2 = []\n\n# You couldn't just make 'list1_copy = list1',\n# because this would just copy (share) the reference.\n# (i.e. when you change list1_copy, list1 will also change)\n\n# this will make a (new) copy of list1\n# so you can happily iterate over it ( without anything getting lost :)\nlist1_copy = list1[:]\n\nfor item in list1_copy:\n list2.append(item)\n list1.remove(item)\n\nThe list1[start:end:step] is the slicing syntax: when you leave start empty it defaults to 0, when you leave end empty it is the highest possible value. So list1[:] means everything in it. (thanks to Wallacoloo)\nLike some dudes said, you could also use the extend-method of the list-object to just copy the one list to another, if this was your intention. (But I choosed the way above, because this is near to your approach.)\nAs you are new to python, I have something for you: Dive Into Python 3 - it's free and easy. - Have fun!\n",
"Essential debugging skill: Add print statements. (or print functions in Python 3)\n>>> list1= [1, 2, 3, 4, 5, 6]\n>>> for item in list1:\n... print item\n... list1.remove(item)\n... print list1\n... \n1\n[2, 3, 4, 5, 6]\n3\n[2, 4, 5, 6]\n5\n[2, 4, 6]\n\nNotice that Python is trying to step through the positions of the list, but you keep removing items from the list, making the positions become meaningless.\nPython picks the item at position 0 from the list.\nYou then remove the item, changing the list.\nPython then picks the item at position 1 from the list (appearing to skip an item)\nYou then remove that item, changing the list.\nPython then picks the item at position 2 from the list (appearing to skip an item)\nYou then remove the item, changing the list.\nPython would then like to pick the item at position 3, but there's no such item. So the loop stops.\n",
"You shouldn't modify a list while you iterate over it. This causes the iterator to point at the wrong item. After the first item is handled, the iterator is pointing at index = 1, but because you've removed an item, the next item is now at index zero, so it will be skipped. This is why you are only handling every other item.\nTry:\n list2.extend(list1) # This appends all items from list1 to list2.\n del list1[:] # From ChristopheD's post.\n\n",
"Exactly as ChristopheD says.\nCould do this:\nlist1 = [1, 2, 3, 4, 5, 6]\nlist2 = []\n\nfor item in list1:\n list2.append(item)\n\nlist1 = []\n\nThat'll clear list1.\nEdit He/she has updated their post. I'll leave this up as a slight alternative.\n",
"Using a list comprehension:\nlist2 = [item for item in list1]\n\nBind the name list2 to the the same object as list1:\nlist2 = list1\n\n(Note that if you modify the contents of list1, list2 will be change accordingly.)\nCreate a copy of list1 and bind it to the name list2:\nlist2 = list1[:]\n\nIn this case list1 and list2 are different objects.\n",
"Try this instead:\nlist1 = [1, 2, 3, 4, 5, 6]\nlist2 = []\n\nlist2.extend(list1)\nlist1[:] = []\n\n",
"There is also the humble copy function (or deepcopy if you have complex objects and not just integers in your list):\nfrom copy import copy\n\nlist2 = copy(list1)\n\nYou might get a more appropriate answer if you explain what you're trying to accomplish (unless you're just learning about python lists).\n\"Variables\" in Python are just names/references, so the destructive copy you seem to want to do seems kind of strange. If you want list2 to have the same values as list1 you can just do:\nlist2 = list1 # now they are both referring to the same list\n\nAnd if after that you want to use list1 for something else, you can just do:\nlist1 = ['A', 'B', 'C']\n\n",
"As you can see in other answers, you are trying to modify the list while iterating over it. This doesn't work. There are many ways to copy one list to another. I did some tests to see how fast each approach is:\n>>> timeit.Timer('list2 = list1[:]', 'list1 = range(10**3)').timeit(10**6)\n3.9134418964385986\n\n>>> timeit.Timer('list2 = []; list2.extend(list1)', 'list1 = range(10**3)').timeit(10**6)\n4.9082601070404053\n\n>>> timeit.Timer('list2 = copy.copy(list1)', 'import copy; list1 = range(10**3)').timeit(10**6)\n7.5023419857025146\n\n>>> timeit.Timer('list2 = [i for i in list1]', 'list1 = range(10**3)').timeit(10**6)\n95.697894811630249\n\nThe slice syntax is the fastest. It's much faster than using a list comprehension.\nTo clear a list, you can use:\ndel list1[:]\n\n",
"@potatocubed: Many of the answers given solve the trivial example you gave (\"move list1 to list2\"), but don't really explain the \"why\" of the deeper problem, which is modifying a list as you iterate over it. Study S.Lott's answer...\n"
] |
[
8,
8,
4,
3,
1,
1,
1,
1,
1,
0
] |
[] |
[] |
[
"list",
"python"
] |
stackoverflow_0002541528_list_python.txt
|
Q:
Why am I getting a " instance has no attribute '__getitem__' " error?
Here's the code:
class BinaryTree:
def __init__(self,rootObj):
self.key = rootObj
self.left = None
self.right = None
root = [self.key, self.left, self.right]
def getRootVal(root):
return root[0]
def setRootVal(newVal):
root[0] = newVal
def getLeftChild(root):
return root[1]
def getRightChild(root):
return root[2]
def insertLeft(self,newNode):
if self.left == None:
self.left = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.left = self.left
self.left = t
def insertRight(self,newNode):
if self.right == None:
self.right = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.right = self.right
self.right = t
def buildParseTree(fpexp):
fplist = fpexp.split()
pStack = Stack()
eTree = BinaryTree('')
pStack.push(eTree)
currentTree = eTree
for i in fplist:
if i == '(':
currentTree.insertLeft('')
pStack.push(currentTree)
currentTree = currentTree.getLeftChild()
elif i not in '+-*/)':
currentTree.setRootVal(eval(i))
parent = pStack.pop()
currentTree = parent
elif i in '+-*/':
currentTree.setRootVal(i)
currentTree.insertRight('')
pStack.push(currentTree)
currentTree = currentTree.getRightChild()
elif i == ')':
currentTree = pStack.pop()
else:
print "error: I don't recognize " + i
return eTree
def postorder(tree):
if tree != None:
postorder(tree.getLeftChild())
postorder(tree.getRightChild())
print tree.getRootVal()
def preorder(self):
print self.key
if self.left:
self.left.preorder()
if self.right:
self.right.preorder()
def inorder(tree):
if tree != None:
inorder(tree.getLeftChild())
print tree.getRootVal()
inorder(tree.getRightChild())
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def main():
parseData = raw_input( "Please enter the problem you wished parsed.(NOTE: problem must have parenthesis to seperate each binary grouping and must be spaced out.) " )
tree = buildParseTree(parseData)
print( "The post order is: ", + postorder(tree))
print( "The post order is: ", + postorder(tree))
print( "The post order is: ", + preorder(tree))
print( "The post order is: ", + inorder(tree))
main()
And here is the error:
Please enter the problem you wished parsed.(NOTE: problem must have parenthesis to seperate each binary grouping and must be spaced out.) ( 1 + 2 )
Traceback (most recent call last):
File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 108, in
main()
File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 102, in main
tree = buildParseTree(parseData)
File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 46, in buildParseTree
currentTree = currentTree.getLeftChild()
File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 15, in getLeftChild
return root[1]
AttributeError: BinaryTree instance has no attribute '__getitem__'
A:
Because you declared your methods wrong:
Lets have a look what happens if you call tree.getRootVal(). .getRootVal() is declared this way:
def getRootVal(root):
return root[0]
As you probably know, the first parameter passed to a method is always the instance and it is provided implicitly. So you basically try to treat an instance of BinaryTree as a sequence(root[0]).
You have to specify it this way:
class BinaryTree:
def __init__(self,rootObj):
self.key = rootObj
self.left = None
self.right = None
self.root = [self.key, self.left, self.right] # self.root
def getRootVal(self):
return self.root[0] # access self.root
def setRootVal(self, newVal):
self.root[0] = newVal
# and also the other functions
The first parameter to an objects method does not have to be called self. But helps to do it this way in order to avoid errors like you did.
Interesting that you declared insertLeft and insertRight correctly ;)
A:
Your first problem is that root should be self.root.
Your second problem is that here:
def getLeftChild(root):
return root[1]
You are redefining root with a new meaning.
A:
As PreludeAndFugue says, you should fix the formatting. But from what I can gather, there is at least one error in your class methods in BinaryTree: most of them don't even take self as a parameter. Fix that and maybe you might be a bit better off.
|
Why am I getting a " instance has no attribute '__getitem__' " error?
|
Here's the code:
class BinaryTree:
def __init__(self,rootObj):
self.key = rootObj
self.left = None
self.right = None
root = [self.key, self.left, self.right]
def getRootVal(root):
return root[0]
def setRootVal(newVal):
root[0] = newVal
def getLeftChild(root):
return root[1]
def getRightChild(root):
return root[2]
def insertLeft(self,newNode):
if self.left == None:
self.left = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.left = self.left
self.left = t
def insertRight(self,newNode):
if self.right == None:
self.right = BinaryTree(newNode)
else:
t = BinaryTree(newNode)
t.right = self.right
self.right = t
def buildParseTree(fpexp):
fplist = fpexp.split()
pStack = Stack()
eTree = BinaryTree('')
pStack.push(eTree)
currentTree = eTree
for i in fplist:
if i == '(':
currentTree.insertLeft('')
pStack.push(currentTree)
currentTree = currentTree.getLeftChild()
elif i not in '+-*/)':
currentTree.setRootVal(eval(i))
parent = pStack.pop()
currentTree = parent
elif i in '+-*/':
currentTree.setRootVal(i)
currentTree.insertRight('')
pStack.push(currentTree)
currentTree = currentTree.getRightChild()
elif i == ')':
currentTree = pStack.pop()
else:
print "error: I don't recognize " + i
return eTree
def postorder(tree):
if tree != None:
postorder(tree.getLeftChild())
postorder(tree.getRightChild())
print tree.getRootVal()
def preorder(self):
print self.key
if self.left:
self.left.preorder()
if self.right:
self.right.preorder()
def inorder(tree):
if tree != None:
inorder(tree.getLeftChild())
print tree.getRootVal()
inorder(tree.getRightChild())
class Stack:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
def main():
parseData = raw_input( "Please enter the problem you wished parsed.(NOTE: problem must have parenthesis to seperate each binary grouping and must be spaced out.) " )
tree = buildParseTree(parseData)
print( "The post order is: ", + postorder(tree))
print( "The post order is: ", + postorder(tree))
print( "The post order is: ", + preorder(tree))
print( "The post order is: ", + inorder(tree))
main()
And here is the error:
Please enter the problem you wished parsed.(NOTE: problem must have parenthesis to seperate each binary grouping and must be spaced out.) ( 1 + 2 )
Traceback (most recent call last):
File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 108, in
main()
File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 102, in main
tree = buildParseTree(parseData)
File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 46, in buildParseTree
currentTree = currentTree.getLeftChild()
File "C:\Users\Kevin\Desktop\Python Stuff\Assignment 11\parseTree.py", line 15, in getLeftChild
return root[1]
AttributeError: BinaryTree instance has no attribute '__getitem__'
|
[
"Because you declared your methods wrong:\nLets have a look what happens if you call tree.getRootVal(). .getRootVal() is declared this way:\ndef getRootVal(root):\n return root[0]\n\nAs you probably know, the first parameter passed to a method is always the instance and it is provided implicitly. So you basically try to treat an instance of BinaryTree as a sequence(root[0]). \nYou have to specify it this way:\nclass BinaryTree:\n def __init__(self,rootObj):\n self.key = rootObj\n self.left = None\n self.right = None\n self.root = [self.key, self.left, self.right] # self.root\n\n def getRootVal(self):\n return self.root[0] # access self.root\n\n def setRootVal(self, newVal):\n self.root[0] = newVal\n\n # and also the other functions\n\nThe first parameter to an objects method does not have to be called self. But helps to do it this way in order to avoid errors like you did.\nInteresting that you declared insertLeft and insertRight correctly ;)\n",
"Your first problem is that root should be self.root.\nYour second problem is that here:\ndef getLeftChild(root):\n return root[1]\n\nYou are redefining root with a new meaning.\n",
"As PreludeAndFugue says, you should fix the formatting. But from what I can gather, there is at least one error in your class methods in BinaryTree: most of them don't even take self as a parameter. Fix that and maybe you might be a bit better off.\n"
] |
[
22,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002541718_python.txt
|
Q:
Read/Write a file from/to network folder/share using Python?
How to Write/Read a file to/from a network folder/share using python? The application will run under Linux and network folder/share can be a Linux/Windows System.
Also, how to check that network folder/share has enough space before writing a file?
What things should i consider?
A:
Mount the shares using Samba, check the free space on the share using df or os.statvfs and read/write to it like any other folder.
|
Read/Write a file from/to network folder/share using Python?
|
How to Write/Read a file to/from a network folder/share using python? The application will run under Linux and network folder/share can be a Linux/Windows System.
Also, how to check that network folder/share has enough space before writing a file?
What things should i consider?
|
[
"Mount the shares using Samba, check the free space on the share using df or os.statvfs and read/write to it like any other folder.\n"
] |
[
1
] |
[] |
[] |
[
"network_shares",
"python"
] |
stackoverflow_0002542025_network_shares_python.txt
|
Q:
Python 3: receive user input including newline characters
I'm trying to read in the following text from the command-line in Python 3 (copied verbatim, newlines and all):
lcbeika
rraobmlo
grmfina
ontccep
emrlin
tseiboo
edosrgd
mkoeys
eissaml
knaiefr
Using input, I can only read in the first word as once it reads the first newline it stops reading.
Is there a way I could read in them all without iteratively calling input?
A:
You can import sys and use the methods on sys.stdin for example:
text = sys.stdin.read()
or:
lines = sys.stdin.readlines()
or:
for line in sys.stdin:
# Do something with line.
|
Python 3: receive user input including newline characters
|
I'm trying to read in the following text from the command-line in Python 3 (copied verbatim, newlines and all):
lcbeika
rraobmlo
grmfina
ontccep
emrlin
tseiboo
edosrgd
mkoeys
eissaml
knaiefr
Using input, I can only read in the first word as once it reads the first newline it stops reading.
Is there a way I could read in them all without iteratively calling input?
|
[
"You can import sys and use the methods on sys.stdin for example:\ntext = sys.stdin.read()\n\nor:\nlines = sys.stdin.readlines()\n\nor:\nfor line in sys.stdin:\n # Do something with line.\n\n"
] |
[
11
] |
[
"if you are passing the text into your script as a file , you can use readlines()\neg\ndata=open(\"file\").readlines()\n\nor you can use fileinput\nimport fileinput\nfor line in fileinput.input():\n print line\n\n"
] |
[
-1
] |
[
"input",
"python",
"python_3.x"
] |
stackoverflow_0002542171_input_python_python_3.x.txt
|
Q:
Get a user's timezone in Python + Pylons
Is there a way to get the timezone of the connecting user using Pylons, and to adjust the content before rendering accordingly? Or can this only be done by JS?
Thanks.
A:
You can't get the client's timezone using server-side code, you can, however:
use Javascript: Date.getTimezoneOffset();
use geolocation to determine where the user is located and deduce the timezone from the location
|
Get a user's timezone in Python + Pylons
|
Is there a way to get the timezone of the connecting user using Pylons, and to adjust the content before rendering accordingly? Or can this only be done by JS?
Thanks.
|
[
"You can't get the client's timezone using server-side code, you can, however:\n\nuse Javascript: Date.getTimezoneOffset();\nuse geolocation to determine where the user is located and deduce the timezone from the location\n\n"
] |
[
2
] |
[] |
[] |
[
"pylons",
"python",
"timezone"
] |
stackoverflow_0002542206_pylons_python_timezone.txt
|
Q:
Google Federated Login vs Hybrid Protocol vs Google Data Authentication. Whats's the Difference?
I am trying to implement Google Authentication in my website, in which I would also be pulling some Google Data using the Google Data API and I am using Google App Engine with Jinja2.
My question is, so many ways are mentioned to do it. I am confused between Google Federated Login,Google Data Protocol, Hybrid Protocol. Are these things the same or different ways to do the same thing.
From what I read and understood, which might be incorrect, Google Federated Login uses the hybrid protocol to authenticate and fetch the google data.
Is there a proper guide to implement any one of these in python. Examples which I found at the google link are kind of different. From what I understood,correct me if i am wrong, I have to implement only the OpenID Consumer part.
In order to implement Google Federated Login in Python, I saw that we need to download a separate library from the openid-enabled.com but I found a different library for the google data implementation at http://code.google.com/p/gdata-python-client/
As you can see, I am confused a lot :D. Please help me :)
Thanks
A:
Here is an article specifically on Retrieving Authenticated Google Data Feeds with Google App Engine
The way I understand this example:
You use the gdata-python-client to set up this AuthSub interaction
gdata.auth.extract_auth_sub_token_from_url extracts the token you get from AuthSub (step 4 above)
you can now use this token to access Google Data.
|
Google Federated Login vs Hybrid Protocol vs Google Data Authentication. Whats's the Difference?
|
I am trying to implement Google Authentication in my website, in which I would also be pulling some Google Data using the Google Data API and I am using Google App Engine with Jinja2.
My question is, so many ways are mentioned to do it. I am confused between Google Federated Login,Google Data Protocol, Hybrid Protocol. Are these things the same or different ways to do the same thing.
From what I read and understood, which might be incorrect, Google Federated Login uses the hybrid protocol to authenticate and fetch the google data.
Is there a proper guide to implement any one of these in python. Examples which I found at the google link are kind of different. From what I understood,correct me if i am wrong, I have to implement only the OpenID Consumer part.
In order to implement Google Federated Login in Python, I saw that we need to download a separate library from the openid-enabled.com but I found a different library for the google data implementation at http://code.google.com/p/gdata-python-client/
As you can see, I am confused a lot :D. Please help me :)
Thanks
|
[
"Here is an article specifically on Retrieving Authenticated Google Data Feeds with Google App Engine\nThe way I understand this example: \n\nYou use the gdata-python-client to set up this AuthSub interaction\n\ngdata.auth.extract_auth_sub_token_from_url extracts the token you get from AuthSub (step 4 above)\nyou can now use this token to access Google Data.\n\n"
] |
[
1
] |
[] |
[] |
[
"google_data",
"oauth",
"openid",
"python"
] |
stackoverflow_0001854467_google_data_oauth_openid_python.txt
|
Q:
Find elements based on xsd type with lxml
I am trying to get a list of elements with a specific xsd type with lxml 2.x and I can't figure out how to traverse the xsd for specific types.
Example of schema:
<xsd:element name="ServerOwner" type="srvrs:string90" minOccurs="0">
<xsd:element name="HostName" type="srvrs:string35" minOccurs="0">
Example xml data:
<srvrs:ServerOwner>John Doe</srvrs:ServerOwner>
<srvrs:HostName>box01.example.com</srvrs:HostName>
The ideal function would look like:
elements = getElems(xml_doc, 'string90')
def getElems(xml_doc, xsd_type):
** xpath or something to find the elements and build a dict
return elements
A:
Really the only special support lxml has for XML Schema, as seen here, is to tell you if some document is valid according to some schema or not. Anything more sophisticated you'll have to do yourself.
This should be a relatively simple two-phase process, I'd think -- get all the xsd:element elements in the schema that match the type you care about, and look at their names:
def getElems(schemaDoc, xmlDoc, typeName):
names = schemaDoc.xpath("//xsd:element[@type = $n]/@name",
namespaces={"xsd":
"http://www.w3.org/2001/XMLSchema"},
n=typeName)
Then, fetch all the elements with each name from the document.
elements = []
for name in names:
namedElements = xmlDoc.xpath("//*[local-name() = $name]", name=name)
elements.extend(namedElements)
Now you have a list of elements with the names that matched the type in the schema.
return elements
Note that the xpath expression for searching the document has to look at every element, so if you can tighten that up to only look in the subsection of the document you care about it'll go faster.
|
Find elements based on xsd type with lxml
|
I am trying to get a list of elements with a specific xsd type with lxml 2.x and I can't figure out how to traverse the xsd for specific types.
Example of schema:
<xsd:element name="ServerOwner" type="srvrs:string90" minOccurs="0">
<xsd:element name="HostName" type="srvrs:string35" minOccurs="0">
Example xml data:
<srvrs:ServerOwner>John Doe</srvrs:ServerOwner>
<srvrs:HostName>box01.example.com</srvrs:HostName>
The ideal function would look like:
elements = getElems(xml_doc, 'string90')
def getElems(xml_doc, xsd_type):
** xpath or something to find the elements and build a dict
return elements
|
[
"Really the only special support lxml has for XML Schema, as seen here, is to tell you if some document is valid according to some schema or not. Anything more sophisticated you'll have to do yourself.\nThis should be a relatively simple two-phase process, I'd think -- get all the xsd:element elements in the schema that match the type you care about, and look at their names:\ndef getElems(schemaDoc, xmlDoc, typeName):\n names = schemaDoc.xpath(\"//xsd:element[@type = $n]/@name\",\n namespaces={\"xsd\": \n \"http://www.w3.org/2001/XMLSchema\"},\n n=typeName)\n\nThen, fetch all the elements with each name from the document.\n elements = []\n for name in names: \n namedElements = xmlDoc.xpath(\"//*[local-name() = $name]\", name=name)\n elements.extend(namedElements)\n\nNow you have a list of elements with the names that matched the type in the schema.\n return elements\n\nNote that the xpath expression for searching the document has to look at every element, so if you can tighten that up to only look in the subsection of the document you care about it'll go faster.\n"
] |
[
5
] |
[] |
[] |
[
"lxml",
"python",
"xml",
"xsd"
] |
stackoverflow_0002542580_lxml_python_xml_xsd.txt
|
Q:
What is the most efficient way to populate class attributes with a row from a database query?
Looking to have a database query set all the instance variables in a class:
Example:
def populate(self, if):
#Perform mysql query
self._name = row['name']
self._email = row['email']
...
What's the fastest way to do this? Or is this not recommended (with a better approach)?
A:
It makes your code the most readable and predictable to do it manually like this. That way you know exactly what attributes exist and what attributes do not pretty easily.
You can use setattr to automate tons of these.
One fairly nice way would be to define a list attributes = ['name', 'email'...] as a class attribute then to do
for name in self.attributes:
setattr(self, "_" + name, row[name])
You also can get the attributes from the query itself, but this will change depending on your query (especially if you're using SELECT * or anything like that) and your changing your database.
I notice these attributes all have leading underscore. If this is a purely internal thing, consider whether an attribute rather than the query result itself or storing a dict wouldn't better suit your needs. Generally, attributes are supposed to be fairly static things.
I hear oursql is nicer the MySQLdb
A:
Look at sqlalchemy it's the most popular database abstraction for python.
If you really like the active record pattern there is a layer you can put on top of it called elixir.
I use sqlalchemy because it's a nice database abstraction and allows me to switch out databases. I use sqlite in memory for my tests and I can wedge it in to my code using sqlalchemy.
|
What is the most efficient way to populate class attributes with a row from a database query?
|
Looking to have a database query set all the instance variables in a class:
Example:
def populate(self, if):
#Perform mysql query
self._name = row['name']
self._email = row['email']
...
What's the fastest way to do this? Or is this not recommended (with a better approach)?
|
[
"\nIt makes your code the most readable and predictable to do it manually like this. That way you know exactly what attributes exist and what attributes do not pretty easily.\nYou can use setattr to automate tons of these. \nOne fairly nice way would be to define a list attributes = ['name', 'email'...] as a class attribute then to do\nfor name in self.attributes:\n setattr(self, \"_\" + name, row[name])\n\nYou also can get the attributes from the query itself, but this will change depending on your query (especially if you're using SELECT * or anything like that) and your changing your database.\nI notice these attributes all have leading underscore. If this is a purely internal thing, consider whether an attribute rather than the query result itself or storing a dict wouldn't better suit your needs. Generally, attributes are supposed to be fairly static things.\nI hear oursql is nicer the MySQLdb\n\n",
"Look at sqlalchemy it's the most popular database abstraction for python.\nIf you really like the active record pattern there is a layer you can put on top of it called elixir.\nI use sqlalchemy because it's a nice database abstraction and allows me to switch out databases. I use sqlite in memory for my tests and I can wedge it in to my code using sqlalchemy. \n"
] |
[
4,
3
] |
[] |
[] |
[
"mysql",
"pylons",
"python"
] |
stackoverflow_0002542887_mysql_pylons_python.txt
|
Q:
Problem with room/screen/menu controller in python game: old rooms are not removed from memory
I'm literally banging my head against a wall here (as in, yes, physically, at my current location, I am damaging my cranium). Basically, I've got a Python/Pygame game with some typical game "rooms", or "screens." EG title screen, high scores screen, and the actual game room. Something bad is happening when I switch between rooms: the old room (and its various items) are not removed from memory, or from my event listener. Not only that, but every time I go back to a certain room, my number of event listeners increases, as well as the RAM being consumed! (So if I go back and forth between the title screen and the "game room", for instance, the number of event listeners and the memory usage just keep going up and up.
The main issue is that all the event listeners start to add up and really drain the CPU. I'm new to Python, and don't know if I'm doing something obviously wrong here, or what.
I will love you so much if you can help me with this!
Below is the relevant source code. Complete source code at http://www.necessarygames.com/my_games/betraveled/betraveled_src0328.zip
(Requires Python 2.6 + Pygame 1.9)
MAIN.PY
class RoomController(object):
"""Controls which room is currently active (eg Title Screen)"""
def __init__(self, screen, ev_manager):
self.room = None
self.screen = screen
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
self.room = self.set_room(config.room)
def set_room(self, room_const):
#Unregister old room from ev_manager
if self.room:
self.room.ev_manager.unregister_listener(self.room)
self.room = None
#Set new room based on const
if room_const == config.TITLE_SCREEN:
return rooms.TitleScreen(self.screen, self.ev_manager)
elif room_const == config.GAME_MODE_ROOM:
return rooms.GameModeRoom(self.screen, self.ev_manager)
elif room_const == config.GAME_ROOM:
return rooms.GameRoom(self.screen, self.ev_manager)
elif room_const == config.HIGH_SCORES_ROOM:
return rooms.HighScoresRoom(self.screen, self.ev_manager)
def notify(self, event):
if isinstance(event, ChangeRoomRequest):
if event.game_mode:
config.game_mode = event.game_mode
self.room = self.set_room(event.new_room)
#Run game
def main():
pygame.init()
screen = pygame.display.set_mode(config.screen_size)
ev_manager = EventManager()
spinner = CPUSpinnerController(ev_manager)
room_controller = RoomController(screen, ev_manager)
pygame_event_controller = PyGameEventController(ev_manager)
spinner.run()
EVENT_MANAGER.PY
class EventManager:
#This object is responsible for coordinating most communication
#between the Model, View, and Controller.
def __init__(self):
from weakref import WeakKeyDictionary
self.last_listeners = {}
self.listeners = WeakKeyDictionary()
self.eventQueue= []
self.gui_app = None
#----------------------------------------------------------------------
def register_listener(self, listener):
self.listeners[listener] = 1
#----------------------------------------------------------------------
def unregister_listener(self, listener):
if listener in self.listeners:
del self.listeners[listener]
#----------------------------------------------------------------------
def clear(self):
del self.listeners[:]
#----------------------------------------------------------------------
def post(self, event):
# if isinstance(event, MouseButtonLeftEvent):
# debug(event.name)
#NOTE: copying the list like this before iterating over it, EVERY tick, is highly inefficient,
#but currently has to be done because of how new listeners are added to the queue while it is running
#(eg when popping cards from a deck). Should be changed. See: http://dr0id.homepage.bluewin.ch/pygame_tutorial08.html
#and search for "Watch the iteration"
print 'Number of listeners: ' + str(len(self.listeners))
for listener in list(self.listeners):
#NOTE: If the weakref has died, it will be
#automatically removed, so we don't have
#to worry about it.
listener.notify(event)
def notify(self, event):
pass
#------------------------------------------------------------------------------
class PyGameEventController:
"""..."""
def __init__(self, ev_manager):
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
self.input_freeze = False
#----------------------------------------------------------------------
def notify(self, incoming_event):
if isinstance(incoming_event, UserInputFreeze):
self.input_freeze = True
elif isinstance(incoming_event, UserInputUnFreeze):
self.input_freeze = False
elif isinstance(incoming_event, TickEvent) or isinstance(incoming_event, BoardCreationTick):
#Share some time with other processes, so we don't hog the cpu
pygame.time.wait(5)
#Handle Pygame Events
for event in pygame.event.get():
#If this event manager has an associated PGU GUI app, notify it of the event
if self.ev_manager.gui_app:
self.ev_manager.gui_app.event(event)
#Standard event handling for everything else
ev = None
if event.type == QUIT:
ev = QuitEvent()
elif event.type == pygame.MOUSEBUTTONDOWN and not self.input_freeze:
if event.button == 1: #Button 1
pos = pygame.mouse.get_pos()
ev = MouseButtonLeftEvent(pos)
elif event.type == pygame.MOUSEBUTTONDOWN and not self.input_freeze:
if event.button == 2: #Button 2
pos = pygame.mouse.get_pos()
ev = MouseButtonRightEvent(pos)
elif event.type == pygame.MOUSEBUTTONUP and not self.input_freeze:
if event.button == 2: #Button 2 Release
pos = pygame.mouse.get_pos()
ev = MouseButtonRightReleaseEvent(pos)
elif event.type == pygame.MOUSEMOTION:
pos = pygame.mouse.get_pos()
ev = MouseMoveEvent(pos)
#Post event to event manager
if ev:
self.ev_manager.post(ev)
# elif isinstance(event, BoardCreationTick):
# #Share some time with other processes, so we don't hog the cpu
# pygame.time.wait(5)
#
# #If this event manager has an associated PGU GUI app, notify it of the event
# if self.ev_manager.gui_app:
# self.ev_manager.gui_app.event(event)
#------------------------------------------------------------------------------
class CPUSpinnerController:
def __init__(self, ev_manager):
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
self.clock = pygame.time.Clock()
self.cumu_time = 0
self.keep_going = True
#----------------------------------------------------------------------
def run(self):
if not self.keep_going:
raise Exception('dead spinner')
while self.keep_going:
time_passed = self.clock.tick()
fps = self.clock.get_fps()
self.cumu_time += time_passed
self.ev_manager.post(TickEvent(time_passed, fps))
if self.cumu_time >= 1000:
self.cumu_time = 0
self.ev_manager.post(SecondEvent(fps=fps))
pygame.quit()
#----------------------------------------------------------------------
def notify(self, event):
if isinstance(event, QuitEvent):
#this will stop the while loop from running
self.keep_going = False
EXAMPLE CLASS USING EVENT MANAGER
class Timer(object):
def __init__(self, ev_manager, time_left):
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
self.time_left = time_left
self.paused = False
def __repr__(self):
return str(self.time_left)
def pause(self):
self.paused = True
def unpause(self):
self.paused = False
def notify(self, event):
#Pause Event
if isinstance(event, Pause):
self.pause()
#Unpause Event
elif isinstance(event, Unpause):
self.unpause()
#Second Event
elif isinstance(event, SecondEvent):
if not self.paused:
self.time_left -= 1
A:
When you do something like this:
return rooms.TitleScreen(self.screen, self.ev_manager)
I'm assuming that you're creating a new TitleScreen object.
If this is what you want to do then you probably want to delete the old room object when switching rooms.
def notify(self, event):
if isinstance(event, ChangeRoomRequest):
if event.game_mode:
config.game_mode = event.game_mode
del self.room // delete the old room object
self.room = self.set_room(event.new_room)
If you want the rooms to persist, your set_room function is going to be have to check to see if the room has already been created. Then you can create a new room or load the old one intelligently. But you will also have to keep track of these rooms somehow.
EDIT:
OK then. The problem isn't the rooms, it's listeners. Every listener you register on init should probably be unregistered on del. I did a search for 'unregister_listener' in your src and only found it unregistering the room listeners.
So when you create 100 buttons and then create 100 more without unregistering any listeners, you'll have 100 orphaned listeners. That's not good. I'd overload the __ del __ () function to remove those listeners just like the __ init __ () function adds them.
Does that make sense?
A:
I've also tried keeping track of the rooms, instead of throwing them and creating new ones each time a new room request comes around. Unfortunately, this code isn't working for me either: when I return to the title screen from the game room, the title screen renders, but nothing responds to anything... I'm not sure what the problem is there...
Watching the number of listeners, this doesn't seem to be solving the "creep" problem, as it goes from:
1) Title Screen: 4 listeners active, to:
2) Game mode select screen: 5 listeners active, to:
3) Game room: 86 listeners active, to:
4) Title Screen (unresponsive): 100 listeners active
Here's the code I tried in MAIN.PY
class RoomController(object):
"""Controls which room is currently active (eg Title Screen)"""
def __init__(self, screen, ev_manager):
self.room = None
self.screen = screen
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
self.title_screen = None
self.game_mode_room = None
self.game_room = None
self.high_scores_room = None
self.room = self.set_room(config.room)
def set_room(self, room_const):
#Set new room based on const
if room_const == config.TITLE_SCREEN:
if self.title_screen == None:
self.title_screen = rooms.TitleScreen(self.screen, self.ev_manager)
return self.title_screen
elif room_const == config.GAME_MODE_ROOM:
if self.game_mode_room == None:
self.game_mode_room = rooms.GameModeRoom(self.screen, self.ev_manager)
return self.game_mode_room
elif room_const == config.GAME_ROOM:
if self.game_room == None:
self.game_room = rooms.GameRoom(self.screen, self.ev_manager)
return self.game_room
elif room_const == config.HIGH_SCORES_ROOM:
if self.high_scores_room == None:
self.high_scores_room = rooms.HighScoresRoom(self.screen, self.ev_manager)
return self.high_scores_room
def notify(self, event):
if isinstance(event, TickEvent):
self.render(self.screen)
pygame.display.update()
elif isinstance(event, SecondEvent):
pygame.display.set_caption(''.join(['FPS: ', str(int(event.fps))]))
elif isinstance(event, ChangeRoomRequest):
if event.game_mode:
config.game_mode = event.game_mode
self.room = self.set_room(event.new_room)
def render(self, surface):
self.room.render(surface)
def main():
pygame.init()
screen = pygame.display.set_mode(config.screen_size)
ev_manager = EventManager()
spinner = CPUSpinnerController(ev_manager)
room_controller = RoomController(screen, ev_manager)
pygame_event_controller = PyGameEventController(ev_manager)
spinner.run()
# this runs the main function if this script is called to run.
# If it is imported as a module, we don't run the main function.
if __name__ == "__main__":
# cProfile.run('main()', 'cprofile')
main()
A:
Well, temporarily "solved" this by adding a clear() function to my event manager, and calling that before every room switch, clearing out all listeners except for my three controllers:
def clear(self):
for listener in list(self.listeners):
if not isinstance(listener, CPUSpinnerController):
if not isinstance(listener, RoomController):
if not isinstance(listener, PyGameEventController):
self.unregister_listener(listener)
Doesn't seem like the best method though. If anyone has any insight as to why this isn't working, or why my event listener has to be manually cleared even though I'm using a weak ref dictionary to hold the listeners, I'd love to hear it.
|
Problem with room/screen/menu controller in python game: old rooms are not removed from memory
|
I'm literally banging my head against a wall here (as in, yes, physically, at my current location, I am damaging my cranium). Basically, I've got a Python/Pygame game with some typical game "rooms", or "screens." EG title screen, high scores screen, and the actual game room. Something bad is happening when I switch between rooms: the old room (and its various items) are not removed from memory, or from my event listener. Not only that, but every time I go back to a certain room, my number of event listeners increases, as well as the RAM being consumed! (So if I go back and forth between the title screen and the "game room", for instance, the number of event listeners and the memory usage just keep going up and up.
The main issue is that all the event listeners start to add up and really drain the CPU. I'm new to Python, and don't know if I'm doing something obviously wrong here, or what.
I will love you so much if you can help me with this!
Below is the relevant source code. Complete source code at http://www.necessarygames.com/my_games/betraveled/betraveled_src0328.zip
(Requires Python 2.6 + Pygame 1.9)
MAIN.PY
class RoomController(object):
"""Controls which room is currently active (eg Title Screen)"""
def __init__(self, screen, ev_manager):
self.room = None
self.screen = screen
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
self.room = self.set_room(config.room)
def set_room(self, room_const):
#Unregister old room from ev_manager
if self.room:
self.room.ev_manager.unregister_listener(self.room)
self.room = None
#Set new room based on const
if room_const == config.TITLE_SCREEN:
return rooms.TitleScreen(self.screen, self.ev_manager)
elif room_const == config.GAME_MODE_ROOM:
return rooms.GameModeRoom(self.screen, self.ev_manager)
elif room_const == config.GAME_ROOM:
return rooms.GameRoom(self.screen, self.ev_manager)
elif room_const == config.HIGH_SCORES_ROOM:
return rooms.HighScoresRoom(self.screen, self.ev_manager)
def notify(self, event):
if isinstance(event, ChangeRoomRequest):
if event.game_mode:
config.game_mode = event.game_mode
self.room = self.set_room(event.new_room)
#Run game
def main():
pygame.init()
screen = pygame.display.set_mode(config.screen_size)
ev_manager = EventManager()
spinner = CPUSpinnerController(ev_manager)
room_controller = RoomController(screen, ev_manager)
pygame_event_controller = PyGameEventController(ev_manager)
spinner.run()
EVENT_MANAGER.PY
class EventManager:
#This object is responsible for coordinating most communication
#between the Model, View, and Controller.
def __init__(self):
from weakref import WeakKeyDictionary
self.last_listeners = {}
self.listeners = WeakKeyDictionary()
self.eventQueue= []
self.gui_app = None
#----------------------------------------------------------------------
def register_listener(self, listener):
self.listeners[listener] = 1
#----------------------------------------------------------------------
def unregister_listener(self, listener):
if listener in self.listeners:
del self.listeners[listener]
#----------------------------------------------------------------------
def clear(self):
del self.listeners[:]
#----------------------------------------------------------------------
def post(self, event):
# if isinstance(event, MouseButtonLeftEvent):
# debug(event.name)
#NOTE: copying the list like this before iterating over it, EVERY tick, is highly inefficient,
#but currently has to be done because of how new listeners are added to the queue while it is running
#(eg when popping cards from a deck). Should be changed. See: http://dr0id.homepage.bluewin.ch/pygame_tutorial08.html
#and search for "Watch the iteration"
print 'Number of listeners: ' + str(len(self.listeners))
for listener in list(self.listeners):
#NOTE: If the weakref has died, it will be
#automatically removed, so we don't have
#to worry about it.
listener.notify(event)
def notify(self, event):
pass
#------------------------------------------------------------------------------
class PyGameEventController:
"""..."""
def __init__(self, ev_manager):
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
self.input_freeze = False
#----------------------------------------------------------------------
def notify(self, incoming_event):
if isinstance(incoming_event, UserInputFreeze):
self.input_freeze = True
elif isinstance(incoming_event, UserInputUnFreeze):
self.input_freeze = False
elif isinstance(incoming_event, TickEvent) or isinstance(incoming_event, BoardCreationTick):
#Share some time with other processes, so we don't hog the cpu
pygame.time.wait(5)
#Handle Pygame Events
for event in pygame.event.get():
#If this event manager has an associated PGU GUI app, notify it of the event
if self.ev_manager.gui_app:
self.ev_manager.gui_app.event(event)
#Standard event handling for everything else
ev = None
if event.type == QUIT:
ev = QuitEvent()
elif event.type == pygame.MOUSEBUTTONDOWN and not self.input_freeze:
if event.button == 1: #Button 1
pos = pygame.mouse.get_pos()
ev = MouseButtonLeftEvent(pos)
elif event.type == pygame.MOUSEBUTTONDOWN and not self.input_freeze:
if event.button == 2: #Button 2
pos = pygame.mouse.get_pos()
ev = MouseButtonRightEvent(pos)
elif event.type == pygame.MOUSEBUTTONUP and not self.input_freeze:
if event.button == 2: #Button 2 Release
pos = pygame.mouse.get_pos()
ev = MouseButtonRightReleaseEvent(pos)
elif event.type == pygame.MOUSEMOTION:
pos = pygame.mouse.get_pos()
ev = MouseMoveEvent(pos)
#Post event to event manager
if ev:
self.ev_manager.post(ev)
# elif isinstance(event, BoardCreationTick):
# #Share some time with other processes, so we don't hog the cpu
# pygame.time.wait(5)
#
# #If this event manager has an associated PGU GUI app, notify it of the event
# if self.ev_manager.gui_app:
# self.ev_manager.gui_app.event(event)
#------------------------------------------------------------------------------
class CPUSpinnerController:
def __init__(self, ev_manager):
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
self.clock = pygame.time.Clock()
self.cumu_time = 0
self.keep_going = True
#----------------------------------------------------------------------
def run(self):
if not self.keep_going:
raise Exception('dead spinner')
while self.keep_going:
time_passed = self.clock.tick()
fps = self.clock.get_fps()
self.cumu_time += time_passed
self.ev_manager.post(TickEvent(time_passed, fps))
if self.cumu_time >= 1000:
self.cumu_time = 0
self.ev_manager.post(SecondEvent(fps=fps))
pygame.quit()
#----------------------------------------------------------------------
def notify(self, event):
if isinstance(event, QuitEvent):
#this will stop the while loop from running
self.keep_going = False
EXAMPLE CLASS USING EVENT MANAGER
class Timer(object):
def __init__(self, ev_manager, time_left):
self.ev_manager = ev_manager
self.ev_manager.register_listener(self)
self.time_left = time_left
self.paused = False
def __repr__(self):
return str(self.time_left)
def pause(self):
self.paused = True
def unpause(self):
self.paused = False
def notify(self, event):
#Pause Event
if isinstance(event, Pause):
self.pause()
#Unpause Event
elif isinstance(event, Unpause):
self.unpause()
#Second Event
elif isinstance(event, SecondEvent):
if not self.paused:
self.time_left -= 1
|
[
"When you do something like this:\nreturn rooms.TitleScreen(self.screen, self.ev_manager) \n\nI'm assuming that you're creating a new TitleScreen object.\nIf this is what you want to do then you probably want to delete the old room object when switching rooms.\ndef notify(self, event):\n if isinstance(event, ChangeRoomRequest):\n if event.game_mode:\n config.game_mode = event.game_mode \n del self.room // delete the old room object\n self.room = self.set_room(event.new_room)\n\nIf you want the rooms to persist, your set_room function is going to be have to check to see if the room has already been created. Then you can create a new room or load the old one intelligently. But you will also have to keep track of these rooms somehow.\nEDIT:\nOK then. The problem isn't the rooms, it's listeners. Every listener you register on init should probably be unregistered on del. I did a search for 'unregister_listener' in your src and only found it unregistering the room listeners.\nSo when you create 100 buttons and then create 100 more without unregistering any listeners, you'll have 100 orphaned listeners. That's not good. I'd overload the __ del __ () function to remove those listeners just like the __ init __ () function adds them.\nDoes that make sense?\n",
"I've also tried keeping track of the rooms, instead of throwing them and creating new ones each time a new room request comes around. Unfortunately, this code isn't working for me either: when I return to the title screen from the game room, the title screen renders, but nothing responds to anything... I'm not sure what the problem is there... \nWatching the number of listeners, this doesn't seem to be solving the \"creep\" problem, as it goes from:\n1) Title Screen: 4 listeners active, to:\n2) Game mode select screen: 5 listeners active, to:\n3) Game room: 86 listeners active, to:\n4) Title Screen (unresponsive): 100 listeners active\nHere's the code I tried in MAIN.PY\nclass RoomController(object):\n \"\"\"Controls which room is currently active (eg Title Screen)\"\"\"\n\n def __init__(self, screen, ev_manager):\n self.room = None\n self.screen = screen\n self.ev_manager = ev_manager\n self.ev_manager.register_listener(self)\n\n self.title_screen = None\n self.game_mode_room = None\n self.game_room = None\n self.high_scores_room = None\n\n self.room = self.set_room(config.room)\n\n def set_room(self, room_const):\n #Set new room based on const\n if room_const == config.TITLE_SCREEN:\n if self.title_screen == None:\n self.title_screen = rooms.TitleScreen(self.screen, self.ev_manager)\n return self.title_screen\n elif room_const == config.GAME_MODE_ROOM:\n if self.game_mode_room == None:\n self.game_mode_room = rooms.GameModeRoom(self.screen, self.ev_manager) \n return self.game_mode_room \n elif room_const == config.GAME_ROOM:\n if self.game_room == None:\n self.game_room = rooms.GameRoom(self.screen, self.ev_manager)\n return self.game_room\n elif room_const == config.HIGH_SCORES_ROOM:\n if self.high_scores_room == None:\n self.high_scores_room = rooms.HighScoresRoom(self.screen, self.ev_manager)\n return self.high_scores_room \n\n def notify(self, event):\n if isinstance(event, TickEvent): \n self.render(self.screen) \n pygame.display.update()\n elif isinstance(event, SecondEvent):\n pygame.display.set_caption(''.join(['FPS: ', str(int(event.fps))])) \n elif isinstance(event, ChangeRoomRequest):\n if event.game_mode:\n config.game_mode = event.game_mode \n self.room = self.set_room(event.new_room)\n\n def render(self, surface):\n self.room.render(surface)\n\ndef main():\n pygame.init()\n screen = pygame.display.set_mode(config.screen_size)\n\n ev_manager = EventManager()\n spinner = CPUSpinnerController(ev_manager)\n room_controller = RoomController(screen, ev_manager) \n pygame_event_controller = PyGameEventController(ev_manager)\n\n spinner.run()\n\n\n# this runs the main function if this script is called to run.\n# If it is imported as a module, we don't run the main function.\nif __name__ == \"__main__\": \n# cProfile.run('main()', 'cprofile')\n main()\n\n",
"Well, temporarily \"solved\" this by adding a clear() function to my event manager, and calling that before every room switch, clearing out all listeners except for my three controllers:\ndef clear(self): \n for listener in list(self.listeners):\n if not isinstance(listener, CPUSpinnerController): \n if not isinstance(listener, RoomController): \n if not isinstance(listener, PyGameEventController): \n self.unregister_listener(listener)\n\nDoesn't seem like the best method though. If anyone has any insight as to why this isn't working, or why my event listener has to be manually cleared even though I'm using a weak ref dictionary to hold the listeners, I'd love to hear it. \n"
] |
[
1,
0,
0
] |
[] |
[] |
[
"event_handling",
"performance",
"pygame",
"python"
] |
stackoverflow_0002540437_event_handling_performance_pygame_python.txt
|
Q:
python on 32 bit
Hi I am running Windows XP, on 32bit. How do I install python? When I run the installation file, it gives me an error saying "installation package not supported by processor type" does python need 64 bit to execute?
A:
Your 32-bit options (for Windows) include ActivePython 2.6.5 and ActivePython 3.1.2 (ActivePython comes with some extras in addition to the standard python.org release), plain Python 2.6.5 and 3.1.2, and commercial solutions such as Enthought Python (ActiveState also offers commercial options, but the ones I pointed to are the free "community editions" -- python.org's offerings are also gratis, of course).
A:
No it doesn't require 64-bit. The download page has both 32-bit and 64-bit downloads.
|
python on 32 bit
|
Hi I am running Windows XP, on 32bit. How do I install python? When I run the installation file, it gives me an error saying "installation package not supported by processor type" does python need 64 bit to execute?
|
[
"Your 32-bit options (for Windows) include ActivePython 2.6.5 and ActivePython 3.1.2 (ActivePython comes with some extras in addition to the standard python.org release), plain Python 2.6.5 and 3.1.2, and commercial solutions such as Enthought Python (ActiveState also offers commercial options, but the ones I pointed to are the free \"community editions\" -- python.org's offerings are also gratis, of course).\n",
"No it doesn't require 64-bit. The download page has both 32-bit and 64-bit downloads.\n"
] |
[
4,
3
] |
[] |
[] |
[
"python",
"windows_xp"
] |
stackoverflow_0002543120_python_windows_xp.txt
|
Q:
Pylons: Set global variable for Authkit user
How can I can set a global variable for the username of the logged-in user? At the moment i have the following code in all my controllers to get the username. I rather set it as a global variable if possible.
request.environ.get("REMOTE_USER")
I tried putting the same code in the app_globals.py file but it gave me the following error message:
"No object (name: request) has been registered for this thread"
A:
There is no single "logged-in user" if you're serving requests on multiple threads -- by setting a single global variable the threads would trample upon each other and end up very very confused on who "the logged-in user" actually is. There is (at most;-) a single logged-in user per request, so keeping that info in the request object seems vastly preferable;-).
|
Pylons: Set global variable for Authkit user
|
How can I can set a global variable for the username of the logged-in user? At the moment i have the following code in all my controllers to get the username. I rather set it as a global variable if possible.
request.environ.get("REMOTE_USER")
I tried putting the same code in the app_globals.py file but it gave me the following error message:
"No object (name: request) has been registered for this thread"
|
[
"There is no single \"logged-in user\" if you're serving requests on multiple threads -- by setting a single global variable the threads would trample upon each other and end up very very confused on who \"the logged-in user\" actually is. There is (at most;-) a single logged-in user per request, so keeping that info in the request object seems vastly preferable;-).\n"
] |
[
1
] |
[] |
[] |
[
"authkit",
"pylons",
"python"
] |
stackoverflow_0002543315_authkit_pylons_python.txt
|
Q:
Python's equivalence?
Is there anyway to transform the following code in Java to Python's equivalence?
public class Animal{
public enum AnimalBreed{
Dog, Cat, Cow, Chicken, Elephant
}
private static final int Animals = AnimalBreed.Dog.ordinal();
private static final String[] myAnimal = new String[Animals];
private static Animal[] animal = new Animal[Animals];
public static final Animal DogAnimal = new Animal(AnimalBreed.Dog, "woff");
public static final Animal CatAnimal = new Animal(AnimalBreed.Cat, "meow");
private AnimalBreed breed;
public static Animal myDog (String name) {
return new Animal(AnimalBreed.Dog, name);
}
}
A:
Translating this code directly would be a waste of time. The hardest thing when moving from Java to Python is giving up most of what you know. But the simple fact is that Python is not Java, and translating line by line won't work as you expect. It's better to translate algorithms rather than code, and let Python do what it's good at.
A:
It's unclear to me what the desired semantics of your Java would be. I'm guessing you're sort of trying to model a collection of animals (species, not breeds, incidentally) and imbue a set of associated classes with the behavior that varies according to the type of animal (roughly speaking the sounds that each makes).
In Python the natural way to do this would be through meta programming. You create a class or a factory function which returns each of the classes by passing arguments into a template. Since functions and classes are first order object in Python they can be passed around like any other object. Since classes are themselves objects you can access their attributes using setattr (and its cousins: hasattr and getattr).
Here's a simple example:
#!/usr/bin/env python
def Animal(species, sound):
class meta: pass
def makeSound(meta, sound=sound):
print sound
setattr(meta, makeSound.__name__, makeSound)
def name(meta, myname=species):
return myname
setattr(meta, 'name', name)
return meta
if __name__ == '__main__':
animal_sounds = (('Dog', 'woof'),
('Cat', 'meow'),
('Cow', 'moo'),
('Chicken', 'cluck'),
('Elephant', 'eraunngh'))
menagerie = dict()
for animal, sound in animal_sounds:
menagerie[animal] = Animal(animal, sound)
for Beast in menagerie:
beast = Beast()
print beast.name(), ' says ',
beast.makeSound()
Dog = menagerie['Dog']
fido = Dog() # equivalent to fido = menagerie['Dog']()
fido.makeSound()
# prints "woof"
Cat = menagerie['Cat']
felix = Cat()
felix.makeSound()
Mouse = Animal('Mouse', 'squeak')
mickey = Mouse()
mouse.makeSound()
# prints "squeak"
This seems like a trite example but I hope it gets the point across. I can create a table (in this case a tuple of tuples) which provides the arguments which will be used to fill in the varying parameters/behavior of our classes. The classes returned by Animal are just like any other Python classes. I've tried to show that in the examples here.
A:
This is not a line-for-line translation, but something in the ballpark:
class Animal(object):
animal_breeds = "Dog Cat Cow Chicken Elephant".split()
animals = {}
def __init__(self, breed, name):
self._breed = breed
self.name = name
Animal.animals[name] = self
@property
def breed(self):
return Animal.animal_breeds[self._breed]
@staticmethod
def myDog(name):
return Animal(Animal.AnimalBreed.Dog, name)
# add enumeration of Animal breeds to Animal class
class Constants(object): pass
Animal.AnimalBreed = Constants()
for i,b in enumerate(Animal.animal_breeds):
setattr(Animal.AnimalBreed, b, i)
# define some class-level constant animals
# (although "woff" and "meow" are not what I would expect
# for names of animals)
Animal.DogAnimal = Animal(Animal.AnimalBreed.Dog, "woff")
Animal.CatAnimal = Animal(Animal.AnimalBreed.Cat, "meow")
# this code would be in a separate module that would import this
# code using
# from animal import Animal
#
print Animal.myDog("Rex").breed
print Animal.animals.keys()
A:
http://code.activestate.com/recipes/413486/ contains a lot of help on this topic. Be warned that deepcopy support probably doesn't work with it.
|
Python's equivalence?
|
Is there anyway to transform the following code in Java to Python's equivalence?
public class Animal{
public enum AnimalBreed{
Dog, Cat, Cow, Chicken, Elephant
}
private static final int Animals = AnimalBreed.Dog.ordinal();
private static final String[] myAnimal = new String[Animals];
private static Animal[] animal = new Animal[Animals];
public static final Animal DogAnimal = new Animal(AnimalBreed.Dog, "woff");
public static final Animal CatAnimal = new Animal(AnimalBreed.Cat, "meow");
private AnimalBreed breed;
public static Animal myDog (String name) {
return new Animal(AnimalBreed.Dog, name);
}
}
|
[
"Translating this code directly would be a waste of time. The hardest thing when moving from Java to Python is giving up most of what you know. But the simple fact is that Python is not Java, and translating line by line won't work as you expect. It's better to translate algorithms rather than code, and let Python do what it's good at.\n",
"It's unclear to me what the desired semantics of your Java would be. I'm guessing you're sort of trying to model a collection of animals (species, not breeds, incidentally) and imbue a set of associated classes with the behavior that varies according to the type of animal (roughly speaking the sounds that each makes).\nIn Python the natural way to do this would be through meta programming. You create a class or a factory function which returns each of the classes by passing arguments into a template. Since functions and classes are first order object in Python they can be passed around like any other object. Since classes are themselves objects you can access their attributes using setattr (and its cousins: hasattr and getattr).\nHere's a simple example:\n#!/usr/bin/env python\ndef Animal(species, sound):\n class meta: pass\n\n def makeSound(meta, sound=sound):\n print sound\n setattr(meta, makeSound.__name__, makeSound)\n\n def name(meta, myname=species):\n return myname\n setattr(meta, 'name', name)\n return meta\n\nif __name__ == '__main__':\n animal_sounds = (('Dog', 'woof'),\n ('Cat', 'meow'),\n ('Cow', 'moo'),\n ('Chicken', 'cluck'),\n ('Elephant', 'eraunngh'))\n\n menagerie = dict()\n for animal, sound in animal_sounds:\n menagerie[animal] = Animal(animal, sound)\n\n for Beast in menagerie:\n beast = Beast()\n print beast.name(), ' says ',\n beast.makeSound()\n\n Dog = menagerie['Dog']\n fido = Dog() # equivalent to fido = menagerie['Dog']()\n fido.makeSound()\n # prints \"woof\"\n Cat = menagerie['Cat']\n felix = Cat()\n felix.makeSound()\n Mouse = Animal('Mouse', 'squeak')\n mickey = Mouse()\n mouse.makeSound()\n # prints \"squeak\"\n\nThis seems like a trite example but I hope it gets the point across. I can create a table (in this case a tuple of tuples) which provides the arguments which will be used to fill in the varying parameters/behavior of our classes. The classes returned by Animal are just like any other Python classes. I've tried to show that in the examples here.\n",
"This is not a line-for-line translation, but something in the ballpark:\nclass Animal(object):\n animal_breeds = \"Dog Cat Cow Chicken Elephant\".split()\n animals = {}\n\n def __init__(self, breed, name):\n self._breed = breed\n self.name = name\n Animal.animals[name] = self\n\n @property\n def breed(self):\n return Animal.animal_breeds[self._breed]\n\n @staticmethod\n def myDog(name):\n return Animal(Animal.AnimalBreed.Dog, name)\n\n# add enumeration of Animal breeds to Animal class\nclass Constants(object): pass\nAnimal.AnimalBreed = Constants()\nfor i,b in enumerate(Animal.animal_breeds):\n setattr(Animal.AnimalBreed, b, i)\n\n# define some class-level constant animals\n# (although \"woff\" and \"meow\" are not what I would expect\n# for names of animals) \nAnimal.DogAnimal = Animal(Animal.AnimalBreed.Dog, \"woff\")\nAnimal.CatAnimal = Animal(Animal.AnimalBreed.Cat, \"meow\")\n\n# this code would be in a separate module that would import this\n# code using\n# from animal import Animal\n#\nprint Animal.myDog(\"Rex\").breed\nprint Animal.animals.keys()\n\n",
"http://code.activestate.com/recipes/413486/ contains a lot of help on this topic. Be warned that deepcopy support probably doesn't work with it.\n"
] |
[
7,
2,
1,
0
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002536318_python.txt
|
Q:
Do you know any Augmented Reality library for python?
I would like to code something with augmented reality, do you know any python library to play with?
A:
OpenCV would be the closest match I can think of ...
A:
ARToolKit apparently has python bindings:
http://www.hitlabnz.org/forum/showthread.php?548-PyARTK-0.1-Python-binding-for-ARToolKit-released
I've not experimented, ymmv.
|
Do you know any Augmented Reality library for python?
|
I would like to code something with augmented reality, do you know any python library to play with?
|
[
"OpenCV would be the closest match I can think of ...\n",
"ARToolKit apparently has python bindings:\nhttp://www.hitlabnz.org/forum/showthread.php?548-PyARTK-0.1-Python-binding-for-ARToolKit-released\nI've not experimented, ymmv.\n"
] |
[
3,
1
] |
[] |
[] |
[
"augmented_reality",
"python"
] |
stackoverflow_0002543520_augmented_reality_python.txt
|
Q:
In python, what is the fastest way to determine if a string is an email or an integer?
I'd like to be able to pull users from a database using either a supplied e-mail address or the user id (an integer). To do this, I have to detect if the supplied string is an integer, or an e-mail. Looking for the fastest way to do this. Thanks.
def __init__(self, data):
#populate class data
self._fetchInfo(data)
def _fetchInfo(self, data):
#If an email
#SELECT ... WHERE email = 'data'
#or if a user_id
#SELECT ... WHERE id = 'data'
#Fill class attributes
self._id = row['id']
self._email = row['id']
...
A:
The canonical way to handle this in Python is to try first, ask forgiveness later:
def _fetchInfo(self, data):
try:
data=int(data)
sql='SELECT ... WHERE id = %s'
args=[data]
except ValueError:
sql='SELECT ... WHERE email = %s'
args=[data]
# This might fail, in which case, data was neither a valid integer or email address
This strategy also goes by the moniker "It is Easier to Ask for Forgiveness than Permission".
A:
You can use the isinstance function:
if isinstance(data, int):
# it's an id
else:
# it's a string
Though personally, I'd just have two methods, fetchById and fetchByEmail to make it clear that's how it works.
A:
You said both were strings, right? This would work, too.
if data.isdigit():
# it's an id
else:
# it's not
A:
if '@' in data:
# email
else:
# id
|
In python, what is the fastest way to determine if a string is an email or an integer?
|
I'd like to be able to pull users from a database using either a supplied e-mail address or the user id (an integer). To do this, I have to detect if the supplied string is an integer, or an e-mail. Looking for the fastest way to do this. Thanks.
def __init__(self, data):
#populate class data
self._fetchInfo(data)
def _fetchInfo(self, data):
#If an email
#SELECT ... WHERE email = 'data'
#or if a user_id
#SELECT ... WHERE id = 'data'
#Fill class attributes
self._id = row['id']
self._email = row['id']
...
|
[
"The canonical way to handle this in Python is to try first, ask forgiveness later: \ndef _fetchInfo(self, data):\n try:\n data=int(data)\n sql='SELECT ... WHERE id = %s'\n args=[data]\n except ValueError:\n sql='SELECT ... WHERE email = %s'\n args=[data]\n # This might fail, in which case, data was neither a valid integer or email address\n\nThis strategy also goes by the moniker \"It is Easier to Ask for Forgiveness than Permission\".\n",
"You can use the isinstance function:\nif isinstance(data, int):\n # it's an id\nelse:\n # it's a string\n\nThough personally, I'd just have two methods, fetchById and fetchByEmail to make it clear that's how it works.\n",
"You said both were strings, right? This would work, too.\nif data.isdigit():\n # it's an id\nelse:\n # it's not\n\n",
"if '@' in data:\n # email\nelse:\n # id\n\n"
] |
[
4,
2,
2,
1
] |
[] |
[] |
[
"integer",
"python",
"string"
] |
stackoverflow_0002542642_integer_python_string.txt
|
Q:
Django Distinct on queryset in forms.py
I try to get a list with distinct into the forms.py like this:
forms.ModelMultipleChoiceField(queryset=Events.objects.values('hostname'), required=False).distinct()
In the python shell this command works perfect, but when trying it in forms.py leaves me a blank form, so nothing appears. When i just do Events.objects.all() the form appears, but distinct doesn't work with Events.objects.all()... i also tried values_list etc but doesn't seem to fit into the forms neither... anyone got an idea how to get a SELECT DISTINCT into a ModelMultipleChoiceField?
I read some other questions about this at stackoverflow but nothing seems to work out with me, so hopefully someone knows how to do this in forms.py.
Thxs in advance
A:
For a ModelMultipleChoiceField, Django expects a model object - because it stores the value of the selected item's primary key. In other words, it's meant to be used to manage ManyToMany fields.
It sounds like you're wanting to store the actual string value, so this might not be the right choice for you. You probably want to use a standard MultipleChoiceField, and override the form's __init__ method to set the field's choices attribute. Remember though that any choice field is a set of 2-tuples, each containing the db value and the display value - so even though you want them to be the same, you'll need to include the value twice:
def __init__(self, *args, **kwargs):
super(MyFormClass, self).__init__(*args, **kwargs)
self.fields['mychoicefield'].choices = [(x[0], x[0]) for x in
Event.objects.values_list('hostname').distinct()])
|
Django Distinct on queryset in forms.py
|
I try to get a list with distinct into the forms.py like this:
forms.ModelMultipleChoiceField(queryset=Events.objects.values('hostname'), required=False).distinct()
In the python shell this command works perfect, but when trying it in forms.py leaves me a blank form, so nothing appears. When i just do Events.objects.all() the form appears, but distinct doesn't work with Events.objects.all()... i also tried values_list etc but doesn't seem to fit into the forms neither... anyone got an idea how to get a SELECT DISTINCT into a ModelMultipleChoiceField?
I read some other questions about this at stackoverflow but nothing seems to work out with me, so hopefully someone knows how to do this in forms.py.
Thxs in advance
|
[
"For a ModelMultipleChoiceField, Django expects a model object - because it stores the value of the selected item's primary key. In other words, it's meant to be used to manage ManyToMany fields.\nIt sounds like you're wanting to store the actual string value, so this might not be the right choice for you. You probably want to use a standard MultipleChoiceField, and override the form's __init__ method to set the field's choices attribute. Remember though that any choice field is a set of 2-tuples, each containing the db value and the display value - so even though you want them to be the same, you'll need to include the value twice:\ndef __init__(self, *args, **kwargs):\n super(MyFormClass, self).__init__(*args, **kwargs)\n self.fields['mychoicefield'].choices = [(x[0], x[0]) for x in\n Event.objects.values_list('hostname').distinct()])\n\n"
] |
[
0
] |
[] |
[] |
[
"distinct",
"django",
"forms",
"python"
] |
stackoverflow_0002543672_distinct_django_forms_python.txt
|
Q:
How to call Twitter's Streaming/Filter Feed with urllib2/httplib?
Update:
I switched this back from answered as I tried the solution posed in cogent Nick's answer and switched to Google's urlfetch:
logging.debug("starting urlfetch for http://%s%s" % (self.host, self.url))
result = urlfetch.fetch("http://%s%s" % (self.host, self.url), payload=self.body, method="POST", headers=self.headers, allow_truncated=True, deadline=5)
logging.debug("finished urlfetch")
but unfortunately finished urlfetch is never printed - I see the timeout happen in the logs (it returns 200 after 5 seconds), but execution doesn't seem tor return.
Hi All-
I'm attempting to play around with Twitter's Streaming (aka firehose) API with Google App Engine (I'm aware this probably isn't a great long term play as you can't keep the connection perpetually open with GAE), but so far I haven't had any luck getting my program to actually parse the results returned by Twitter.
Some code:
logging.debug("firing up urllib2")
req = urllib2.Request(url="http://%s%s" % (self.host, self.url), data=self.body, headers=self.headers)
logging.debug("called urlopen for %s %s, about to call urlopen" % (self.host, self.url))
fobj = urllib2.urlopen(req)
logging.debug("called urlopen")
When this executes, unfortunately, my debug output never shows the called urlopen line printed. I suspect what's happening is that Twitter keeps the connection open and urllib2 doesn't return because the server doesn't terminate the connection.
Wireshark shows the request being sent properly and a response returned with results.
I tried adding Connection: close to my request header, but that didn't yield a successful result.
Any ideas on how to get this to work?
A:
urllib on App Engine is a thin wrapper around the urlfetch API. You're right about what's happening: Twitter's streaming API never terminates its response, so it times out, and urlfetch throws an exception.
If you use urlfetch directly, you can set the timeout (up to 10 seconds), and set allow_truncated to True so you can get the partial result. The Twitter streaming API really isn't a good match for App Engine, though, because App Engine requests are limited to 30 seconds of execution time, and urlfetch requests can't send back results progressively, or take more than 10 seconds. Using Twitter's 'standard' API would be a better option.
|
How to call Twitter's Streaming/Filter Feed with urllib2/httplib?
|
Update:
I switched this back from answered as I tried the solution posed in cogent Nick's answer and switched to Google's urlfetch:
logging.debug("starting urlfetch for http://%s%s" % (self.host, self.url))
result = urlfetch.fetch("http://%s%s" % (self.host, self.url), payload=self.body, method="POST", headers=self.headers, allow_truncated=True, deadline=5)
logging.debug("finished urlfetch")
but unfortunately finished urlfetch is never printed - I see the timeout happen in the logs (it returns 200 after 5 seconds), but execution doesn't seem tor return.
Hi All-
I'm attempting to play around with Twitter's Streaming (aka firehose) API with Google App Engine (I'm aware this probably isn't a great long term play as you can't keep the connection perpetually open with GAE), but so far I haven't had any luck getting my program to actually parse the results returned by Twitter.
Some code:
logging.debug("firing up urllib2")
req = urllib2.Request(url="http://%s%s" % (self.host, self.url), data=self.body, headers=self.headers)
logging.debug("called urlopen for %s %s, about to call urlopen" % (self.host, self.url))
fobj = urllib2.urlopen(req)
logging.debug("called urlopen")
When this executes, unfortunately, my debug output never shows the called urlopen line printed. I suspect what's happening is that Twitter keeps the connection open and urllib2 doesn't return because the server doesn't terminate the connection.
Wireshark shows the request being sent properly and a response returned with results.
I tried adding Connection: close to my request header, but that didn't yield a successful result.
Any ideas on how to get this to work?
|
[
"urllib on App Engine is a thin wrapper around the urlfetch API. You're right about what's happening: Twitter's streaming API never terminates its response, so it times out, and urlfetch throws an exception.\nIf you use urlfetch directly, you can set the timeout (up to 10 seconds), and set allow_truncated to True so you can get the partial result. The Twitter streaming API really isn't a good match for App Engine, though, because App Engine requests are limited to 30 seconds of execution time, and urlfetch requests can't send back results progressively, or take more than 10 seconds. Using Twitter's 'standard' API would be a better option.\n"
] |
[
1
] |
[] |
[] |
[
"google_app_engine",
"python",
"twitter_feed"
] |
stackoverflow_0002543339_google_app_engine_python_twitter_feed.txt
|
Q:
Average of two strings in alphabetical/lexicographical order
Suppose you take the strings 'a' and 'z' and list all the strings that come between them in alphabetical order: ['a','b','c' ... 'x','y','z']. Take the midpoint of this list and you find 'm'. So this is kind of like taking an average of those two strings.
You could extend it to strings with more than one character, for example the midpoint between 'aa' and 'zz' would be found in the middle of the list ['aa', 'ab', 'ac' ... 'zx', 'zy', 'zz'].
Might there be a Python method somewhere that does this? If not, even knowing the name of the algorithm would help.
I began making my own routine that simply goes through both strings and finds midpoint of the first differing letter, which seemed to work great in that 'aa' and 'az' midpoint was 'am', but then it fails on 'cat', 'doggie' midpoint which it thinks is 'c'. I tried Googling for "binary search string midpoint" etc. but without knowing the name of what I am trying to do here I had little luck.
I added my own solution as an answer
A:
If you define an alphabet of characters, you can just convert to base 10, do an average, and convert back to base-N where N is the size of the alphabet.
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def enbase(x):
n = len(alphabet)
if x < n:
return alphabet[x]
return enbase(x/n) + alphabet[x%n]
def debase(x):
n = len(alphabet)
result = 0
for i, c in enumerate(reversed(x)):
result += alphabet.index(c) * (n**i)
return result
def average(a, b):
a = debase(a)
b = debase(b)
return enbase((a + b) / 2)
print average('a', 'z') #m
print average('aa', 'zz') #mz
print average('cat', 'doggie') #budeel
print average('google', 'microsoft') #gebmbqkil
print average('microsoft', 'google') #gebmbqkil
Edit: Based on comments and other answers, you might want to handle strings of different lengths by appending the first letter of the alphabet to the shorter word until they're the same length. This will result in the "average" falling between the two inputs in a lexicographical sort. Code changes and new outputs below.
def pad(x, n):
p = alphabet[0] * (n - len(x))
return '%s%s' % (x, p)
def average(a, b):
n = max(len(a), len(b))
a = debase(pad(a, n))
b = debase(pad(b, n))
return enbase((a + b) / 2)
print average('a', 'z') #m
print average('aa', 'zz') #mz
print average('aa', 'az') #m (equivalent to ma)
print average('cat', 'doggie') #cumqec
print average('google', 'microsoft') #jlilzyhcw
print average('microsoft', 'google') #jlilzyhcw
A:
It sounds like what you want, is to treat alphabetical characters as a base-26 value between 0 and 1. When you have strings of different length (an example in base 10), say 305 and 4202, your coming out with a midpoint of 3, since you're looking at the characters one at a time. Instead, treat them as a floating point mantissa: 0.305 and 0.4202. From that, it's easy to come up with a midpoint of .3626 (you can round if you'd like).
Do the same with base 26 (a=0...z=25, ba=26, bb=27, etc.) to do the calculations for letters:
cat becomes 'a.cat' and doggie becomes 'a.doggie', doing the math gives cat a decimal value of 0.078004096, doggie a value of 0.136390697, with an average of 0.107197397 which in base 26 is roughly "cumcqo"
A:
If you mean the alphabetically, simply use FogleBird's algorithm but reverse the parameters and the result!
>>> print average('cat'[::-1], 'doggie'[::-1])[::-1]
cumdec
or rewriting average like so
>>> def average(a, b):
... a = debase(a[::-1])
... b = debase(b[::-1])
... return enbase((a + b) / 2)[::-1]
...
>>> print average('cat', 'doggie')
cumdec
>>> print average('google', 'microsoft')
jlvymlupj
>>> print average('microsoft', 'google')
jlvymlupj
A:
Based on your proposed usage, consistent hashing ( http://en.wikipedia.org/wiki/Consistent_hashing ) seems to make more sense.
A:
Thanks for everyone who answered, but I ended up writing my own solution because the others weren't exactly what I needed. I am trying to average app engine key names, and after studying them a bit more I discovered they actually allow any 7-bit ASCII characters in the names. Additionally I couldn't really rely on the solutions that converted the key names first to floating point, because I suspected floating point accuracy just isn't enough.
To take an average, first you add two numbers together and then divide by two. These are both such simple operations that I decided to just make functions to add and divide base 128 numbers represented as lists. This solution hasn't been used in my system yet so I might still find some bugs in it. Also it could probably be a lot shorter, but this is just something I needed to get done instead of trying to make it perfect.
# Given two lists representing a number with one digit left to decimal point and the
# rest after it, for example 1.555 = [1,5,5,5] and 0.235 = [0,2,3,5], returns a similar
# list representing those two numbers added together.
#
def ladd(a, b, base=128):
i = max(len(a), len(b))
lsum = [0] * i
while i > 1:
i -= 1
av = bv = 0
if i < len(a): av = a[i]
if i < len(b): bv = b[i]
lsum[i] += av + bv
if lsum[i] >= base:
lsum[i] -= base
lsum[i-1] += 1
return lsum
# Given a list of digits after the decimal point, returns a new list of digits
# representing that number divided by two.
#
def ldiv2(vals, base=128):
vs = vals[:]
vs.append(0)
i = len(vs)
while i > 0:
i -= 1
if (vs[i] % 2) == 1:
vs[i] -= 1
vs[i+1] += base / 2
vs[i] = vs[i] / 2
if vs[-1] == 0: vs = vs[0:-1]
return vs
# Given two app engine key names, returns the key name that comes between them.
#
def average(a_kn, b_kn):
m = lambda x:ord(x)
a = [0] + map(m, a_kn)
b = [0] + map(m, b_kn)
avg = ldiv2(ladd(a, b))
return "".join(map(lambda x:chr(x), avg[1:]))
print average('a', 'z') # m@
print average('aa', 'zz') # n-@
print average('aa', 'az') # am@
print average('cat', 'doggie') # d(mstr@
print average('google', 'microsoft') # jlim.,7s:
print average('microsoft', 'google') # jlim.,7s:
A:
import math
def avg(str1,str2):
y = ''
s = 'abcdefghijklmnopqrstuvwxyz'
for i in range(len(str1)):
x = s.index(str2[i])+s.index(str1[i])
x = math.floor(x/2)
y += s[x]
return y
print(avg('z','a')) # m
print(avg('aa','az')) # am
print(avg('cat','dog')) # chm
Still working on strings with different lengths... any ideas?
A:
This version thinks 'abc' is a fraction like 0.abc. In this approach space is zero and a valid input/output.
MAX_ITER = 10
letters = " abcdefghijklmnopqrstuvwxyz"
def to_double(name):
d = 0
for i, ch in enumerate(name):
idx = letters.index(ch)
d += idx * len(letters) ** (-i - 1)
return d
def from_double(d):
name = ""
for i in range(MAX_ITER):
d *= len(letters)
name += letters[int(d)]
d -= int(d)
return name
def avg(w1, w2):
w1 = to_double(w1)
w2 = to_double(w2)
return from_double((w1 + w2) * 0.5)
print avg('a', 'a') # 'a'
print avg('a', 'aa') # 'a mmmmmmmm'
print avg('aa', 'aa') # 'a zzzzzzzz'
print avg('car', 'duck') # 'cxxemmmmmm'
Unfortunately, the naïve algorithm is not able to detect the periodic 'z's, this would be something like 0.99999 in decimal; therefore 'a zzzzzzzz' is actually 'aa' (the space before the 'z' periodicity must be increased by one.
In order to normalise this, you can use the following function
def remove_z_period(name):
if len(name) != MAX_ITER:
return name
if name[-1] != 'z':
return name
n = ""
overflow = True
for ch in reversed(name):
if overflow:
if ch == 'z':
ch = ' '
else:
ch=letters[(letters.index(ch)+1)]
overflow = False
n = ch + n
return n
print remove_z_period('a zzzzzzzz') # 'aa'
A:
I haven't programmed in python in a while and this seemed interesting enough to try.
Bear with my recursive programming. Too many functional languages look like python.
def stravg_half(a, ln):
# If you have a problem it will probably be in here.
# The floor of the character's value is 0, but you may want something different
f = 0
#f = ord('a')
L = ln - 1
if 0 == L:
return ''
A = ord(a[0])
return chr(A/2) + stravg_half( a[1:], L)
def stravg_helper(a, b, ln, x):
L = ln - 1
A = ord(a[0])
B = ord(b[0])
D = (A + B)/2
if 0 == L:
if 0 == x:
return chr(D)
# NOTE: The caller of helper makes sure that len(a)>=len(b)
return chr(D) + stravg_half(a[1:], x)
return chr(D) + stravg_helper(a[1:], b[1:], L, x)
def stravg(a, b):
la = len(a)
lb = len(b)
if 0 == la:
if 0 == lb:
return a # which is empty
return stravg_half(b, lb)
if 0 == lb:
return stravg_half(a, la)
x = la - lb
if x > 0:
return stravg_helper(a, b, lb, x)
return stravg_helper(b, a, la, -x) # Note the order of the args
|
Average of two strings in alphabetical/lexicographical order
|
Suppose you take the strings 'a' and 'z' and list all the strings that come between them in alphabetical order: ['a','b','c' ... 'x','y','z']. Take the midpoint of this list and you find 'm'. So this is kind of like taking an average of those two strings.
You could extend it to strings with more than one character, for example the midpoint between 'aa' and 'zz' would be found in the middle of the list ['aa', 'ab', 'ac' ... 'zx', 'zy', 'zz'].
Might there be a Python method somewhere that does this? If not, even knowing the name of the algorithm would help.
I began making my own routine that simply goes through both strings and finds midpoint of the first differing letter, which seemed to work great in that 'aa' and 'az' midpoint was 'am', but then it fails on 'cat', 'doggie' midpoint which it thinks is 'c'. I tried Googling for "binary search string midpoint" etc. but without knowing the name of what I am trying to do here I had little luck.
I added my own solution as an answer
|
[
"If you define an alphabet of characters, you can just convert to base 10, do an average, and convert back to base-N where N is the size of the alphabet.\nalphabet = 'abcdefghijklmnopqrstuvwxyz'\n\ndef enbase(x):\n n = len(alphabet)\n if x < n:\n return alphabet[x]\n return enbase(x/n) + alphabet[x%n]\n\ndef debase(x):\n n = len(alphabet)\n result = 0\n for i, c in enumerate(reversed(x)):\n result += alphabet.index(c) * (n**i)\n return result\n\ndef average(a, b):\n a = debase(a)\n b = debase(b)\n return enbase((a + b) / 2)\n\nprint average('a', 'z') #m\nprint average('aa', 'zz') #mz\nprint average('cat', 'doggie') #budeel\nprint average('google', 'microsoft') #gebmbqkil\nprint average('microsoft', 'google') #gebmbqkil\n\nEdit: Based on comments and other answers, you might want to handle strings of different lengths by appending the first letter of the alphabet to the shorter word until they're the same length. This will result in the \"average\" falling between the two inputs in a lexicographical sort. Code changes and new outputs below.\ndef pad(x, n):\n p = alphabet[0] * (n - len(x)) \n return '%s%s' % (x, p)\n\ndef average(a, b):\n n = max(len(a), len(b))\n a = debase(pad(a, n))\n b = debase(pad(b, n))\n return enbase((a + b) / 2)\n\nprint average('a', 'z') #m\nprint average('aa', 'zz') #mz\nprint average('aa', 'az') #m (equivalent to ma)\nprint average('cat', 'doggie') #cumqec\nprint average('google', 'microsoft') #jlilzyhcw\nprint average('microsoft', 'google') #jlilzyhcw\n\n",
"It sounds like what you want, is to treat alphabetical characters as a base-26 value between 0 and 1. When you have strings of different length (an example in base 10), say 305 and 4202, your coming out with a midpoint of 3, since you're looking at the characters one at a time. Instead, treat them as a floating point mantissa: 0.305 and 0.4202. From that, it's easy to come up with a midpoint of .3626 (you can round if you'd like).\nDo the same with base 26 (a=0...z=25, ba=26, bb=27, etc.) to do the calculations for letters:\ncat becomes 'a.cat' and doggie becomes 'a.doggie', doing the math gives cat a decimal value of 0.078004096, doggie a value of 0.136390697, with an average of 0.107197397 which in base 26 is roughly \"cumcqo\"\n",
"If you mean the alphabetically, simply use FogleBird's algorithm but reverse the parameters and the result!\n>>> print average('cat'[::-1], 'doggie'[::-1])[::-1]\ncumdec\n\nor rewriting average like so\n>>> def average(a, b):\n... a = debase(a[::-1])\n... b = debase(b[::-1])\n... return enbase((a + b) / 2)[::-1]\n... \n>>> print average('cat', 'doggie')\ncumdec\n>>> print average('google', 'microsoft') \njlvymlupj\n>>> print average('microsoft', 'google') \njlvymlupj\n\n",
"Based on your proposed usage, consistent hashing ( http://en.wikipedia.org/wiki/Consistent_hashing ) seems to make more sense.\n",
"Thanks for everyone who answered, but I ended up writing my own solution because the others weren't exactly what I needed. I am trying to average app engine key names, and after studying them a bit more I discovered they actually allow any 7-bit ASCII characters in the names. Additionally I couldn't really rely on the solutions that converted the key names first to floating point, because I suspected floating point accuracy just isn't enough.\nTo take an average, first you add two numbers together and then divide by two. These are both such simple operations that I decided to just make functions to add and divide base 128 numbers represented as lists. This solution hasn't been used in my system yet so I might still find some bugs in it. Also it could probably be a lot shorter, but this is just something I needed to get done instead of trying to make it perfect.\n# Given two lists representing a number with one digit left to decimal point and the\n# rest after it, for example 1.555 = [1,5,5,5] and 0.235 = [0,2,3,5], returns a similar\n# list representing those two numbers added together.\n#\ndef ladd(a, b, base=128):\n i = max(len(a), len(b))\n lsum = [0] * i \n while i > 1:\n i -= 1\n av = bv = 0\n if i < len(a): av = a[i]\n if i < len(b): bv = b[i]\n lsum[i] += av + bv\n if lsum[i] >= base:\n lsum[i] -= base\n lsum[i-1] += 1\n return lsum\n\n# Given a list of digits after the decimal point, returns a new list of digits\n# representing that number divided by two.\n#\ndef ldiv2(vals, base=128):\n vs = vals[:]\n vs.append(0)\n i = len(vs)\n while i > 0:\n i -= 1\n if (vs[i] % 2) == 1:\n vs[i] -= 1\n vs[i+1] += base / 2\n vs[i] = vs[i] / 2\n if vs[-1] == 0: vs = vs[0:-1]\n return vs\n\n# Given two app engine key names, returns the key name that comes between them.\n#\ndef average(a_kn, b_kn):\n m = lambda x:ord(x)\n a = [0] + map(m, a_kn)\n b = [0] + map(m, b_kn)\n avg = ldiv2(ladd(a, b))\n return \"\".join(map(lambda x:chr(x), avg[1:]))\n\nprint average('a', 'z') # m@\nprint average('aa', 'zz') # n-@\nprint average('aa', 'az') # am@\nprint average('cat', 'doggie') # d(mstr@\nprint average('google', 'microsoft') # jlim.,7s:\nprint average('microsoft', 'google') # jlim.,7s:\n\n",
"import math\ndef avg(str1,str2):\n y = ''\n s = 'abcdefghijklmnopqrstuvwxyz'\n for i in range(len(str1)):\n x = s.index(str2[i])+s.index(str1[i])\n x = math.floor(x/2)\n y += s[x]\n return y\n\nprint(avg('z','a')) # m\nprint(avg('aa','az')) # am\nprint(avg('cat','dog')) # chm\n\nStill working on strings with different lengths... any ideas?\n",
"This version thinks 'abc' is a fraction like 0.abc. In this approach space is zero and a valid input/output.\nMAX_ITER = 10\nletters = \" abcdefghijklmnopqrstuvwxyz\"\ndef to_double(name):\n d = 0\n for i, ch in enumerate(name):\n idx = letters.index(ch)\n d += idx * len(letters) ** (-i - 1)\n return d\n\ndef from_double(d):\n name = \"\"\n for i in range(MAX_ITER):\n d *= len(letters)\n name += letters[int(d)]\n d -= int(d)\n return name\n\ndef avg(w1, w2):\n w1 = to_double(w1)\n w2 = to_double(w2)\n return from_double((w1 + w2) * 0.5)\n\nprint avg('a', 'a') # 'a'\nprint avg('a', 'aa') # 'a mmmmmmmm'\nprint avg('aa', 'aa') # 'a zzzzzzzz'\nprint avg('car', 'duck') # 'cxxemmmmmm'\n\nUnfortunately, the naïve algorithm is not able to detect the periodic 'z's, this would be something like 0.99999 in decimal; therefore 'a zzzzzzzz' is actually 'aa' (the space before the 'z' periodicity must be increased by one.\nIn order to normalise this, you can use the following function\ndef remove_z_period(name):\n if len(name) != MAX_ITER:\n return name\n if name[-1] != 'z':\n return name\n n = \"\"\n overflow = True\n for ch in reversed(name):\n if overflow:\n if ch == 'z':\n ch = ' '\n else:\n ch=letters[(letters.index(ch)+1)]\n overflow = False\n n = ch + n\n return n\n\nprint remove_z_period('a zzzzzzzz') # 'aa'\n\n",
"I haven't programmed in python in a while and this seemed interesting enough to try.\nBear with my recursive programming. Too many functional languages look like python.\ndef stravg_half(a, ln):\n # If you have a problem it will probably be in here.\n # The floor of the character's value is 0, but you may want something different\n f = 0\n #f = ord('a')\n L = ln - 1\n if 0 == L:\n return ''\n A = ord(a[0])\n return chr(A/2) + stravg_half( a[1:], L)\n\ndef stravg_helper(a, b, ln, x):\n L = ln - 1\n A = ord(a[0])\n B = ord(b[0])\n D = (A + B)/2\n if 0 == L:\n if 0 == x:\n return chr(D)\n # NOTE: The caller of helper makes sure that len(a)>=len(b)\n return chr(D) + stravg_half(a[1:], x)\n return chr(D) + stravg_helper(a[1:], b[1:], L, x)\n\ndef stravg(a, b):\n la = len(a)\n lb = len(b)\n if 0 == la:\n if 0 == lb:\n return a # which is empty\n return stravg_half(b, lb)\n if 0 == lb:\n return stravg_half(a, la)\n x = la - lb\n if x > 0:\n return stravg_helper(a, b, lb, x)\n return stravg_helper(b, a, la, -x) # Note the order of the args\n\n"
] |
[
8,
6,
6,
2,
1,
0,
0,
0
] |
[] |
[] |
[
"algorithm",
"python"
] |
stackoverflow_0002510755_algorithm_python.txt
|
Q:
wxPython, Threads, and PostEvent between modules
I'm relatively new to wxPython (but not Python itself), so forgive me if I've missed something here.
I'm writing a GUI application, which at a very basic level consists of "Start" and "Stop" buttons that start and stop a thread. This thread is an infinite loop, which only ends when the thread is stopped. The loop generates messages, which at the moment are just output using print.
The GUI class and the infinite loop (using threading.Thread as a subclass) are held in separate files. What is the best way to get the thread to push an update to something like a TextCtrl in the GUI? I've been playing around with PostEvent and Queue, but without much luck.
Here's some bare bones code, with portions removed to keep it concise:
main_frame.py
import wx
from loop import Loop
class MainFrame(wx.Frame):
def __init__(self, parent, title):
# Initialise and show GUI
# Add two buttons, btnStart and btnStop
# Bind the two buttons to the following two methods
self.threads = []
def onStart(self):
x = Loop()
x.start()
self.threads.append(x)
def onStop(self):
for t in self.threads:
t.stop()
loop.py
class Loop(threading.Thread):
def __init__(self):
self._stop = threading.Event()
def run(self):
while not self._stop.isSet():
print datetime.date.today()
def stop(self):
self._stop.set()
I did, at one point, have it working by having the classes in the same file by using wx.lib.newevent.NewEvent() along these lines. If anyone could point me in the right direction, that'd be much appreciated.
A:
The easiest solution would be to use wx.CallAfter
wx.CallAfter(text_control.SetValue, "some_text")
You can call CallAfter from any thread and the function that you pass it to be called will be called from the main thread.
|
wxPython, Threads, and PostEvent between modules
|
I'm relatively new to wxPython (but not Python itself), so forgive me if I've missed something here.
I'm writing a GUI application, which at a very basic level consists of "Start" and "Stop" buttons that start and stop a thread. This thread is an infinite loop, which only ends when the thread is stopped. The loop generates messages, which at the moment are just output using print.
The GUI class and the infinite loop (using threading.Thread as a subclass) are held in separate files. What is the best way to get the thread to push an update to something like a TextCtrl in the GUI? I've been playing around with PostEvent and Queue, but without much luck.
Here's some bare bones code, with portions removed to keep it concise:
main_frame.py
import wx
from loop import Loop
class MainFrame(wx.Frame):
def __init__(self, parent, title):
# Initialise and show GUI
# Add two buttons, btnStart and btnStop
# Bind the two buttons to the following two methods
self.threads = []
def onStart(self):
x = Loop()
x.start()
self.threads.append(x)
def onStop(self):
for t in self.threads:
t.stop()
loop.py
class Loop(threading.Thread):
def __init__(self):
self._stop = threading.Event()
def run(self):
while not self._stop.isSet():
print datetime.date.today()
def stop(self):
self._stop.set()
I did, at one point, have it working by having the classes in the same file by using wx.lib.newevent.NewEvent() along these lines. If anyone could point me in the right direction, that'd be much appreciated.
|
[
"The easiest solution would be to use wx.CallAfter\nwx.CallAfter(text_control.SetValue, \"some_text\")\n\nYou can call CallAfter from any thread and the function that you pass it to be called will be called from the main thread.\n"
] |
[
2
] |
[] |
[] |
[
"events",
"multithreading",
"python",
"user_interface",
"wxpython"
] |
stackoverflow_0002544339_events_multithreading_python_user_interface_wxpython.txt
|
Q:
How do you determine which file is imported in Python with an "import" statement?
How do you determine which file is imported in Python with an "import" statement?
I want to determine that I am loading the correct version of a locally modified .py file. Basically the equivalent of "which" in a POSIX environment.
A:
Start python with the -v parameter to enable debugging output. When you then import a module, Python will print out where the module was imported from:
$ python -v
...
>>> import re
# /usr/lib/python2.6/re.pyc matches /usr/lib/python2.6/re.py
import re # precompiled from /usr/lib/python2.6/re.pyc
...
If you additionally want to see in what other places Python searched for the module, add a second -v:
$ python -v -v
...
>>> import re
# trying re.so
# trying remodule.so
# trying re.py
# trying re.pyc
# trying /usr/lib/python2.6/re.so
# trying /usr/lib/python2.6/remodule.so
# trying /usr/lib/python2.6/re.py
# /usr/lib/python2.6/re.pyc matches /usr/lib/python2.6/re.py
import re # precompiled from /usr/lib/python2.6/re.pyc
...
A:
Look at its __file__ attribute.
A:
I figured it out. Imported modules have a __file__ field that is the file that was loaded. Combine that with __import__, I defined a function:
which = lambda str : __import__(str).__file__.
A:
Put an explicit version identifier in each module.
__version__ = "Some.version.String"
Put these in every module you write, without exception.
import someModule
print someModule.__version__
This is (a) explicit, (b) easy to manage. You can also use "Keyword Substitution" from your version control tool to actually fill in the version string for you on each commit.
|
How do you determine which file is imported in Python with an "import" statement?
|
How do you determine which file is imported in Python with an "import" statement?
I want to determine that I am loading the correct version of a locally modified .py file. Basically the equivalent of "which" in a POSIX environment.
|
[
"Start python with the -v parameter to enable debugging output. When you then import a module, Python will print out where the module was imported from:\n$ python -v\n...\n>>> import re\n# /usr/lib/python2.6/re.pyc matches /usr/lib/python2.6/re.py\nimport re # precompiled from /usr/lib/python2.6/re.pyc\n...\n\nIf you additionally want to see in what other places Python searched for the module, add a second -v:\n$ python -v -v\n...\n>>> import re\n# trying re.so\n# trying remodule.so\n# trying re.py\n# trying re.pyc\n# trying /usr/lib/python2.6/re.so\n# trying /usr/lib/python2.6/remodule.so\n# trying /usr/lib/python2.6/re.py\n# /usr/lib/python2.6/re.pyc matches /usr/lib/python2.6/re.py\nimport re # precompiled from /usr/lib/python2.6/re.pyc\n...\n\n",
"Look at its __file__ attribute.\n",
"I figured it out. Imported modules have a __file__ field that is the file that was loaded. Combine that with __import__, I defined a function:\nwhich = lambda str : __import__(str).__file__.\n",
"Put an explicit version identifier in each module.\n__version__ = \"Some.version.String\"\n\nPut these in every module you write, without exception.\nimport someModule\nprint someModule.__version__\n\nThis is (a) explicit, (b) easy to manage. You can also use \"Keyword Substitution\" from your version control tool to actually fill in the version string for you on each commit.\n"
] |
[
12,
10,
3,
0
] |
[] |
[] |
[
"import",
"python"
] |
stackoverflow_0002542809_import_python.txt
|
Q:
"No module named slimmer.middleware"
I'm trying to setup blog engine django-mingus, but meet this obstacle:
[Tue Mar 30 04:14:02 2010] [error] [client 192.168.12.161] mod_wsgi (pid=12908): Exception occurred processing WSGI script '/home/piv/srv/python-env/myblog/project/django-mingus/mingus/deploy/django.wsgi'.
[Tue Mar 30 04:14:02 2010] [error] [client 192.168.12.161] Traceback (most recent call last):
[Tue Mar 30 04:14:02 2010] [error] [client 192.168.12.161] File "/home/piv/srv/python-env/myblog/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 230, in __call__
[Tue Mar 30 04:14:02 2010] [error] [client 192.168.12.161] self.load_middleware()
[Tue Mar 30 04:14:02 2010] [error] [client 192.168.12.161] File "/home/piv/srv/python-env/myblog/lib/python2.5/site-packages/django/core/handlers/base.py", line 42, in load_middleware
[Tue Mar 30 04:14:02 2010] [error] [client 192.168.12.161] raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e)
[Tue Mar 30 04:14:02 2010] [error] [client 192.168.12.161] ImproperlyConfigured: Error importing middleware slimmer.middleware: "No module named slimmer.middleware"
When I start Django development server it works well, but through Apache+mod_wsgi it appears this issue.
What could be the reason of this problem?
A:
Read:
http://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html
Try the alternate WSGI script file described at the end.
This will resolve some sys.path issues if you hadn't done anything to address them yourself.
If still doesn't work, may be a permissions issue given that Apache normally runs as different user and so may not be able to read code if that code was only readable to you. See:
http://code.google.com/p/modwsgi/wiki/ApplicationIssues#Access_Rights_Of_Apache_User
|
"No module named slimmer.middleware"
|
I'm trying to setup blog engine django-mingus, but meet this obstacle:
[Tue Mar 30 04:14:02 2010] [error] [client 192.168.12.161] mod_wsgi (pid=12908): Exception occurred processing WSGI script '/home/piv/srv/python-env/myblog/project/django-mingus/mingus/deploy/django.wsgi'.
[Tue Mar 30 04:14:02 2010] [error] [client 192.168.12.161] Traceback (most recent call last):
[Tue Mar 30 04:14:02 2010] [error] [client 192.168.12.161] File "/home/piv/srv/python-env/myblog/lib/python2.5/site-packages/django/core/handlers/wsgi.py", line 230, in __call__
[Tue Mar 30 04:14:02 2010] [error] [client 192.168.12.161] self.load_middleware()
[Tue Mar 30 04:14:02 2010] [error] [client 192.168.12.161] File "/home/piv/srv/python-env/myblog/lib/python2.5/site-packages/django/core/handlers/base.py", line 42, in load_middleware
[Tue Mar 30 04:14:02 2010] [error] [client 192.168.12.161] raise exceptions.ImproperlyConfigured, 'Error importing middleware %s: "%s"' % (mw_module, e)
[Tue Mar 30 04:14:02 2010] [error] [client 192.168.12.161] ImproperlyConfigured: Error importing middleware slimmer.middleware: "No module named slimmer.middleware"
When I start Django development server it works well, but through Apache+mod_wsgi it appears this issue.
What could be the reason of this problem?
|
[
"Read:\nhttp://blog.dscpl.com.au/2010/03/improved-wsgi-script-for-use-with.html\nTry the alternate WSGI script file described at the end.\nThis will resolve some sys.path issues if you hadn't done anything to address them yourself.\nIf still doesn't work, may be a permissions issue given that Apache normally runs as different user and so may not be able to read code if that code was only readable to you. See:\nhttp://code.google.com/p/modwsgi/wiki/ApplicationIssues#Access_Rights_Of_Apache_User\n"
] |
[
0
] |
[] |
[] |
[
"django",
"python"
] |
stackoverflow_0002544002_django_python.txt
|
Q:
Django Sum all values with a distinct ForeignKey ID & zip them with fields from related table
I would like to perform something similar to this (ie get the sum of distinct event amounts in a payment table then group the payments by event details and total money paid for them. Also getting users and what they have paid for an event will be done) in Django using PostgreSQL.
My models are as below:
class UserProfile(User):
onames = models.CharField(max_length=30, blank=True)
phoneNumber = models.CharField(max_length=15, blank=True)
regNo = models.CharField(max_length=15)
designation = models.CharField(max_length=3,choices=DESIGNATION_CHOICES, default='MEM')
image = models.ImageField(max_length=100,upload_to='photos/%Y/%m/%d', blank=True, null=True, default='photos/2010/03/placeholder.jpg')
course = models.CharField(max_length=30, blank=True, null=True)
timezone = models.CharField(max_length=50, default='Africa/Nairobi')
smsCom = models.BooleanField()
mailCom = models.BooleanField()
class Payments(models.Model):
username = models.ForeignKey(UserProfile, related_name='payer')
receiptNo = models.CharField(max_length=30, primary_key=True)
particulars = models.CharField(max_length=50)
date = models.DateField(auto_now_add=True)
amount = models.FloatField(max_length=99, blank=True)
eventID = models.ForeignKey('events', null=True, blank=True)
receiver = models.ForeignKey(UserProfile, related_name='receiver')
deleted = models.BooleanField()
class events(models.Model):
eventName = models.CharField(max_length=100)
eventID = models.AutoField(primary_key=True)
details = models.TextField()
attendanceFee = models.FloatField(max_length=99)
date = models.DateField()
username = models.ManyToManyField(UserProfile, related_name='user')
eventposter = models.ForeignKey(UserProfile, related_name='event_poster')
deleted = models.BooleanField()
A:
after some nerve cracking, the solution was to split the query into 2, i.e, one for grouping and summing and the other one for getting the matching values.
For grouping and summing, refer here
|
Django Sum all values with a distinct ForeignKey ID & zip them with fields from related table
|
I would like to perform something similar to this (ie get the sum of distinct event amounts in a payment table then group the payments by event details and total money paid for them. Also getting users and what they have paid for an event will be done) in Django using PostgreSQL.
My models are as below:
class UserProfile(User):
onames = models.CharField(max_length=30, blank=True)
phoneNumber = models.CharField(max_length=15, blank=True)
regNo = models.CharField(max_length=15)
designation = models.CharField(max_length=3,choices=DESIGNATION_CHOICES, default='MEM')
image = models.ImageField(max_length=100,upload_to='photos/%Y/%m/%d', blank=True, null=True, default='photos/2010/03/placeholder.jpg')
course = models.CharField(max_length=30, blank=True, null=True)
timezone = models.CharField(max_length=50, default='Africa/Nairobi')
smsCom = models.BooleanField()
mailCom = models.BooleanField()
class Payments(models.Model):
username = models.ForeignKey(UserProfile, related_name='payer')
receiptNo = models.CharField(max_length=30, primary_key=True)
particulars = models.CharField(max_length=50)
date = models.DateField(auto_now_add=True)
amount = models.FloatField(max_length=99, blank=True)
eventID = models.ForeignKey('events', null=True, blank=True)
receiver = models.ForeignKey(UserProfile, related_name='receiver')
deleted = models.BooleanField()
class events(models.Model):
eventName = models.CharField(max_length=100)
eventID = models.AutoField(primary_key=True)
details = models.TextField()
attendanceFee = models.FloatField(max_length=99)
date = models.DateField()
username = models.ManyToManyField(UserProfile, related_name='user')
eventposter = models.ForeignKey(UserProfile, related_name='event_poster')
deleted = models.BooleanField()
|
[
"after some nerve cracking, the solution was to split the query into 2, i.e, one for grouping and summing and the other one for getting the matching values. \nFor grouping and summing, refer here\n"
] |
[
0
] |
[] |
[] |
[
"django",
"django_models",
"postgresql",
"python"
] |
stackoverflow_0002534783_django_django_models_postgresql_python.txt
|
Q:
How to localize an app on Google App Engine?
What options are there for localizing an app on Google App Engine? How do you do it using Webapp, Django, web2py or [insert framework here].
1. Readable URLs and entity key names
Readable URLs are good for usability and search engine optimization (Stack Overflow is a good example on how to do it). On Google App Engine, key based queries are recommended for performance reasons. It follows that it is good practice to use the entity key name in the URL, so that the entity can be fetched from the datastore as quickly as possible.
Some characters have special meaning in URLs (&, ", ' etc). To be able to use key names as parts of an URL, they should not contain any of these characters. Currently I use the function below to create key names:
import re
import unicodedata
def urlify(unicode_string):
"""Translates latin1 unicode strings to url friendly ASCII.
Converts accented latin1 characters to their non-accented ASCII
counterparts, converts to lowercase, converts spaces to hyphens
and removes all characters that are not alphanumeric ASCII.
Arguments
unicode_string: Unicode encoded string.
Returns
String consisting of alphanumeric (ASCII) characters and hyphens.
"""
str = unicodedata.normalize('NFKD', unicode_string).encode('ASCII',
'ignore')
str = re.sub('[^\w\s-]', '', str).strip().lower()
return re.sub('[-\s]+', '-', str)
This is basically a whitelist for approved characters. It works fine for English and Swedish, however it will fail for non-western scripts and remove letters from some western ones (like Norwegian and Danish with their œ and ø).
Can anyone suggest a method that works with more languages? Would it be better to remove problematic characters (blacklist)?
2. Translating templates
Does Django internationalization and localization work on Google App Engine? Are there any extra steps that must be performed? Is it possible to use Django i18n and l10n for Django templates while using Webapp?
The Jinja2 template language provides integration with Babel. How well does this work, in your experience?
What options are avilable for your chosen template language?
3. Translated datastore content
When serving content from (or storing it to) the datastore: Is there a better way than getting the accept_language parameter from the HTTP request and matching this with a language property that you have set with each entity?
A:
Regarding point 1, there's really no need to go to such lengths: Simply use unicode key names. They'll be encoded as UTF-8 in the datastore for you.
Regarding point 3, there are many ways to handle language detection. Certainly accept_language should be part of it, and you'll find webob's accept_language support particularly useful here (hopefully Django or your framework-of-choice has something similar). It's quite often the case, however, that a user's browser's language configuration isn't correct, so you'll want to make sure there's some way for the user to override the detected language - for example, with a link on each page to change the language, setting a preference cookie.
A:
Concerning point 2, I asked a similar question a few months ago. I've managed to get the application internationalized, but just the content, not the urls (wasn't planning on doing so either).
I've also added the revision I made to my code so that people can see what changes went into i18n'ing this Google App Engine app. Look at my second comment on the accepted answer.
Good luck with your other 2 points!
|
How to localize an app on Google App Engine?
|
What options are there for localizing an app on Google App Engine? How do you do it using Webapp, Django, web2py or [insert framework here].
1. Readable URLs and entity key names
Readable URLs are good for usability and search engine optimization (Stack Overflow is a good example on how to do it). On Google App Engine, key based queries are recommended for performance reasons. It follows that it is good practice to use the entity key name in the URL, so that the entity can be fetched from the datastore as quickly as possible.
Some characters have special meaning in URLs (&, ", ' etc). To be able to use key names as parts of an URL, they should not contain any of these characters. Currently I use the function below to create key names:
import re
import unicodedata
def urlify(unicode_string):
"""Translates latin1 unicode strings to url friendly ASCII.
Converts accented latin1 characters to their non-accented ASCII
counterparts, converts to lowercase, converts spaces to hyphens
and removes all characters that are not alphanumeric ASCII.
Arguments
unicode_string: Unicode encoded string.
Returns
String consisting of alphanumeric (ASCII) characters and hyphens.
"""
str = unicodedata.normalize('NFKD', unicode_string).encode('ASCII',
'ignore')
str = re.sub('[^\w\s-]', '', str).strip().lower()
return re.sub('[-\s]+', '-', str)
This is basically a whitelist for approved characters. It works fine for English and Swedish, however it will fail for non-western scripts and remove letters from some western ones (like Norwegian and Danish with their œ and ø).
Can anyone suggest a method that works with more languages? Would it be better to remove problematic characters (blacklist)?
2. Translating templates
Does Django internationalization and localization work on Google App Engine? Are there any extra steps that must be performed? Is it possible to use Django i18n and l10n for Django templates while using Webapp?
The Jinja2 template language provides integration with Babel. How well does this work, in your experience?
What options are avilable for your chosen template language?
3. Translated datastore content
When serving content from (or storing it to) the datastore: Is there a better way than getting the accept_language parameter from the HTTP request and matching this with a language property that you have set with each entity?
|
[
"Regarding point 1, there's really no need to go to such lengths: Simply use unicode key names. They'll be encoded as UTF-8 in the datastore for you.\nRegarding point 3, there are many ways to handle language detection. Certainly accept_language should be part of it, and you'll find webob's accept_language support particularly useful here (hopefully Django or your framework-of-choice has something similar). It's quite often the case, however, that a user's browser's language configuration isn't correct, so you'll want to make sure there's some way for the user to override the detected language - for example, with a link on each page to change the language, setting a preference cookie.\n",
"Concerning point 2, I asked a similar question a few months ago. I've managed to get the application internationalized, but just the content, not the urls (wasn't planning on doing so either).\nI've also added the revision I made to my code so that people can see what changes went into i18n'ing this Google App Engine app. Look at my second comment on the accepted answer.\nGood luck with your other 2 points!\n"
] |
[
3,
2
] |
[] |
[] |
[
"django",
"google_app_engine",
"internationalization",
"localization",
"python"
] |
stackoverflow_0002544843_django_google_app_engine_internationalization_localization_python.txt
|
Q:
How to create instances of related models in Django
I'm working on a CMSy app for which I've implemented a set of models which allow for creation of custom Template instances, made up of a number of Fields and tied to a specific Customer. The end-goal is that one or more templates with a set of custom fields can be defined through the Admin interface and associated to a customer, so that customer can then create content objects in the format prescribed by the template.
I seem to have gotten this hooked up such that I can create any number of Template objects, but I'm struggling with how to create instances - actual content objects - in those templates. For example, I can define a template "Basic Page" for customer "Acme" which has the fields "Title" and "Body", but I haven't figured out how to create Basic Page instances where these fields can be filled in.
Here are my (somewhat elided) models...
class Customer(models.Model):
...
class Field(models.Model):
label = models.CharField(max_length=255)
component = models.ForeignKey(ContentType,
limit_choices_to={'id__in': component_choices}
)
fields = models.Manager()
class Template(models.Model):
label = models.CharField(max_length=255)
clients = models.ManyToManyField(Customer, blank=True)
fields = models.ManyToManyField(Field, blank=True)
class ContentObject(models.Model):
label = models.CharField(max_length=255)
template = models.ForeignKey(Template)
author = models.ForeignKey(User)
customer = models.ForeignKey(Customer)
mod_date = models.DateTimeField('Modified Date', editable=False)
def __unicode__(self):
return '%s (%s)' % (self.label, self.template)
def save(self):
self.mod_date = datetime.datetime.now()
super(ContentObject, self).save()
Thanks in advance for any advice!
A:
If you want to stick with this model architecture, you need to add another field to the ContentObject class that will serve to store the actual content. It could be something like:
ContentObject(models.Model):
...
fields_content = models.ManyToManyField(Field, through=FieldContent)
...
and then:
class FieldContent(models.Model):
field = ForeignKey(Field)
content_object = ForeignKey(ContentObject)
content = CharField
Then you should obviously make sure, probably using the pre_save signal, that for a given ContentObject instance only fields that are in the instance's template can go to the FieldContent table.
And then you can create the actual content by something like:
FieldContent.objects.create(field=your_field, content_object=your_content_object, content=content_given_by_the_customer)
A:
It would just be:
my_customer.templates.add(my_template)
where my_customer and my_template are instances of Customer and Template respectively.
See the documentation for related objects
A:
Sorry if I wasn't clear. The problem is how to create instances based on a template, not how to create the templates.
My Template class is used to define what Fields a given template contains and what Customers can use it. My ContentObject class is intended to define a content record based on a Template.
Thanks again!
A:
To expand on pawartur's answer there are a couple of ways you can handle multiple (possibly complex) data types for the fields. One way you could try is to use model inheritance, maybe something like this:
class FieldContent(models.Model):
field = models.ForeignKey(Field)
content_object = models.ForeignKeyKey(ContentObject)
def get_component(self):
"""Return the specific component instance for this field."""
return self.field.get_object_for_this_type(pk=self.pk)
Then you inherit from this base Model for each field type component, for example:
class SomeComponent(FieldContent):
# specific fields for the component here
You can then do things like:
somecontentobject.get(id=whatever).fieldcontent_set.get(whatever).get_component().specific_component_field
To create new field instances you might want to add a helper method to your Field model, something like:
def create_content(self, content_object):
return self.component.get_class().objects.create(
content_object=content_object, field=self)
One thing to watch out for is that all this kind of stuff does tend to have you fighting against the framework, places where Django used to do everything for you (forms, admin etc) suddenly become a bit of work to sort out. It might be worth looking in to how some real life projects handle it, Django-cms (django-cms.org) is a probably a good start.
Just a warning: I haven't tested any of the code in this post as I'm not at a computer with anything useful installed, but it should be generally ok.
|
How to create instances of related models in Django
|
I'm working on a CMSy app for which I've implemented a set of models which allow for creation of custom Template instances, made up of a number of Fields and tied to a specific Customer. The end-goal is that one or more templates with a set of custom fields can be defined through the Admin interface and associated to a customer, so that customer can then create content objects in the format prescribed by the template.
I seem to have gotten this hooked up such that I can create any number of Template objects, but I'm struggling with how to create instances - actual content objects - in those templates. For example, I can define a template "Basic Page" for customer "Acme" which has the fields "Title" and "Body", but I haven't figured out how to create Basic Page instances where these fields can be filled in.
Here are my (somewhat elided) models...
class Customer(models.Model):
...
class Field(models.Model):
label = models.CharField(max_length=255)
component = models.ForeignKey(ContentType,
limit_choices_to={'id__in': component_choices}
)
fields = models.Manager()
class Template(models.Model):
label = models.CharField(max_length=255)
clients = models.ManyToManyField(Customer, blank=True)
fields = models.ManyToManyField(Field, blank=True)
class ContentObject(models.Model):
label = models.CharField(max_length=255)
template = models.ForeignKey(Template)
author = models.ForeignKey(User)
customer = models.ForeignKey(Customer)
mod_date = models.DateTimeField('Modified Date', editable=False)
def __unicode__(self):
return '%s (%s)' % (self.label, self.template)
def save(self):
self.mod_date = datetime.datetime.now()
super(ContentObject, self).save()
Thanks in advance for any advice!
|
[
"If you want to stick with this model architecture, you need to add another field to the ContentObject class that will serve to store the actual content. It could be something like:\nContentObject(models.Model):\n ...\n fields_content = models.ManyToManyField(Field, through=FieldContent)\n ...\n\nand then:\nclass FieldContent(models.Model):\n field = ForeignKey(Field)\n content_object = ForeignKey(ContentObject)\n content = CharField\n\nThen you should obviously make sure, probably using the pre_save signal, that for a given ContentObject instance only fields that are in the instance's template can go to the FieldContent table.\nAnd then you can create the actual content by something like:\nFieldContent.objects.create(field=your_field, content_object=your_content_object, content=content_given_by_the_customer)\n\n",
"It would just be:\nmy_customer.templates.add(my_template)\n\nwhere my_customer and my_template are instances of Customer and Template respectively.\nSee the documentation for related objects\n",
"Sorry if I wasn't clear. The problem is how to create instances based on a template, not how to create the templates. \nMy Template class is used to define what Fields a given template contains and what Customers can use it. My ContentObject class is intended to define a content record based on a Template. \nThanks again! \n",
"To expand on pawartur's answer there are a couple of ways you can handle multiple (possibly complex) data types for the fields. One way you could try is to use model inheritance, maybe something like this:\nclass FieldContent(models.Model):\n field = models.ForeignKey(Field)\n content_object = models.ForeignKeyKey(ContentObject)\n def get_component(self):\n \"\"\"Return the specific component instance for this field.\"\"\"\n return self.field.get_object_for_this_type(pk=self.pk)\n\nThen you inherit from this base Model for each field type component, for example:\nclass SomeComponent(FieldContent):\n # specific fields for the component here\n\nYou can then do things like:\n somecontentobject.get(id=whatever).fieldcontent_set.get(whatever).get_component().specific_component_field\nTo create new field instances you might want to add a helper method to your Field model, something like:\n def create_content(self, content_object):\n return self.component.get_class().objects.create(\n content_object=content_object, field=self)\n\nOne thing to watch out for is that all this kind of stuff does tend to have you fighting against the framework, places where Django used to do everything for you (forms, admin etc) suddenly become a bit of work to sort out. It might be worth looking in to how some real life projects handle it, Django-cms (django-cms.org) is a probably a good start.\nJust a warning: I haven't tested any of the code in this post as I'm not at a computer with anything useful installed, but it should be generally ok.\n"
] |
[
1,
0,
0,
0
] |
[] |
[] |
[
"django",
"models",
"python"
] |
stackoverflow_0002481860_django_models_python.txt
|
Q:
Class Decorators, Inheritance, super(), and maximum recursion
I'm trying to figure out how to use decorators on subclasses that use super(). Since my class decorator creates another subclass a decorated class seems to prevent the use of super() when it changes the className passed to super(className, self). Below is an example:
def class_decorator(cls):
class _DecoratedClass(cls):
def __init__(self):
return super(_DecoratedClass, self).__init__()
return _DecoratedClass
class BaseClass(object):
def __init__(self):
print "class: %s" % self.__class__.__name__
def print_class(self):
print "class: %s" % self.__class__.__name__
bc = BaseClass().print_class()
class SubClass(BaseClass):
def print_class(self):
super(SubClass, self).print_class()
sc = SubClass().print_class()
@class_decorator
class SubClassAgain(BaseClass):
def print_class(self):
super(SubClassAgain, self).print_class()
sca = SubClassAgain()
# sca.print_class() # Uncomment for maximum recursion
The output should be:
class: BaseClass
class: BaseClass
class: SubClass
class: SubClass
class: _DecoratedClass
Traceback (most recent call last):
File "class_decorator_super.py", line 34, in <module>
sca.print_class()
File "class_decorator_super.py", line 31, in print_class
super(SubClassAgain, self).print_class()
...
...
RuntimeError: maximum recursion depth exceeded while calling a Python object
Does anyone know of a way to not break a subclass that uses super() when using a decorator? Ideally I'd like to reuse a class from time to time and simply decorate it w/out breaking it.
A:
Basically, you can see the problem after entering your code sample at the interactive Python prompt:
>>> SubClassAgain
<class '__main__._DecoratedClass'>
i.e., the name SubClassAgain is now bound (in global scope, in this case) to a class that in fact isn't the "real" SubClassAgain, but a subclass thereof. So, any late-bound reference to that name, like the one you have in its super(SubClassAgain, call, will of course get the subclass that's masquerading by that name -- that subclass's superclass is of course "the real SubClassAgain", whence the infinite recursion.
You can reproduce the same problem very simply without decoration, just by having any subclass usurp its base-class's name:
>>> class Base(object):
... def pcl(self): print 'cl: %s' % self.__class__.__name__
...
>>> class Sub(Base):
... def pcl(self): super(Sub, self).pcl()
...
>>> Sub().pcl()
cl: Sub
>>> class Sub(Sub): pass
...
now, Sub().pcl() will cause infinite recursion, due to the "name usurpation". Class decoration, unless you use it to decorate and return the same class you get as an argument, is systematic "name usurpation", and thus incompatible with uses of the class name which absolutely must return the "true" class of that name, and not the usurper (be that in self or otherwise).
Workarounds -- if you absolutely must have both class decoration as usurpation (not just class decoration by changes in the received class argument), and super -- basically need protocols for cooperation between the usurper and the possible-usurpee, such as the following small changes to your example code:
def class_decorator(cls):
class _DecoratedClass(cls):
_thesuper = cls
def __init__(self):
return super(_DecoratedClass, self).__init__()
return _DecoratedClass
...
@class_decorator
class SubClassAgain(BaseClass):
def print_class(self):
cls = SubClassAgain
if '_thesuper' in cls.__dict__:
cls = cls._thesuper
super(cls, self).print_class()
A:
As you might already be aware, the problem arises from the fact that the name SubClassAgain in SubClassAgain.print_class is scoped to the current module's global namespace. SubClassAgain thus refers to the class _DecoratedClass rather than the class that gets decorated. One way of getting at the decorated class is to follow a convention that class decorators have a property referring to the decorated class.
def class_decorator(cls):
class _DecoratedClass(cls):
original=cls
def __init__(self):
print '_DecoratedClass.__init__'
return super(_DecoratedClass, self).__init__()
return _DecoratedClass
@class_decorator
class SubClassAgain(BaseClass):
original
def print_class(self):
super(self.__class__.original, self).print_class()
Another is to use the __bases__ property to get the decorated class.
@class_decorator
class SubClassAgain(BaseClass):
def print_class(self):
super(self.__class__.__bases__[0], self).print_class()
Of course, with multiple decorators, either of these become unwieldy. The latter also doesn't work with subclasses of the decorated class. You can combine decorators and mixins, writing a decorator that adds a mixin into a class. This won't help you override methods.
def class_decorator(cls):
class _DecoratedClass(object):
def foo(self):
return 'foo'
cls.__bases__ += (_DecoratedClass, )
return cls
Lastly, you can work directly with the class attributes to set methods.
def class_decorator(cls):
old_init = getattr(cls, '__init__')
def __init__(self, *args, **kwargs):
print 'decorated __init__'
old_init(self, *args, **kwargs)
setattr(cls, '__init__', __init__)
return cls
This is probably the best option for your example, though the mixin-based decorator also has its uses.
A:
The decorator creates a kind-of diamond inheritance situation. You can avoid these problems by not using super(). Changing SubClassAgain to the following will prevent infinite recursion:
@class_decorator
class SubClassAgain(BaseClass):
def print_class(self):
BaseClass.print_class(self)
A:
Are you sure you want to use a class decorator and not simply inheritance? For instance, instead of a decorator to replace your class with a subclass introducing some methods, perhaps you want a mixin class and to use multiple inheritance to create the final class?
This would be accomplished by something like
class MyMixIn(object):
def __init__(self):
super(MyMixIn, self).__init__()
class BaseClass(object):
def __init__(self):
print "class: %s" % self.__class__.__name__
def print_class(self):
print "class: %s" % self.__class__.__name__
class SubClassAgain(BaseClass, MyMixIn):
def print_class(self):
super(SubClassAgain, self).print_class()
sca = SubClassAgain()
sca.print_class()
A:
How about simply promoting _DecoratedClass's __bases__ up to the __bases__ of SubClassAgain?
def class_decorator(cls):
class _DecoratedClass(cls):
def __init__(self):
return super(_DecoratedClass, self).__init__()
_DecoratedClass.__bases__=cls.__bases__
return _DecoratedClass
|
Class Decorators, Inheritance, super(), and maximum recursion
|
I'm trying to figure out how to use decorators on subclasses that use super(). Since my class decorator creates another subclass a decorated class seems to prevent the use of super() when it changes the className passed to super(className, self). Below is an example:
def class_decorator(cls):
class _DecoratedClass(cls):
def __init__(self):
return super(_DecoratedClass, self).__init__()
return _DecoratedClass
class BaseClass(object):
def __init__(self):
print "class: %s" % self.__class__.__name__
def print_class(self):
print "class: %s" % self.__class__.__name__
bc = BaseClass().print_class()
class SubClass(BaseClass):
def print_class(self):
super(SubClass, self).print_class()
sc = SubClass().print_class()
@class_decorator
class SubClassAgain(BaseClass):
def print_class(self):
super(SubClassAgain, self).print_class()
sca = SubClassAgain()
# sca.print_class() # Uncomment for maximum recursion
The output should be:
class: BaseClass
class: BaseClass
class: SubClass
class: SubClass
class: _DecoratedClass
Traceback (most recent call last):
File "class_decorator_super.py", line 34, in <module>
sca.print_class()
File "class_decorator_super.py", line 31, in print_class
super(SubClassAgain, self).print_class()
...
...
RuntimeError: maximum recursion depth exceeded while calling a Python object
Does anyone know of a way to not break a subclass that uses super() when using a decorator? Ideally I'd like to reuse a class from time to time and simply decorate it w/out breaking it.
|
[
"Basically, you can see the problem after entering your code sample at the interactive Python prompt:\n>>> SubClassAgain\n<class '__main__._DecoratedClass'>\n\ni.e., the name SubClassAgain is now bound (in global scope, in this case) to a class that in fact isn't the \"real\" SubClassAgain, but a subclass thereof. So, any late-bound reference to that name, like the one you have in its super(SubClassAgain, call, will of course get the subclass that's masquerading by that name -- that subclass's superclass is of course \"the real SubClassAgain\", whence the infinite recursion.\nYou can reproduce the same problem very simply without decoration, just by having any subclass usurp its base-class's name:\n>>> class Base(object):\n... def pcl(self): print 'cl: %s' % self.__class__.__name__\n... \n>>> class Sub(Base):\n... def pcl(self): super(Sub, self).pcl()\n... \n>>> Sub().pcl()\ncl: Sub\n>>> class Sub(Sub): pass\n... \n\nnow, Sub().pcl() will cause infinite recursion, due to the \"name usurpation\". Class decoration, unless you use it to decorate and return the same class you get as an argument, is systematic \"name usurpation\", and thus incompatible with uses of the class name which absolutely must return the \"true\" class of that name, and not the usurper (be that in self or otherwise).\nWorkarounds -- if you absolutely must have both class decoration as usurpation (not just class decoration by changes in the received class argument), and super -- basically need protocols for cooperation between the usurper and the possible-usurpee, such as the following small changes to your example code:\ndef class_decorator(cls):\n class _DecoratedClass(cls):\n _thesuper = cls\n def __init__(self):\n return super(_DecoratedClass, self).__init__()\n return _DecoratedClass\n\n ...\n\n@class_decorator\nclass SubClassAgain(BaseClass):\n def print_class(self):\n cls = SubClassAgain\n if '_thesuper' in cls.__dict__:\n cls = cls._thesuper\n super(cls, self).print_class()\n\n",
"As you might already be aware, the problem arises from the fact that the name SubClassAgain in SubClassAgain.print_class is scoped to the current module's global namespace. SubClassAgain thus refers to the class _DecoratedClass rather than the class that gets decorated. One way of getting at the decorated class is to follow a convention that class decorators have a property referring to the decorated class. \ndef class_decorator(cls):\n class _DecoratedClass(cls):\n original=cls\n def __init__(self):\n print '_DecoratedClass.__init__'\n return super(_DecoratedClass, self).__init__()\n return _DecoratedClass\n\n@class_decorator\nclass SubClassAgain(BaseClass):\n original\n def print_class(self):\n super(self.__class__.original, self).print_class()\n\nAnother is to use the __bases__ property to get the decorated class.\n@class_decorator\nclass SubClassAgain(BaseClass):\n def print_class(self):\n super(self.__class__.__bases__[0], self).print_class()\n\nOf course, with multiple decorators, either of these become unwieldy. The latter also doesn't work with subclasses of the decorated class. You can combine decorators and mixins, writing a decorator that adds a mixin into a class. This won't help you override methods.\ndef class_decorator(cls):\n class _DecoratedClass(object):\n def foo(self):\n return 'foo'\n cls.__bases__ += (_DecoratedClass, )\n return cls\n\nLastly, you can work directly with the class attributes to set methods.\ndef class_decorator(cls):\n old_init = getattr(cls, '__init__')\n def __init__(self, *args, **kwargs):\n print 'decorated __init__'\n old_init(self, *args, **kwargs)\n setattr(cls, '__init__', __init__)\n return cls\n\nThis is probably the best option for your example, though the mixin-based decorator also has its uses.\n",
"The decorator creates a kind-of diamond inheritance situation. You can avoid these problems by not using super(). Changing SubClassAgain to the following will prevent infinite recursion:\n@class_decorator\nclass SubClassAgain(BaseClass):\n def print_class(self):\n BaseClass.print_class(self)\n\n",
"Are you sure you want to use a class decorator and not simply inheritance? For instance, instead of a decorator to replace your class with a subclass introducing some methods, perhaps you want a mixin class and to use multiple inheritance to create the final class?\nThis would be accomplished by something like\nclass MyMixIn(object):\n def __init__(self):\n super(MyMixIn, self).__init__()\n\nclass BaseClass(object):\n def __init__(self):\n print \"class: %s\" % self.__class__.__name__\n def print_class(self):\n print \"class: %s\" % self.__class__.__name__\n\nclass SubClassAgain(BaseClass, MyMixIn):\n def print_class(self):\n super(SubClassAgain, self).print_class()\n\nsca = SubClassAgain()\nsca.print_class() \n\n",
"How about simply promoting _DecoratedClass's __bases__ up to the __bases__ of SubClassAgain?\ndef class_decorator(cls):\n class _DecoratedClass(cls):\n def __init__(self):\n return super(_DecoratedClass, self).__init__()\n _DecoratedClass.__bases__=cls.__bases__\n return _DecoratedClass\n\n"
] |
[
5,
3,
3,
2,
0
] |
[] |
[] |
[
"decorator",
"python"
] |
stackoverflow_0002542747_decorator_python.txt
|
Q:
python web framework for webmail service
I'm planning to write a webmail service in Python but I can't decide which framework to choose. What criteria should I look into when trying to decide which framework to use ?
A:
I know you're asking about which web framework but this might be very useful to you. Lamson is a framework for dealing with email, it lets you basically write your own mail server and do all sorts of useful stuff in Python, check it out here http://lamsonproject.org/
For the framework I'd recommend Django, while you might end up replacing bits as your needs change I think you should never underestimate the value of being able to get something working really quickly. Django's admin app is absolutely incredible and saves so much time building your own admin interface, that alone makes Django the one to use in my opinion.
A:
Model View Controller separation is a nice one, though standard with most frameworks. It greatly improves code readability, separation of tasks, testability, optimization later on, and maintainability in the future.
The ability to utilize a templating language of your choice. This allows you to balance speed, simplicity, and extensibility according to your own needs and habits.
Widget library integration (e.g. to ToscaWidgets) is a bonus, providing automated server-side (and with certain add-ons client-side) validation and type coercion.
The framework should encourage structured projects.
A variety of deployment options; pure WSGI, FastCGI, etc.
Note that the frameworks (off the top of my head) that meet these criteria are quite varied:
WebCore (I’m biased, it’s mine. ;)
TurboGears (I’ve used this one a lot on previous projects; it’s pretty good!)
Django (I hesitate to mention this one, but it’s quite popular.)
It also depends on how low-level you want to get and how comfortable you are with the support base. WebCore and TurboGears utilize standard WSGI middleware layers and provide helpful accessors for shared features, while Django takes the “batteries included” approach. The pure WSGI approach is much easier to customize, while Django has a huge userbase.
These are a few of my thoughts, and I’ll probably update my answer as I think of more things.
A:
I'd like to add that you might want to look at posterity (http://posterity.edgewall.org/). Even though the project is basically abandoned, I guess there is at least some interesting code.
|
python web framework for webmail service
|
I'm planning to write a webmail service in Python but I can't decide which framework to choose. What criteria should I look into when trying to decide which framework to use ?
|
[
"I know you're asking about which web framework but this might be very useful to you. Lamson is a framework for dealing with email, it lets you basically write your own mail server and do all sorts of useful stuff in Python, check it out here http://lamsonproject.org/\nFor the framework I'd recommend Django, while you might end up replacing bits as your needs change I think you should never underestimate the value of being able to get something working really quickly. Django's admin app is absolutely incredible and saves so much time building your own admin interface, that alone makes Django the one to use in my opinion.\n",
"\nModel View Controller separation is a nice one, though standard with most frameworks. It greatly improves code readability, separation of tasks, testability, optimization later on, and maintainability in the future.\nThe ability to utilize a templating language of your choice. This allows you to balance speed, simplicity, and extensibility according to your own needs and habits.\nWidget library integration (e.g. to ToscaWidgets) is a bonus, providing automated server-side (and with certain add-ons client-side) validation and type coercion.\nThe framework should encourage structured projects.\nA variety of deployment options; pure WSGI, FastCGI, etc.\n\nNote that the frameworks (off the top of my head) that meet these criteria are quite varied:\n\nWebCore (I’m biased, it’s mine. ;)\nTurboGears (I’ve used this one a lot on previous projects; it’s pretty good!)\nDjango (I hesitate to mention this one, but it’s quite popular.)\n\nIt also depends on how low-level you want to get and how comfortable you are with the support base. WebCore and TurboGears utilize standard WSGI middleware layers and provide helpful accessors for shared features, while Django takes the “batteries included” approach. The pure WSGI approach is much easier to customize, while Django has a huge userbase.\nThese are a few of my thoughts, and I’ll probably update my answer as I think of more things.\n",
"I'd like to add that you might want to look at posterity (http://posterity.edgewall.org/). Even though the project is basically abandoned, I guess there is at least some interesting code.\n"
] |
[
2,
0,
0
] |
[] |
[] |
[
"frameworks",
"python",
"webmail"
] |
stackoverflow_0002395585_frameworks_python_webmail.txt
|
Q:
Python calling pipe.communicate() in a thread
Using Python 2.6.1 on Mac OS X 10.6.2, I've the following problem:
I have a threaded process (a Thread class), and each of those threads has a pipe (a subprocess.Popen) something likeso:
from threading import Thread
cmd = "some_cmd"
class Worker(Thread):
def run(self):
pipe = Popen(cmd,
stdin=PIPE,
stdout=PIPE,
stderr=PIPE)
out, err = pipe.communicate("some data")
The problem is that the pipe.communicate() code is blocking. Interestingly, when I sent an interrupt (e.g. Ctrl-C KeyboardInterrupt) to the parent process then it unblocks.
Interestingly, when I use class Worker(multiprocessing.Process), the code works just fine.
Any thoughts as to why this is blocking - and how to fix it - would be greatly appreciated.
Thank you.
A:
Using multiple threads and multiple processes will often cause problems, particularly (though not exclusively) on Unix-based systems; I recommend you just avoid mixing the two.
A:
If you call sys.exit() in the main thread, other threads will terminate at the next opportunity (on most operating systems). However, if they're in a blocking call (such as communicate()), they will wait until the blocking call completes before terminating. Control-C works because it causes the operating system to interrupt the blocking call.
Generally, the safest approach is to ensure that none of your threads call functions that may block indefinitely. Unfortunately, that often involves writing a lot more code.
In your particular case, you could store the Popen objects in a global set() before calling communicate, and have the main thread call Popen.terminate() on each of them just before exiting. That would cause the child to exit, communicate() to return, and the thread to exit.
Are you setting the thread as a daemon thread?
|
Python calling pipe.communicate() in a thread
|
Using Python 2.6.1 on Mac OS X 10.6.2, I've the following problem:
I have a threaded process (a Thread class), and each of those threads has a pipe (a subprocess.Popen) something likeso:
from threading import Thread
cmd = "some_cmd"
class Worker(Thread):
def run(self):
pipe = Popen(cmd,
stdin=PIPE,
stdout=PIPE,
stderr=PIPE)
out, err = pipe.communicate("some data")
The problem is that the pipe.communicate() code is blocking. Interestingly, when I sent an interrupt (e.g. Ctrl-C KeyboardInterrupt) to the parent process then it unblocks.
Interestingly, when I use class Worker(multiprocessing.Process), the code works just fine.
Any thoughts as to why this is blocking - and how to fix it - would be greatly appreciated.
Thank you.
|
[
"Using multiple threads and multiple processes will often cause problems, particularly (though not exclusively) on Unix-based systems; I recommend you just avoid mixing the two.\n",
"If you call sys.exit() in the main thread, other threads will terminate at the next opportunity (on most operating systems). However, if they're in a blocking call (such as communicate()), they will wait until the blocking call completes before terminating. Control-C works because it causes the operating system to interrupt the blocking call.\nGenerally, the safest approach is to ensure that none of your threads call functions that may block indefinitely. Unfortunately, that often involves writing a lot more code.\nIn your particular case, you could store the Popen objects in a global set() before calling communicate, and have the main thread call Popen.terminate() on each of them just before exiting. That would cause the child to exit, communicate() to return, and the thread to exit.\nAre you setting the thread as a daemon thread?\n"
] |
[
1,
1
] |
[] |
[] |
[
"deadlock",
"multiprocessing",
"multithreading",
"python"
] |
stackoverflow_0002542423_deadlock_multiprocessing_multithreading_python.txt
|
Q:
How to pass SOAP headers into python SUDS that are not defined in WSDL file
I have a camera on my network which I am trying to connect to with suds but suds doesn't send all the information needed. I need to put extra soap headers not defined in the WSDL file so the camera can understand the message. All the headers are contained in a SOAP envelope and then the suds command should be in the body of the message.
I have checked the suds website
and it says to pass in the headers like so: (This passes in the element as a header but I have an envelope so I'm not sure how to input this)
from suds.sax.element import Element
client = client(url)
ssnns = ('ssn', 'http://namespaces/sessionid')
ssn = Element('SessionID', ns=ssnns).setText('123')
client.set_options(soapheaders=ssn)
result = client.service.addPerson(person)
Now, I am not sure how I would implement this. Say for example, I have the below header:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:SOAP
ENC="http://www.w3.org/2003/05/soap-encoding"
<wsa:MessageID SOAP-ENV:mustUnderstand="true">urn:uuid:43268c01-f09c6</wsa:MessageID>
<SOAP-ENV:Header>
Using this or a similar example does anyone know how I would pass a valid SOAP message to the targeted service?
Thanks
A:
I have worked out how to enter in new headers and namespaces in suds.
As stated above you create an Element and pass it in as a soapheader as so:
from suds.sax.element import Element
client = client(url)
ssnns = ('ssn', 'http://namespaces/sessionid')
ssn = Element('SessionID', ns=ssnns).setText('123')
client.set_options(soapheaders=ssn)
result = client.service.addPerson(person)
But if you would like to add a namespace I have found adding a prefix seem's to do the trick. So when you create one of the elements you add addPrefix. I'm not sure if this was the way it was intended to be done but it work's.
ssn = Element('SessionID', ns=ssnns).setText('123').addPrefix(p='SOAP-ENC', u='http://www.w3.org/2003/05/soap-encoding')
The p = 'SOAP-ENC' can be any prefix eg. wsa and the u = http://address is the address of the namespace.
A complete script that would run could be:
#!/usr/local/bin/python2.6
import suds
#import logging
from suds.client import Client
from suds.sax.element import Element
from suds.sax.attribute import Attribute
from suds.xsd.sxbasic import Import
def absoluteMove():
# connects to WSDL file and stores location in variable 'client'
client = Client('http://10.10.10.10/p.wsdl')
client.options.location = 'http://10.10.10.10:32963'
# Create the header
wsans = ('wsa', 'http://schemas.xmlsoap.org/ws/2004/08/addressing')
mustAttribute = Attribute('SOAP-ENV:mustUnderstand', 'true')
n1s = ('SOAP-ENC', 'http://www.w3.org/2003/05/soap-encoding')
msgId = Element('Element').addPrefix(p='SOAP-ENC', u='http://www.w3.org/2003/05/soap-encoding')
msgId2 = Element('Address', ns=wsans).setText('http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous')
msgId1 = Element('ReplyTo', ns=wsans).insert(msgId2)
msgId1.append(mustAttribute)
msgId3 = Element('To', ns=wsans).setText('http://10.10.10.10:32954')
msgId3.append(mustAttribute)
client.set_options(soapheaders=[msgId, msgId1, msgId3, msgId2])
# Create 'token' object to pass as an argument using the 'factory' namespace
token = client.factory.create('ns4:ReferenceToken')
# Create 'dest' object to pass as an argument and values passed to this object
dest = client.factory.create('ns4:PTZVector')
dest.PanTilt._x=1
dest.PanTilt._y=4.9
dest.Zoom._x=1
# Create 'speed' object to pass as an argument and values passed to this object
speed = client.factory.create('ns4:PTZSpeed')
speed.PanTilt._x=0
speed.PanTilt._y=0
speed.Zoom._x=1
# 'AbsoluteMove' method invoked passing in the new values entered in the above objects
try:
result = client.service.AbsoluteMove(token, dest, speed)
print "absoluteMove result ", result
return result
except suds.WebFault, e:
print "suds.WebFaults caught: "
print e
if __name__ == '__main__': result = absoluteMove()
This moves the camera. To change the type of soap-envelope check my next question.
You can add logging into this script whci allow's you to check what xml command you have sent which is handy:
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger('suds.client').setLevel(logging.DEBUG)
The location can be put into the script as an option if the location is not in the wsdl file.
|
How to pass SOAP headers into python SUDS that are not defined in WSDL file
|
I have a camera on my network which I am trying to connect to with suds but suds doesn't send all the information needed. I need to put extra soap headers not defined in the WSDL file so the camera can understand the message. All the headers are contained in a SOAP envelope and then the suds command should be in the body of the message.
I have checked the suds website
and it says to pass in the headers like so: (This passes in the element as a header but I have an envelope so I'm not sure how to input this)
from suds.sax.element import Element
client = client(url)
ssnns = ('ssn', 'http://namespaces/sessionid')
ssn = Element('SessionID', ns=ssnns).setText('123')
client.set_options(soapheaders=ssn)
result = client.service.addPerson(person)
Now, I am not sure how I would implement this. Say for example, I have the below header:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2003/05/soap-envelope" xmlns:SOAP
ENC="http://www.w3.org/2003/05/soap-encoding"
<wsa:MessageID SOAP-ENV:mustUnderstand="true">urn:uuid:43268c01-f09c6</wsa:MessageID>
<SOAP-ENV:Header>
Using this or a similar example does anyone know how I would pass a valid SOAP message to the targeted service?
Thanks
|
[
"I have worked out how to enter in new headers and namespaces in suds.\nAs stated above you create an Element and pass it in as a soapheader as so:\nfrom suds.sax.element import Element \nclient = client(url) \nssnns = ('ssn', 'http://namespaces/sessionid') \nssn = Element('SessionID', ns=ssnns).setText('123') \nclient.set_options(soapheaders=ssn) \nresult = client.service.addPerson(person)\n\nBut if you would like to add a namespace I have found adding a prefix seem's to do the trick. So when you create one of the elements you add addPrefix. I'm not sure if this was the way it was intended to be done but it work's.\nssn = Element('SessionID', ns=ssnns).setText('123').addPrefix(p='SOAP-ENC', u='http://www.w3.org/2003/05/soap-encoding')\n\nThe p = 'SOAP-ENC' can be any prefix eg. wsa and the u = http://address is the address of the namespace.\nA complete script that would run could be:\n#!/usr/local/bin/python2.6\n\nimport suds\n#import logging\nfrom suds.client import Client\nfrom suds.sax.element import Element\nfrom suds.sax.attribute import Attribute\nfrom suds.xsd.sxbasic import Import\n\ndef absoluteMove():\n\n # connects to WSDL file and stores location in variable 'client'\n client = Client('http://10.10.10.10/p.wsdl')\n client.options.location = 'http://10.10.10.10:32963'\n\n # Create the header\n wsans = ('wsa', 'http://schemas.xmlsoap.org/ws/2004/08/addressing')\n mustAttribute = Attribute('SOAP-ENV:mustUnderstand', 'true')\n n1s = ('SOAP-ENC', 'http://www.w3.org/2003/05/soap-encoding')\n msgId = Element('Element').addPrefix(p='SOAP-ENC', u='http://www.w3.org/2003/05/soap-encoding')\n\n msgId2 = Element('Address', ns=wsans).setText('http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous')\n msgId1 = Element('ReplyTo', ns=wsans).insert(msgId2)\n msgId1.append(mustAttribute)\n\n msgId3 = Element('To', ns=wsans).setText('http://10.10.10.10:32954')\n msgId3.append(mustAttribute)\n\n client.set_options(soapheaders=[msgId, msgId1, msgId3, msgId2])\n\n # Create 'token' object to pass as an argument using the 'factory' namespace\n token = client.factory.create('ns4:ReferenceToken')\n\n # Create 'dest' object to pass as an argument and values passed to this object\n dest = client.factory.create('ns4:PTZVector')\n dest.PanTilt._x=1\n dest.PanTilt._y=4.9\n dest.Zoom._x=1\n\n\n # Create 'speed' object to pass as an argument and values passed to this object\n speed = client.factory.create('ns4:PTZSpeed')\n speed.PanTilt._x=0\n speed.PanTilt._y=0\n speed.Zoom._x=1\n\n # 'AbsoluteMove' method invoked passing in the new values entered in the above objects\n\n try:\n result = client.service.AbsoluteMove(token, dest, speed)\n print \"absoluteMove result \", result\n return result\n except suds.WebFault, e:\n print \"suds.WebFaults caught: \"\n print e\n\nif __name__ == '__main__': result = absoluteMove()\n\nThis moves the camera. To change the type of soap-envelope check my next question.\nYou can add logging into this script whci allow's you to check what xml command you have sent which is handy:\nimport logging\nlogging.basicConfig(level=logging.INFO)\nlogging.getLogger('suds.client').setLevel(logging.DEBUG)\n\nThe location can be put into the script as an option if the location is not in the wsdl file.\n"
] |
[
22
] |
[] |
[] |
[
"python",
"soapheader",
"suds",
"wsdl",
"xml"
] |
stackoverflow_0002469988_python_soapheader_suds_wsdl_xml.txt
|
Q:
cache backend works on devserver but not mod_wsgi
I am using a custom cache backend to wrap the built-in cache backends so that I can add the current site_id to all the cache_keys (this is useful for multi-site functionality with a single memcached instance)
unfortunately it works great on the django built-in devserver, but give a nasty error when I try to run it on the live server with mod_wsgi
Here is the traceback from my error log:
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] mod_wsgi (pid=22933): Exception occurred processing WSGI script '/home/jiaaro/webapps/op_wsgi/myProject/deploy/myProject.wsgi'.
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] Traceback (most recent call last):
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] File "/home/jiaaro/webapps/op_wsgi/lib/python2.5/django/core/handlers/wsgi.py", line 230, in __call__
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] self.load_middleware()
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] File "/home/jiaaro/webapps/op_wsgi/lib/python2.5/django/core/handlers/base.py", line 40, in load_middleware
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] mod = import_module(mw_module)
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] File "/home/jiaaro/webapps/op_wsgi/lib/python2.5/django/utils/importlib.py", line 35, in import_module
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] __import__(name)
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] File "/home/jiaaro/webapps/op_wsgi/myProject/apps/site_settings/__init__.py", line 6, in <module>
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] import cache_wrapper
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] File "/home/jiaaro/webapps/op_wsgi/myProject/apps/site_settings/cache_wrapper.py", line 4, in <module>
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] from django.core.cache.backends.base import BaseCache
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] File "/home/jiaaro/webapps/op_wsgi/lib/python2.5/django/core/cache/__init__.py", line 73, in <module>
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] cache = get_cache(settings.CACHE_BACKEND)
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] File "/home/jiaaro/webapps/op_wsgi/lib/python2.5/django/core/cache/__init__.py", line 68, in get_cache
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] return getattr(module, 'CacheClass')(host, params)
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] AttributeError: 'module' object has no attribute 'CacheClass'
if I run the devserver on the same machine (the live server) it works fine... I am able to do this without trouble:
$ cd /home/jiaaro/webapps/op_wsgi/myProject
$ python2.5 manage.py runserver
and in a separate ssh session...
$ wget 127.0.0.1:8000
The pages are served correctly, using memcached, and the live database. is there something different about the way mod_wsgi imports modules that I should know about?
maybe something about the single-process, single-threaded nature of the devserver?
I have been struggling with this for days now, any help would be appreciated
Extra info:
Webfaction shared hosting (centos)
Apache 2
Python 2.5
Django 1.1.1
mod_wsgi 2.5
MySql 5.0
More Details:
- I have set the cache backend (and it is working since you can see it importing the correct module in the traceback)
- There is a class called "CacheClass" in the module:
site_settings/cache_wrapper.py :
from django.conf import settings
CACHE_BACKEND = getattr(settings, 'CUSTOM_CACHE_BACKEND')
from django.core.cache.backends.base import BaseCache
class CacheClass(BaseCache):
from decorators import accept_site
def __init__(self, *args):
from django.core.cache import get_cache
self.WRAPPED_CACHE = get_cache(CACHE_BACKEND)
@accept_site
def add(self, site, key, *args):
return self.WRAPPED_CACHE.add(self._key(site, key),*args)
@accept_site
def get(self, site, key, *args):
return self.WRAPPED_CACHE.get(self._key(site, key),*args)
... (all the rest of the wrapped methods)
def _key(self, site, key):
from exceptions import NoCurrentSite
if not site:
raise NoCurrentSite
return "%s|%s" % (site.id, key)
THe accept_site decorator works in conjunction with some middleware to figure out the current site. Here they are:
decorators.py:
def accept_site(fn):
def decorator(self, *args, **kwargs):
site = kwargs.get('site', None)
try:
del kwargs['site']
except KeyError:
pass
from .middleware import get_current_site
site = site or get_current_site()
if not site:
raise NoCurrentSite("The current site is not available via thread locals, please specify a site with the 'site' keyword argument")
return fn(self, site, *args, **kwargs)
return decorator
and the middleware.py
try:
from threading import local
except ImportError:
from django.utils._threading_local import local
from django.conf import settings
from django.contrib.sites.models import Site
DEFAULT_SITE_ID = 1
_thread_locals = local()
def get_current_site():
return getattr(_thread_locals, 'site', None)
def set_current_site(site):
setattr(_thread_locals, 'site', site)
class SiteSettings(object):
"""Middleware that gets various objects from the
request object and saves them in thread local storage."""
def process_request(self, request):
if settings.DEBUG:
site_id = request.GET.get('site_id', DEFAULT_SITE_ID)
else:
site_id = DEFAULT_SITE_ID
current_site_domain = request.META["HTTP_HOST"]
try:
current_site = Site.objects.get(domain__iexact=current_site_domain())
except:
current_site = Site.objects.get(id=site_id)
set_current_site(current_site)
All of this works using the devserver, using the same settings as the wsgi server and configured with the same python path (as far as I can see)
At this point I'm hoping I've created an import loop somewhere (though that wouldn't make sense that it only occurs in the devserver)
edit: I found a list of the differences between devserver and apache in the django docs which says,
Devserver adds installed apps to
sys.path, Apache does not.
Maybe that has something to do with it?
A:
Have you set the CACHE_BACKEND in your settings.py? When DEBUG=True, this is not an issue, as I believe a dummy backend is installed, but in production, you will need to set this value, presumedley even if you're writing your own backend.
cache backend docs
If that's set and you're still having issues, try switching to the dummy cache module or the local memory one (even though this isn't a good production setup) to see if those work, and if they do, you may be missing a package in your WSGI's python path like python-memcached
A:
The root of the issue was sys.path I had to make sure the mod_wsgi set up had the same sys.path as the dev server and that no extra copies of packages were left in places they didn't belong (from refactoring that wasn't applied to the server by version control somehow)
|
cache backend works on devserver but not mod_wsgi
|
I am using a custom cache backend to wrap the built-in cache backends so that I can add the current site_id to all the cache_keys (this is useful for multi-site functionality with a single memcached instance)
unfortunately it works great on the django built-in devserver, but give a nasty error when I try to run it on the live server with mod_wsgi
Here is the traceback from my error log:
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] mod_wsgi (pid=22933): Exception occurred processing WSGI script '/home/jiaaro/webapps/op_wsgi/myProject/deploy/myProject.wsgi'.
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] Traceback (most recent call last):
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] File "/home/jiaaro/webapps/op_wsgi/lib/python2.5/django/core/handlers/wsgi.py", line 230, in __call__
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] self.load_middleware()
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] File "/home/jiaaro/webapps/op_wsgi/lib/python2.5/django/core/handlers/base.py", line 40, in load_middleware
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] mod = import_module(mw_module)
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] File "/home/jiaaro/webapps/op_wsgi/lib/python2.5/django/utils/importlib.py", line 35, in import_module
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] __import__(name)
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] File "/home/jiaaro/webapps/op_wsgi/myProject/apps/site_settings/__init__.py", line 6, in <module>
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] import cache_wrapper
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] File "/home/jiaaro/webapps/op_wsgi/myProject/apps/site_settings/cache_wrapper.py", line 4, in <module>
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] from django.core.cache.backends.base import BaseCache
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] File "/home/jiaaro/webapps/op_wsgi/lib/python2.5/django/core/cache/__init__.py", line 73, in <module>
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] cache = get_cache(settings.CACHE_BACKEND)
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] File "/home/jiaaro/webapps/op_wsgi/lib/python2.5/django/core/cache/__init__.py", line 68, in get_cache
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] return getattr(module, 'CacheClass')(host, params)
[Wed Feb 17 00:39:34 2010] [error] [client 127.0.0.1] AttributeError: 'module' object has no attribute 'CacheClass'
if I run the devserver on the same machine (the live server) it works fine... I am able to do this without trouble:
$ cd /home/jiaaro/webapps/op_wsgi/myProject
$ python2.5 manage.py runserver
and in a separate ssh session...
$ wget 127.0.0.1:8000
The pages are served correctly, using memcached, and the live database. is there something different about the way mod_wsgi imports modules that I should know about?
maybe something about the single-process, single-threaded nature of the devserver?
I have been struggling with this for days now, any help would be appreciated
Extra info:
Webfaction shared hosting (centos)
Apache 2
Python 2.5
Django 1.1.1
mod_wsgi 2.5
MySql 5.0
More Details:
- I have set the cache backend (and it is working since you can see it importing the correct module in the traceback)
- There is a class called "CacheClass" in the module:
site_settings/cache_wrapper.py :
from django.conf import settings
CACHE_BACKEND = getattr(settings, 'CUSTOM_CACHE_BACKEND')
from django.core.cache.backends.base import BaseCache
class CacheClass(BaseCache):
from decorators import accept_site
def __init__(self, *args):
from django.core.cache import get_cache
self.WRAPPED_CACHE = get_cache(CACHE_BACKEND)
@accept_site
def add(self, site, key, *args):
return self.WRAPPED_CACHE.add(self._key(site, key),*args)
@accept_site
def get(self, site, key, *args):
return self.WRAPPED_CACHE.get(self._key(site, key),*args)
... (all the rest of the wrapped methods)
def _key(self, site, key):
from exceptions import NoCurrentSite
if not site:
raise NoCurrentSite
return "%s|%s" % (site.id, key)
THe accept_site decorator works in conjunction with some middleware to figure out the current site. Here they are:
decorators.py:
def accept_site(fn):
def decorator(self, *args, **kwargs):
site = kwargs.get('site', None)
try:
del kwargs['site']
except KeyError:
pass
from .middleware import get_current_site
site = site or get_current_site()
if not site:
raise NoCurrentSite("The current site is not available via thread locals, please specify a site with the 'site' keyword argument")
return fn(self, site, *args, **kwargs)
return decorator
and the middleware.py
try:
from threading import local
except ImportError:
from django.utils._threading_local import local
from django.conf import settings
from django.contrib.sites.models import Site
DEFAULT_SITE_ID = 1
_thread_locals = local()
def get_current_site():
return getattr(_thread_locals, 'site', None)
def set_current_site(site):
setattr(_thread_locals, 'site', site)
class SiteSettings(object):
"""Middleware that gets various objects from the
request object and saves them in thread local storage."""
def process_request(self, request):
if settings.DEBUG:
site_id = request.GET.get('site_id', DEFAULT_SITE_ID)
else:
site_id = DEFAULT_SITE_ID
current_site_domain = request.META["HTTP_HOST"]
try:
current_site = Site.objects.get(domain__iexact=current_site_domain())
except:
current_site = Site.objects.get(id=site_id)
set_current_site(current_site)
All of this works using the devserver, using the same settings as the wsgi server and configured with the same python path (as far as I can see)
At this point I'm hoping I've created an import loop somewhere (though that wouldn't make sense that it only occurs in the devserver)
edit: I found a list of the differences between devserver and apache in the django docs which says,
Devserver adds installed apps to
sys.path, Apache does not.
Maybe that has something to do with it?
|
[
"Have you set the CACHE_BACKEND in your settings.py? When DEBUG=True, this is not an issue, as I believe a dummy backend is installed, but in production, you will need to set this value, presumedley even if you're writing your own backend.\ncache backend docs\nIf that's set and you're still having issues, try switching to the dummy cache module or the local memory one (even though this isn't a good production setup) to see if those work, and if they do, you may be missing a package in your WSGI's python path like python-memcached\n",
"The root of the issue was sys.path I had to make sure the mod_wsgi set up had the same sys.path as the dev server and that no extra copies of packages were left in places they didn't belong (from refactoring that wasn't applied to the server by version control somehow)\n"
] |
[
1,
0
] |
[] |
[] |
[
"caching",
"django",
"memcached",
"python"
] |
stackoverflow_0002278662_caching_django_memcached_python.txt
|
Q:
How can I keep the system environments set by a bat file, which called by a python script
I call .bat files in Python to set system environments, and check the system environments were set properly, and then back to run python code, the system environments are changed back to original. How can I solve this problem?
A:
Environment settings always happen in the child process and never directly affect the parent process. However you can run (in the same child process that has changed its environment, at the very end of that process) a command (env in Unix-like environment, I believe set in DOS where .bat files lived and in Windows where .cmd files are similar) that outputs the environment to its standard-output, or to a file; the parent process can read that file and apply the changes to its own environment.
In Unix, subprocess.Popen('thescript; env', shell=True, stdout=...) may suffice. In Windows, I'm not sure passing as the first argument foo.bat; set would work; if it doesn't, just create a tiny temporary "auxiliary bat" that does foo.bat then set, and run that one instead.
A:
I suspect that you are calling the batch file from the Python program and then returning to the calling Python code. A child process - in this case your call to the batch file - does not affect the environment of the parent process (your batch file).
Batch files that set up an environment are usually written as:
# set up my environment
python myprogram.py
In this case the subordinate Python program will inherit the environment of the calling batch file.
|
How can I keep the system environments set by a bat file, which called by a python script
|
I call .bat files in Python to set system environments, and check the system environments were set properly, and then back to run python code, the system environments are changed back to original. How can I solve this problem?
|
[
"Environment settings always happen in the child process and never directly affect the parent process. However you can run (in the same child process that has changed its environment, at the very end of that process) a command (env in Unix-like environment, I believe set in DOS where .bat files lived and in Windows where .cmd files are similar) that outputs the environment to its standard-output, or to a file; the parent process can read that file and apply the changes to its own environment.\nIn Unix, subprocess.Popen('thescript; env', shell=True, stdout=...) may suffice. In Windows, I'm not sure passing as the first argument foo.bat; set would work; if it doesn't, just create a tiny temporary \"auxiliary bat\" that does foo.bat then set, and run that one instead.\n",
"I suspect that you are calling the batch file from the Python program and then returning to the calling Python code. A child process - in this case your call to the batch file - does not affect the environment of the parent process (your batch file). \nBatch files that set up an environment are usually written as:\n# set up my environment \npython myprogram.py\n\nIn this case the subordinate Python program will inherit the environment of the calling batch file.\n"
] |
[
3,
1
] |
[] |
[] |
[
"python",
"windows"
] |
stackoverflow_0002546197_python_windows.txt
|
Q:
Python and App Engine project structure
I am relatively new to python and app engine, and I just finished my first project.
It consists of several *.py files (usually py file for every page on the site) and respectively temple files for each py file.
In addition, I have one big PY file that has many functions that are common to a lot of pages, in I also declared the classes of db.Model (that is the datastore kinds).
My question is what is the convention (if there is one) of arranging these files.
If I create a model.py with the datastore classes, should it be in different package?
Where should I put my template files and all of the py files that handle every page (should they be in the same directory as the one big common PY file)?
I have tried to look for MVC and such implementations online but there are very few.
Thanks,
Joel
A:
I usually organize my projects in this way:
project
main.py
README
models
bar.py
foo.py
views
foolist.hml
barlist.hml
controllers
controller1.py
controller2.py
api
controllerapi.py
helpers
utilities.py
lib
extfoo.py
db
foo.db
test
test.py
Look at this post; it's a really great article on how to structure a project (not in python but it does not matter).
A:
Typically I organize like so:
project/
main.py
models.py
app.yaml
index.yaml
templates/
main.html
foo.html
...
styles/
project.css
js/
jquery.js
project.js
images/
icon.png
something.jpg
And I have all of my handlers in main.py, all of my models in models.py, etc.
If I have a lot of handlers, and I can easily split the functionality of some handlers from the others (like taskqueue handlers vs. request handlers vs. xmpp/email handlers) I'll add another foo_handlers.py to the mix, but usually I just cram them all in main.py
But then again, I tend not to write hugely complex Python App Engine apps...
|
Python and App Engine project structure
|
I am relatively new to python and app engine, and I just finished my first project.
It consists of several *.py files (usually py file for every page on the site) and respectively temple files for each py file.
In addition, I have one big PY file that has many functions that are common to a lot of pages, in I also declared the classes of db.Model (that is the datastore kinds).
My question is what is the convention (if there is one) of arranging these files.
If I create a model.py with the datastore classes, should it be in different package?
Where should I put my template files and all of the py files that handle every page (should they be in the same directory as the one big common PY file)?
I have tried to look for MVC and such implementations online but there are very few.
Thanks,
Joel
|
[
"I usually organize my projects in this way:\nproject \n main.py\n README\n models\n bar.py\n foo.py\n views\n foolist.hml\n barlist.hml\n controllers\n controller1.py\n controller2.py\n api\n controllerapi.py\n helpers\n utilities.py\n lib\n extfoo.py\n db\n foo.db\n test\n test.py\n\nLook at this post; it's a really great article on how to structure a project (not in python but it does not matter).\n",
"Typically I organize like so:\nproject/\n main.py\n models.py\n app.yaml\n index.yaml\n templates/\n main.html\n foo.html\n ...\n styles/\n project.css\n js/\n jquery.js\n project.js\n images/\n icon.png\n something.jpg\n\nAnd I have all of my handlers in main.py, all of my models in models.py, etc.\nIf I have a lot of handlers, and I can easily split the functionality of some handlers from the others (like taskqueue handlers vs. request handlers vs. xmpp/email handlers) I'll add another foo_handlers.py to the mix, but usually I just cram them all in main.py\nBut then again, I tend not to write hugely complex Python App Engine apps...\n"
] |
[
3,
3
] |
[] |
[] |
[
"google_app_engine",
"python"
] |
stackoverflow_0002546199_google_app_engine_python.txt
|
Q:
Python Process won't call atexit
I'm trying to use atexit in a Process, but unfortunately it doesn't seem to work. Here's some example code:
import time
import atexit
import logging
import multiprocessing
logging.basicConfig(level=logging.DEBUG)
class W(multiprocessing.Process):
def run(self):
logging.debug("%s Started" % self.name)
@atexit.register
def log_terminate():
# ever called?
logging.debug("%s Terminated!" % self.name)
while True:
time.sleep(10)
@atexit.register
def log_exit():
logging.debug("Main process terminated")
logging.debug("Main process started")
a = W()
b = W()
a.start()
b.start()
time.sleep(1)
a.terminate()
b.terminate()
The output of this code is:
DEBUG:root:Main process started
DEBUG:root:W-1 Started
DEBUG:root:W-2 Started
DEBUG:root:Main process terminated
I would expect that the W.run.log_terminate() would be called when a.terminate() and b.terminate() are called, and the output to be something likeso (emphasis added)!:
DEBUG:root:Main process started
DEBUG:root:W-1 Started
DEBUG:root:W-2 Started
DEBUG:root:W-1 Terminated!
DEBUG:root:W-2 Terminated!
DEBUG:root:Main process terminated
Why isn't this working, and is there a better way to log a message (from the Process context) when a Process is terminated?
Thank you for your input - it's much appreciated.
Solution
EDIT: Based on solution suggested by Alex Martelli, the following works as expected:
import sys
import time
import atexit
import signal
import logging
import multiprocessing
logging.basicConfig(level=logging.DEBUG)
class W(multiprocessing.Process):
def run(self):
logging.debug("%s Started" % self.name)
def log_terminate(num, frame):
logging.debug("%s Terminated" % self.name)
sys.exit()
signal.signal(signal.SIGTERM, log_terminate)
while True:
time.sleep(10)
@atexit.register
def log_exit():
logging.debug("Main process terminated")
logging.debug("Main process started")
a = W()
b = W()
a.start()
b.start()
time.sleep(1)
a.terminate()
b.terminate()
It's worthwhile to note the following comment in the atexit documentation:
Note: the functions registered via this module are not called when the program is killed by a signal, when a Python fatal internal error is detected, or when os._exit() is called.
A:
As the docs say,
On Unix this is done using the SIGTERM
signal; on Windows TerminateProcess()
is used. Note that exit handlers and
finally clauses, etc., will not be
executed.
If you're on Unix, you should be able intercept SIGTERM with signal, and perform whatever "termination activities" you need; however, I don't know of a cross-platform solution.
|
Python Process won't call atexit
|
I'm trying to use atexit in a Process, but unfortunately it doesn't seem to work. Here's some example code:
import time
import atexit
import logging
import multiprocessing
logging.basicConfig(level=logging.DEBUG)
class W(multiprocessing.Process):
def run(self):
logging.debug("%s Started" % self.name)
@atexit.register
def log_terminate():
# ever called?
logging.debug("%s Terminated!" % self.name)
while True:
time.sleep(10)
@atexit.register
def log_exit():
logging.debug("Main process terminated")
logging.debug("Main process started")
a = W()
b = W()
a.start()
b.start()
time.sleep(1)
a.terminate()
b.terminate()
The output of this code is:
DEBUG:root:Main process started
DEBUG:root:W-1 Started
DEBUG:root:W-2 Started
DEBUG:root:Main process terminated
I would expect that the W.run.log_terminate() would be called when a.terminate() and b.terminate() are called, and the output to be something likeso (emphasis added)!:
DEBUG:root:Main process started
DEBUG:root:W-1 Started
DEBUG:root:W-2 Started
DEBUG:root:W-1 Terminated!
DEBUG:root:W-2 Terminated!
DEBUG:root:Main process terminated
Why isn't this working, and is there a better way to log a message (from the Process context) when a Process is terminated?
Thank you for your input - it's much appreciated.
Solution
EDIT: Based on solution suggested by Alex Martelli, the following works as expected:
import sys
import time
import atexit
import signal
import logging
import multiprocessing
logging.basicConfig(level=logging.DEBUG)
class W(multiprocessing.Process):
def run(self):
logging.debug("%s Started" % self.name)
def log_terminate(num, frame):
logging.debug("%s Terminated" % self.name)
sys.exit()
signal.signal(signal.SIGTERM, log_terminate)
while True:
time.sleep(10)
@atexit.register
def log_exit():
logging.debug("Main process terminated")
logging.debug("Main process started")
a = W()
b = W()
a.start()
b.start()
time.sleep(1)
a.terminate()
b.terminate()
It's worthwhile to note the following comment in the atexit documentation:
Note: the functions registered via this module are not called when the program is killed by a signal, when a Python fatal internal error is detected, or when os._exit() is called.
|
[
"As the docs say, \n\nOn Unix this is done using the SIGTERM\n signal; on Windows TerminateProcess()\n is used. Note that exit handlers and\n finally clauses, etc., will not be\n executed.\n\nIf you're on Unix, you should be able intercept SIGTERM with signal, and perform whatever \"termination activities\" you need; however, I don't know of a cross-platform solution.\n"
] |
[
18
] |
[] |
[] |
[
"atexit",
"multiprocessing",
"python",
"terminate"
] |
stackoverflow_0002546276_atexit_multiprocessing_python_terminate.txt
|
Q:
Cleaning an XML file in Python before parsing
I'm using minidom to parse an xml file and it threw an error indicating that the data is not well formed. I figured out that some of the pages have characters like ไà¸à¹€à¸Ÿà¸¥ &, causing the parser to hiccup. Is there an easy way to clean the file before I start parsing it? Right now I'm using a regular expressing to throw away anything that isn't an alpha numeric character and the </> characters, but it isn't quite working.
A:
Try
xmltext = re.sub(u"[^\x20-\x7f]+",u"",xmltext)
It will get rid of everything except 0x20-0x7F range.
You may start from \x01, if you want want to keep control characters like tab, line breaks.
xmltext = re.sub(u"[^\x01-\x7f]+",u"",xmltext)
A:
Take a look at µTidyLib, a Python wrapper to TidyLib.
A:
If you do need the data with the strange characters you could, in stead of just stripping them, convert them to codes the XML parser can understand.
You could have a look at the unicodedata package, especially the normalize method.
I haven't used it myself, so I can't tell you all that much, but you could ask again here on SO if you decide you're going to convert and keep that data.
>>> import unicodedata
>>> unicodedata.normalize("NFKD" , u"ไภเฟล &")
u'a\u03001\u201ea\u0300 \u0327 a\u03001\u20aca\u0300 \u0327Y\u0308a\u0300 \u0327\xa5 &'
A:
It looks like you're dealing with data which are saved with some kind of encoding "as if" they were ASCII. XML file should normally be UTF8, and SAX (the underlying parser used by minidom) should handle that, so it looks like something's wrong in that part of the processing chain. Instead of focusing on "cleaning up" I'd first try to make sure the encoding is correct and correctly recognized. Maybe a broken XML directive? Can you edit your Q to show the first few lines of the file, especially the <?xml ... directive at the very start?
|
Cleaning an XML file in Python before parsing
|
I'm using minidom to parse an xml file and it threw an error indicating that the data is not well formed. I figured out that some of the pages have characters like ไà¸à¹€à¸Ÿà¸¥ &, causing the parser to hiccup. Is there an easy way to clean the file before I start parsing it? Right now I'm using a regular expressing to throw away anything that isn't an alpha numeric character and the </> characters, but it isn't quite working.
|
[
"Try\nxmltext = re.sub(u\"[^\\x20-\\x7f]+\",u\"\",xmltext)\n\nIt will get rid of everything except 0x20-0x7F range.\nYou may start from \\x01, if you want want to keep control characters like tab, line breaks.\nxmltext = re.sub(u\"[^\\x01-\\x7f]+\",u\"\",xmltext)\n\n",
"Take a look at µTidyLib, a Python wrapper to TidyLib.\n",
"If you do need the data with the strange characters you could, in stead of just stripping them, convert them to codes the XML parser can understand.\nYou could have a look at the unicodedata package, especially the normalize method.\nI haven't used it myself, so I can't tell you all that much, but you could ask again here on SO if you decide you're going to convert and keep that data.\n>>> import unicodedata\n>>> unicodedata.normalize(\"NFKD\" , u\"ไภเฟล &\")\nu'a\\u03001\\u201ea\\u0300 \\u0327 a\\u03001\\u20aca\\u0300 \\u0327Y\\u0308a\\u0300 \\u0327\\xa5 &'\n\n",
"It looks like you're dealing with data which are saved with some kind of encoding \"as if\" they were ASCII. XML file should normally be UTF8, and SAX (the underlying parser used by minidom) should handle that, so it looks like something's wrong in that part of the processing chain. Instead of focusing on \"cleaning up\" I'd first try to make sure the encoding is correct and correctly recognized. Maybe a broken XML directive? Can you edit your Q to show the first few lines of the file, especially the <?xml ... directive at the very start?\n"
] |
[
3,
1,
0,
0
] |
[
"I'd throw out all non-ASCII characters which can be identified by having the 8th bit (0x80) set (128 .. 255 respectively 0x80 .. 0xff).\n\nYou could read in the file into a Python string named old_str\nThen perform a filter call in conjunction with a lambda statement:\nnew_str = filter(lambda x: x in string.ascii_letters, old_str)\n\nParse new_str\n\nMany ways exist to accomplish stripping non-ASCII characters from a string.\nThis question might be related: How to check if a string in Python is in ASCII?\n"
] |
[
-1
] |
[
"python",
"xml"
] |
stackoverflow_0002545783_python_xml.txt
|
Q:
xmlrpc client call in python does not come back
Using Python 2.6.4, windows
With the following script I want to test a certain xmlrpc server. I call a non-existent function and hope for a traceback with an error. Instead, the function does not return. What could be the cause?
import xmlrpclib
s = xmlrpclib.Server("http://127.0.0.1:80", verbose=True)
s.functioncall()
The output is:
send: 'POST /RPC2 HTTP/1.0\r\nHost: 127.0.0.1:80\r\nUser-Agent: xmlrpclib.py/1.0
.1 (by www.pythonware.com)\r\nContent-Type: text/xml\r\nContent-Length: 106\r\n\
r\n'
send: "<?xml version='1.0'?>\n<methodCall>\n<methodName>functioncall</methodName
>\n<params>\n</params>\n</methodCall>\n"
reply: 'HTTP/1.1 200 OK\r\n'
header: Content-Type: text/xml
header: Cache-Control: no-cache
header: Content-Length: 376
header: Date: Tue, 30 Mar 2010 13:27:21 GMT
body: '<?xml version="1.0"?>\r\n<methodResponse>\r\n<fault>\r\n<value>\r\n<struc
t>\r\n<member>\r\n<name>faultCode</name>\r\n<value><i4>1</i4></value>\r\n</membe
r>\r\n<member>\r\n<name>faultString</name>\r\n<value><string>PVSS00ctrl (2), 2
010.03.30 15:27:21.395, CTRL, SEVERE, 72, Function not defined, functioncall
, , \n</string></value>\r\n</member>\r\n</struct>\r\n</value>\r\n</fault>\r\n</m
ethodResponse>\r\n'
(here the program hangs and does not return until I kill the server)
edit: the server is written in c++, using its own xmlrpc library
edit: found an issue that looks like the same problem http://bugs.python.org/issue1727418
A:
As you noticed, this is a bug in the server (the client claims to understand 1.0 and the server ignores that and responds in 1.1 anyway, so doesn't close the socket). Python has a workaround for such buggy servers in 2.7 and 3.2, see this issue, but that workaround wasn't in 2.6.4. Unfortunately, from 2.6.5's NEWS.txt it looks like we haven't backported it to 2.6.5 either. The patch for the workaround in 2.7 is here, perhaps you can try applying it to 2.6.5 yourself if it's just impossible to fix the buggy server...?
A:
Most likely, the server you're testing does not close the TCP connection once it has sent the response back to your client. Thus the client hangs, waiting for the server to close the connection before it can return from the function.
|
xmlrpc client call in python does not come back
|
Using Python 2.6.4, windows
With the following script I want to test a certain xmlrpc server. I call a non-existent function and hope for a traceback with an error. Instead, the function does not return. What could be the cause?
import xmlrpclib
s = xmlrpclib.Server("http://127.0.0.1:80", verbose=True)
s.functioncall()
The output is:
send: 'POST /RPC2 HTTP/1.0\r\nHost: 127.0.0.1:80\r\nUser-Agent: xmlrpclib.py/1.0
.1 (by www.pythonware.com)\r\nContent-Type: text/xml\r\nContent-Length: 106\r\n\
r\n'
send: "<?xml version='1.0'?>\n<methodCall>\n<methodName>functioncall</methodName
>\n<params>\n</params>\n</methodCall>\n"
reply: 'HTTP/1.1 200 OK\r\n'
header: Content-Type: text/xml
header: Cache-Control: no-cache
header: Content-Length: 376
header: Date: Tue, 30 Mar 2010 13:27:21 GMT
body: '<?xml version="1.0"?>\r\n<methodResponse>\r\n<fault>\r\n<value>\r\n<struc
t>\r\n<member>\r\n<name>faultCode</name>\r\n<value><i4>1</i4></value>\r\n</membe
r>\r\n<member>\r\n<name>faultString</name>\r\n<value><string>PVSS00ctrl (2), 2
010.03.30 15:27:21.395, CTRL, SEVERE, 72, Function not defined, functioncall
, , \n</string></value>\r\n</member>\r\n</struct>\r\n</value>\r\n</fault>\r\n</m
ethodResponse>\r\n'
(here the program hangs and does not return until I kill the server)
edit: the server is written in c++, using its own xmlrpc library
edit: found an issue that looks like the same problem http://bugs.python.org/issue1727418
|
[
"As you noticed, this is a bug in the server (the client claims to understand 1.0 and the server ignores that and responds in 1.1 anyway, so doesn't close the socket). Python has a workaround for such buggy servers in 2.7 and 3.2, see this issue, but that workaround wasn't in 2.6.4. Unfortunately, from 2.6.5's NEWS.txt it looks like we haven't backported it to 2.6.5 either. The patch for the workaround in 2.7 is here, perhaps you can try applying it to 2.6.5 yourself if it's just impossible to fix the buggy server...?\n",
"Most likely, the server you're testing does not close the TCP connection once it has sent the response back to your client. Thus the client hangs, waiting for the server to close the connection before it can return from the function.\n"
] |
[
5,
2
] |
[] |
[] |
[
"client",
"python",
"xml_rpc"
] |
stackoverflow_0002545655_client_python_xml_rpc.txt
|
Q:
py2app prescripts
The py2app documentation mentions prescripts, being run by __boot__.py prior to the main python script. I couldn't find a way to easily specify any prescript on the setup.py file or build process.
I did however manage to 'hack' __boot__.py manually and add another _run(prescript) command before my main _run(main_script) and it seemed to work fine. It would however be much better using the standard py2app build process.
What I'm essentially trying to do is monkey-patch my sites-packages.zip file prior to the main script being launched. The prescript essentially checks for updates on the server, and if there are any, downloads them, and then overwrites the site-packages.zip file. Much quicker than having to re-install the application from scratch.
Any ideas?
A:
See the docs: your py2app.recipes package must contain a recipe whose check method returns a dict including the 'prescripts' key whose value is, and I quote,
A list of additional Python scripts to
run before initializing the main
script. This is often used to
monkey-patch included modules so that
they work in a frozen environment. The
prescripts may be module names, file
names, or file-like objects containing
Python code (e.g. StringIO). Note that
if a file-like object is used, it will
not currently be scanned for
additional dependencies.
See the built-in recipes sources for examples. This package (as installed on your machine) is where you'll need to add your own custom recipes.
|
py2app prescripts
|
The py2app documentation mentions prescripts, being run by __boot__.py prior to the main python script. I couldn't find a way to easily specify any prescript on the setup.py file or build process.
I did however manage to 'hack' __boot__.py manually and add another _run(prescript) command before my main _run(main_script) and it seemed to work fine. It would however be much better using the standard py2app build process.
What I'm essentially trying to do is monkey-patch my sites-packages.zip file prior to the main script being launched. The prescript essentially checks for updates on the server, and if there are any, downloads them, and then overwrites the site-packages.zip file. Much quicker than having to re-install the application from scratch.
Any ideas?
|
[
"See the docs: your py2app.recipes package must contain a recipe whose check method returns a dict including the 'prescripts' key whose value is, and I quote,\n\nA list of additional Python scripts to\n run before initializing the main\n script. This is often used to\n monkey-patch included modules so that\n they work in a frozen environment. The\n prescripts may be module names, file\n names, or file-like objects containing\n Python code (e.g. StringIO). Note that\n if a file-like object is used, it will\n not currently be scanned for\n additional dependencies.\n\nSee the built-in recipes sources for examples. This package (as installed on your machine) is where you'll need to add your own custom recipes.\n"
] |
[
2
] |
[] |
[] |
[
"monkeypatching",
"py2app",
"python"
] |
stackoverflow_0002544619_monkeypatching_py2app_python.txt
|
Q:
Create static instances of a class inside said class in Python
Apologies if I've got the terminology wrong here—I can't think what this particular idiom would be called.
I've been trying to create a Python 3 class that statically declares instances of itself inside itself—sort of like an enum would work. Here's a simplified version of the code I wrote:
class Test:
A = Test("A")
B = Test("B")
def __init__(self, value):
self.value = value
def __str__(self):
return "Test: " + self.value
print(str(Test.A))
print(str(Test.B))
Writing this, I got an exception on line 2 (A = Test("A")). I assume line 3 would also error if it had made it that far. Using __class__ instead of Test gives the same error.
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in Test
NameError: name 'Test' is not defined
Is there any way to refer to the current class in a static context in Python? I could declare these particular variables outside the class or in a separate class, but for clarity's sake, I'd rather not if I can help it.
To better demonstrate what I'm trying to do, here's the same example in Java:
public class Test {
private static final Test A = new Test("A");
private static final Test B = new Test("B");
private final String value;
public Test(String value) {
this.value = value;
}
public String toString() {
return "Test: " + value;
}
public static void main(String[] args) {
System.out.println(A);
System.out.println(B);
}
}
This works as you would expect: it prints:
Test: A
Test: B
How can I do the same thing in Python?
A:
After you defined the class, just add these two lines:
Test.A = Test("A")
Test.B = Test("B")
A class in Python is an object like any other and you can add new variables at any time. You just can't do it inside the class since it's not defined at that time (it will be added to the symbol table only after the whole code for the class has been parsed correctly).
A:
In Python, a class block isn't just a declaration; it's executed at run time to build the class. Each def inside the class builds a function and binds the name into the class's namespace. For that reason, you can't simply do A = MyClass() directly inside the class block, because MyClass() isn't fully defined until the class block closes. Here's how to do it:
class Test:
def __init__(self, value):
self.value = value
def __str__(self):
return "Test: " + self.value
Test.A = Test("A")
Test.B = Test("B")
A:
While the Aaron's answer is the preferred way you can also use metaclasses:
>>> class TestMeta(type):
... def __init__(cls, name, bases, dct):
... cls.A = cls()
... cls.B = cls()
...
>>> class Test:
... __metaclass__ = TestMeta
...
>>> Test
<class __main__.Test at 0x7f70f8799770>
>>> Test.A
<__main__.Test object at 0x7f70f86f2e10>
>>> Test.B
<__main__.Test object at 0x7f70f86f2e90>
>>>
|
Create static instances of a class inside said class in Python
|
Apologies if I've got the terminology wrong here—I can't think what this particular idiom would be called.
I've been trying to create a Python 3 class that statically declares instances of itself inside itself—sort of like an enum would work. Here's a simplified version of the code I wrote:
class Test:
A = Test("A")
B = Test("B")
def __init__(self, value):
self.value = value
def __str__(self):
return "Test: " + self.value
print(str(Test.A))
print(str(Test.B))
Writing this, I got an exception on line 2 (A = Test("A")). I assume line 3 would also error if it had made it that far. Using __class__ instead of Test gives the same error.
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in Test
NameError: name 'Test' is not defined
Is there any way to refer to the current class in a static context in Python? I could declare these particular variables outside the class or in a separate class, but for clarity's sake, I'd rather not if I can help it.
To better demonstrate what I'm trying to do, here's the same example in Java:
public class Test {
private static final Test A = new Test("A");
private static final Test B = new Test("B");
private final String value;
public Test(String value) {
this.value = value;
}
public String toString() {
return "Test: " + value;
}
public static void main(String[] args) {
System.out.println(A);
System.out.println(B);
}
}
This works as you would expect: it prints:
Test: A
Test: B
How can I do the same thing in Python?
|
[
"After you defined the class, just add these two lines:\nTest.A = Test(\"A\")\nTest.B = Test(\"B\")\n\nA class in Python is an object like any other and you can add new variables at any time. You just can't do it inside the class since it's not defined at that time (it will be added to the symbol table only after the whole code for the class has been parsed correctly).\n",
"In Python, a class block isn't just a declaration; it's executed at run time to build the class. Each def inside the class builds a function and binds the name into the class's namespace. For that reason, you can't simply do A = MyClass() directly inside the class block, because MyClass() isn't fully defined until the class block closes. Here's how to do it:\nclass Test:\n def __init__(self, value):\n self.value = value\n\n def __str__(self):\n return \"Test: \" + self.value\n\nTest.A = Test(\"A\")\nTest.B = Test(\"B\")\n\n",
"While the Aaron's answer is the preferred way you can also use metaclasses:\n>>> class TestMeta(type):\n... def __init__(cls, name, bases, dct):\n... cls.A = cls()\n... cls.B = cls()\n... \n>>> class Test:\n... __metaclass__ = TestMeta\n... \n>>> Test\n<class __main__.Test at 0x7f70f8799770>\n>>> Test.A\n<__main__.Test object at 0x7f70f86f2e10>\n>>> Test.B\n<__main__.Test object at 0x7f70f86f2e90>\n>>> \n\n"
] |
[
22,
4,
4
] |
[] |
[] |
[
"python"
] |
stackoverflow_0002546608_python.txt
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.