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:
how to do certain data processing in python?
I have two lists of strings, which have the following format:
[x1,x2,x3,x4,...] [y1,y2,y3,y4...]
Call it lst1.
lst2 would be:
[x1',x2',x3',x4',...] [y1,y2,y3,y4,...]
you can assume that each string in lst1 has matching y's in the corresponding element in lst2, and the same number of x's, but it would be great to throw an error if some x and x' is not of the same length.
Then, I want to merge lst1 and lst2, in the following way:
create a new list of strings where:
[x1-x1',x2-x2',....] [y1,y2,y3,y4...]
I am really curious to see what kind of solutions would come up with that... I am new to python and I want to see what kind of different ways there are to do things for a data processing of this type (which I do a lot).
Thanks.
A:
(sub(a,b) for (a,b) in itertools.izip(lst1, lst2))
where sub() is whatever kind of 'substracting' you want to do between respective strings
A:
Based on the comment above, that - is not actually a subtraction, but a dash in a string,
Furthermore depending on how you want to deal with the result? As a list:
["%s-%s"%(a,b) for (a,b) in itertools.izip(lst1, lst2)]
Or as an iterator:
("%s-%s"%(a,b) for (a,b) in itertools.izip(lst1, lst2))
Also, instead of itertools.izip you can just use zip but I don't know the implications of that.
A:
Oh wait - -you have two Strings, with brackets and items as characters in it?
That is what I infere from your comment """ The list is of strings which look like this: "[a,b,c,d,e] [x,y,z,w,u]" -- meaning two bracketed substrings – stler 28 mins ago """ -
That is a totally different thing form what one understands from your question, as lists are native objects in python.
To process a string like that, you have to break it apart (using the split method) on the "]" character, and then at the comas:
lst1 = "[a,b,c,d,e] [x,y,z,w,u]"
lst2 = "[1,2,3,4,5] [x,y,z,w,u]"
# part the strings in two parts:
part1, part2 = lst1.split("]",1)
# isolate the elements in part1:
part1 = part1.split(",")
# separate the desired elements from string 2: split at "]", throw "[" away, split at ",":
part3= lst2.split("]")[0].strip("[").split(",")
parts_list = []
for element1, element2 in zip(part1, part3):
if len(element1.strip("[")) != len(element2):
raise ValueError("List parts differ in lenght")
parts_list.append("%s-%s" % (element1, element2))
final_list = ",".join(parts_list) + "]" + part2
| how to do certain data processing in python? | I have two lists of strings, which have the following format:
[x1,x2,x3,x4,...] [y1,y2,y3,y4...]
Call it lst1.
lst2 would be:
[x1',x2',x3',x4',...] [y1,y2,y3,y4,...]
you can assume that each string in lst1 has matching y's in the corresponding element in lst2, and the same number of x's, but it would be great to throw an error if some x and x' is not of the same length.
Then, I want to merge lst1 and lst2, in the following way:
create a new list of strings where:
[x1-x1',x2-x2',....] [y1,y2,y3,y4...]
I am really curious to see what kind of solutions would come up with that... I am new to python and I want to see what kind of different ways there are to do things for a data processing of this type (which I do a lot).
Thanks.
| [
"(sub(a,b) for (a,b) in itertools.izip(lst1, lst2))\n\nwhere sub() is whatever kind of 'substracting' you want to do between respective strings\n",
"Based on the comment above, that - is not actually a subtraction, but a dash in a string,\nFurthermore depending on how you want to deal with the result? As a list:\... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004046062_python.txt |
Q:
quick data processing with python?
I have a file in the following format:
[s1,s2,s3,s4,...] SOME_TEXT
(per line)
For example:
[dog,cat,monkey] 1,2,3
[a,b,c,d,e,f] 13,4,6
the brackets are included.
let's say I have another field like this, which contains two lines:
[banana,cat2,monkey2] 1,2,3
[a2,b2,c2,d,e,f] 13,4,6
I want to take two files of this form and align them the following way:
[dog^banana,cat^cat2,monkey^monkey2] 1,2,3
[a^a2,b^b2,c^c2,d^d2,e^e2,f^f2] 13,4,6
while making sure that "SOME TEXT" in corresponding lines (such as 1,2,3 and 13,4,6) is the same and that the number of elements in the brackets in each corresponding line is the same. What would be a quick compact way to do it?
Thanks.
A:
def read_file(fp,hash):
for l in fp:
p = l[1:].find(']')
k = l[p+3:-1]
v = l[1:p+1].split(",")
if k not in hash:
hash[k] = v
else:
hash[k] = zip(hash[k], v)
hash = {}
for fname in ('f1.txt', 'f2.txt'):
with open(fname) as fp:
read_file(fp, hash)
for k,v in hash.items():
print "[{0}] {1}".format(",".join("^".join(vv) for vv in v), k)
This is a basic way to do it, if you need the lines in the files in the order they were read you'll have to do a bit more work.
Here's the output I get:
[a^a2,b^b2,c^c2,d^d,e^e,f^f] 13,4,6
[dog^banana,cat^cat2,monkey^monkey2] 1,2,3
Edit:
This also assumes that each key ie. 13,4,6 appears once in a file. If it can appear multiple times you'll have to change the hash[k] = zip(hash[k],v) to something more elaborate such has
if k not in hash:
hash[k] = [[vv] for vv in v]
else:
for i,vv in enumerate(v):
hash[k][i].append(vv)
A:
I'd use a regex to chop off everything after the first ] (and hang on to it). Then another regex to explode the string into an array. Then do whatever you need to do to it with regards to merging different arrays from different files, and then piecing it all back together shouldn't be too hard. I'll leave the regex's as an exercise for the reader :-)
A:
for l, m in zip(f1, f2):
l_head, l_tail = l.strip("[ ").split("]")
m_head, m_tail = m.strip("[ ").split("]")
l_head = l_head.split(",")
m_head = m_head.split(",")
assert len(l_head) == len(m_head)
l_tail = l_tail.split(",")
m_tail = m_tail.split(",")
assert len(l_tail) == len(m_tail)
...
I haven't given your variables good names because I don't know what they are. I would name them something more useful.
I also haven't written the code for reassembling the lines. It shouldn't be too hard...
| quick data processing with python? | I have a file in the following format:
[s1,s2,s3,s4,...] SOME_TEXT
(per line)
For example:
[dog,cat,monkey] 1,2,3
[a,b,c,d,e,f] 13,4,6
the brackets are included.
let's say I have another field like this, which contains two lines:
[banana,cat2,monkey2] 1,2,3
[a2,b2,c2,d,e,f] 13,4,6
I want to take two files of this form and align them the following way:
[dog^banana,cat^cat2,monkey^monkey2] 1,2,3
[a^a2,b^b2,c^c2,d^d2,e^e2,f^f2] 13,4,6
while making sure that "SOME TEXT" in corresponding lines (such as 1,2,3 and 13,4,6) is the same and that the number of elements in the brackets in each corresponding line is the same. What would be a quick compact way to do it?
Thanks.
| [
"def read_file(fp,hash):\n for l in fp:\n p = l[1:].find(']')\n k = l[p+3:-1]\n v = l[1:p+1].split(\",\")\n if k not in hash:\n hash[k] = v\n else:\n hash[k] = zip(hash[k], v)\n\nhash = {}\n\nfor fname in ('f1.txt', 'f2.txt'):\n with open(fname) as fp:\... | [
3,
0,
0
] | [] | [] | [
"python"
] | stackoverflow_0004046641_python.txt |
Q:
one-many relationship-google datastore-python
I have two models like below:-
class Food(db.Model):
foodname=db.StringProperty()
cook=db.StringProperty()
class FoodReview(db.Model):
thereview=db.StringProperty()
reviews=db.ReferenceProperty(Food,collections_name='thefoodreviews')
I go ahead and create an entity:-
s=Food(foodname='apple',cook='Alice')`
s.put()
When someone writes a review, the function which does the below comes in play:
theentitykey=db.Query(Food,keys_only=True).filter('foodname =','apple').get()
r=FoodReview()
r.reviews=theentitykey #this is the key of the entity retrieved above and stored as a ref property here
r.thereview='someones review' #someone writes a review
r.put()
Now the problem is how to retrieve these reviews. If I know the key of the entity, I can just do the below:-
theentityobject=db.get(food-key) # but then the issue is how to know the key
for elem in theentityobject.thefoodreviews:
print elem.thereview
else I can do something like this:-
theentityobj=db.Query(Food).filter('foodname =','apple').get()
and then iterate as above, but are the above two ways the correct ones?
A:
If to get the food you're always doing db.Query(Food).filter('foodname =','apple') then it looks like your foodname is your key...
Why not just use it as a key_name?
Then, you can even fetch the reviews without fetching the food itself:
key = db.Key.from_path('food', 'apple')
reviews = FoodReview.all().filter("reviews =", key)
A:
The second method looks exactly like what AppEngine tutorial advices.
Seems like the right thing to do, if you want to find all reviews for a particular foodname.
| one-many relationship-google datastore-python | I have two models like below:-
class Food(db.Model):
foodname=db.StringProperty()
cook=db.StringProperty()
class FoodReview(db.Model):
thereview=db.StringProperty()
reviews=db.ReferenceProperty(Food,collections_name='thefoodreviews')
I go ahead and create an entity:-
s=Food(foodname='apple',cook='Alice')`
s.put()
When someone writes a review, the function which does the below comes in play:
theentitykey=db.Query(Food,keys_only=True).filter('foodname =','apple').get()
r=FoodReview()
r.reviews=theentitykey #this is the key of the entity retrieved above and stored as a ref property here
r.thereview='someones review' #someone writes a review
r.put()
Now the problem is how to retrieve these reviews. If I know the key of the entity, I can just do the below:-
theentityobject=db.get(food-key) # but then the issue is how to know the key
for elem in theentityobject.thefoodreviews:
print elem.thereview
else I can do something like this:-
theentityobj=db.Query(Food).filter('foodname =','apple').get()
and then iterate as above, but are the above two ways the correct ones?
| [
"If to get the food you're always doing db.Query(Food).filter('foodname =','apple') then it looks like your foodname is your key...\nWhy not just use it as a key_name?\nThen, you can even fetch the reviews without fetching the food itself:\nkey = db.Key.from_path('food', 'apple')\nreviews = FoodReview.all().filter(... | [
1,
0
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004045001_google_app_engine_python.txt |
Q:
Django-CMS 500 error when clicking to add a plugin
Hey guys, when clicking to add a new plugin ("Add Plugin" on a "Page" I get a 500 error. Using firebug I got this traceback:
Environment:
Request Method: POST
Request URL: http://192.168.1.10:81/admin/cms/page/1/add-plugin/
Django Version: 1.2.3
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'cms',
'cms.plugins.text',
'cms.plugins.picture',
'cms.plugins.link',
'cms.plugins.file',
'cms.plugins.snippet',
'cms.plugins.googlemap',
'mptt',
'publisher']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.media.PlaceholderMediaMiddleware')
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapped_view
76. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
69. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in inner
190. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django_cms-2.1.0.beta3-py2.6.egg/cms/admin/pageadmin.py" in add_plugin
1061. placeholder = get_object_or_404(Placeholder, pk=placeholder_id)
File "/usr/local/lib/python2.6/dist-packages/django/shortcuts/__init__.py" in get_object_or_404
88. return queryset.get(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in get
333. clone = self.filter(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in filter
550. return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in _filter_or_exclude
568. clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py" in add_q
1128. can_reuse=used_aliases)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py" in add_filter
1071. connector)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/where.py" in add
66. value = obj.prepare(lookup_type, value)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/where.py" in prepare
299. return self.field.get_prep_lookup(lookup_type, value)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/__init__.py" in get_prep_lookup
292. return self.get_prep_value(value)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/__init__.py" in get_prep_value
479. return int(value)
Exception Type: ValueError at /admin/cms/page/1/add-plugin/
Exception Value: invalid literal for int() with base 10: 'body'
This is an default simple install of django-cms, all latest versions, and through python 2.6.
A:
Solution:
Upgrade from the latest pip version, to the latest version on github.
| Django-CMS 500 error when clicking to add a plugin | Hey guys, when clicking to add a new plugin ("Add Plugin" on a "Page" I get a 500 error. Using firebug I got this traceback:
Environment:
Request Method: POST
Request URL: http://192.168.1.10:81/admin/cms/page/1/add-plugin/
Django Version: 1.2.3
Python Version: 2.6.6
Installed Applications:
['django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.admin',
'cms',
'cms.plugins.text',
'cms.plugins.picture',
'cms.plugins.link',
'cms.plugins.file',
'cms.plugins.snippet',
'cms.plugins.googlemap',
'mptt',
'publisher']
Installed Middleware:
('django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'cms.middleware.page.CurrentPageMiddleware',
'cms.middleware.user.CurrentUserMiddleware',
'cms.middleware.media.PlaceholderMediaMiddleware')
Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
100. response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/utils/decorators.py" in _wrapped_view
76. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func
69. response = view_func(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/admin/sites.py" in inner
190. return view(request, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django_cms-2.1.0.beta3-py2.6.egg/cms/admin/pageadmin.py" in add_plugin
1061. placeholder = get_object_or_404(Placeholder, pk=placeholder_id)
File "/usr/local/lib/python2.6/dist-packages/django/shortcuts/__init__.py" in get_object_or_404
88. return queryset.get(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in get
333. clone = self.filter(*args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in filter
550. return self._filter_or_exclude(False, *args, **kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py" in _filter_or_exclude
568. clone.query.add_q(Q(*args, **kwargs))
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py" in add_q
1128. can_reuse=used_aliases)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/query.py" in add_filter
1071. connector)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/where.py" in add
66. value = obj.prepare(lookup_type, value)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/sql/where.py" in prepare
299. return self.field.get_prep_lookup(lookup_type, value)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/__init__.py" in get_prep_lookup
292. return self.get_prep_value(value)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/fields/__init__.py" in get_prep_value
479. return int(value)
Exception Type: ValueError at /admin/cms/page/1/add-plugin/
Exception Value: invalid literal for int() with base 10: 'body'
This is an default simple install of django-cms, all latest versions, and through python 2.6.
| [
"Solution:\nUpgrade from the latest pip version, to the latest version on github. \n"
] | [
0
] | [] | [] | [
"django",
"django_cms",
"python"
] | stackoverflow_0004041847_django_django_cms_python.txt |
Q:
How to get the number of active threads started by specific class?
code looks like below:
class workers1(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
# ...do some stuff
class workers2(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
# ...do some stuff
if __name__ == "__main__":
# start workers
while True:
print "Number of threads active", threading.activeCount()
print "Number of worker1 threads", ?????, "Number of worker2 threads", ?????
Is there a way to get the number of threads being active by originating class ?
A:
This is a minor modification of Doug Hellman's multiprocessing ActivePool example code (to use threading). The idea is to have your workers register themselves in a pool, unregister themselves when they finish, using a threading.Lock to coordinate modification of the pool's active list:
import threading
import time
import random
class ActivePool(object):
def __init__(self):
super(ActivePool, self).__init__()
self.active=[]
self.lock=threading.Lock()
def makeActive(self, name):
with self.lock:
self.active.append(name)
def makeInactive(self, name):
with self.lock:
self.active.remove(name)
def numActive(self):
with self.lock:
return len(self.active)
def __str__(self):
with self.lock:
return str(self.active)
def worker(pool):
name=threading.current_thread().name
pool.makeActive(name)
print 'Now running: %s' % str(pool)
time.sleep(random.randint(1,3))
pool.makeInactive(name)
if __name__=='__main__':
poolA=ActivePool()
poolB=ActivePool()
jobs=[]
for i in range(5):
jobs.append(
threading.Thread(target=worker, name='A{0}'.format(i),
args=(poolA,)))
jobs.append(
threading.Thread(target=worker, name='B{0}'.format(i),
args=(poolB,)))
for j in jobs:
j.daemon=True
j.start()
while threading.activeCount()>1:
for j in jobs:
j.join(1)
print 'A-threads active: {0}, B-threads active: {1}'.format(
poolA.numActive(),poolB.numActive())
yields
Now running: ['A0']
Now running: ['B0']
Now running: ['A0', 'A1']
Now running: ['B0', 'B1']
Now running: ['A0', 'A1', 'A2']
Now running: ['B0', 'B1', 'B2']
Now running: ['A0', 'A1', 'A2', 'A3']
Now running: ['B0', 'B1', 'B2', 'B3']
Now running: ['A0', 'A1', 'A2', 'A3', 'A4']
Now running: ['B0', 'B1', 'B2', 'B3', 'B4']
A-threads active: 4, B-threads active: 5
A-threads active: 2, B-threads active: 5
A-threads active: 0, B-threads active: 3
A-threads active: 0, B-threads active: 3
A-threads active: 0, B-threads active: 3
A-threads active: 0, B-threads active: 3
A-threads active: 0, B-threads active: 3
A-threads active: 0, B-threads active: 0
A-threads active: 0, B-threads active: 0
A-threads active: 0, B-threads active: 0
A:
You can use a semaphore for each class and get their counts: see link.
| How to get the number of active threads started by specific class? | code looks like below:
class workers1(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
# ...do some stuff
class workers2(Thread):
def __init__(self):
Thread.__init__(self)
def run(self):
# ...do some stuff
if __name__ == "__main__":
# start workers
while True:
print "Number of threads active", threading.activeCount()
print "Number of worker1 threads", ?????, "Number of worker2 threads", ?????
Is there a way to get the number of threads being active by originating class ?
| [
"This is a minor modification of Doug Hellman's multiprocessing ActivePool example code (to use threading). The idea is to have your workers register themselves in a pool, unregister themselves when they finish, using a threading.Lock to coordinate modification of the pool's active list:\nimport threading\nimport t... | [
21,
2
] | [] | [] | [
"count",
"multithreading",
"python"
] | stackoverflow_0004046986_count_multithreading_python.txt |
Q:
Good learner book for a 12 year old?
My 12 year old brother has recently expressed an interest in learning to program. I of course think this is a great idea, why not start him early? I'm wondering what you guys think with regards a book? I was thinking I should start him off on Java but I'm unsure what book would be best? Any suggestions with regards a book or even another language would be much appreciated.
UPDATE: I've went with Python and I'm starting him off with "Snake wrangling for kids".
A:
Lego Mindstorms? http://mindstorms.lego.com
Not a book but might be a more fun introduction to programming for a 12 year old.
A:
Head First Java is a great book for any new Java programmer. It has lots of pictures, fun quips and puzzles to solve. Definitely worth the buy.
A:
I found Python to be really easy to learn at first.
This is a great, fun book for it. Just make sure he
has fun!
A:
I'm way past 12 and didn't write my first Fortran program until I was 17, so I may not be an authority.
But I suspect Python is a better start than Java, and this book looks appropriate.
A:
If your brother plays any PC games, you might check to see if any of them are moddable. Many games these days come with scripted campaign editors or have python scripts underlying them that you can modify. They are a great way to get involved with the basic concepts behind programming, as your brother can get pretty immediate feedback in an environment that's already very interesting to him.
It may not be 'programming' per se, but it's an exercise in instructing the computer to do what you want, which requires a clear intention and some work and investigation to actually achieve what you've intended. If he develops that mindset, then more general programming in a more complex environment follows naturally.
A:
I would go (as you did) with Python. Java seems to be overengineered (as Steve Yegge described) -- especially for 12 year old kid.
Hello World: Computer Programmer for Kids and Other Beginners seems to be good choice -- it was even written by some kid about 12 year old and his father.
On Hello World: Computer Programmer for Kids and Other Beginners is even written that this is perfect book for 12 year old :).
Both authors where interviewed by Scott Hanselman -- worth to listen.
A:
I too can recommend the Head First series.
You could try "Head First Programming". It uses some python though.
| Good learner book for a 12 year old? | My 12 year old brother has recently expressed an interest in learning to program. I of course think this is a great idea, why not start him early? I'm wondering what you guys think with regards a book? I was thinking I should start him off on Java but I'm unsure what book would be best? Any suggestions with regards a book or even another language would be much appreciated.
UPDATE: I've went with Python and I'm starting him off with "Snake wrangling for kids".
| [
"Lego Mindstorms? http://mindstorms.lego.com\nNot a book but might be a more fun introduction to programming for a 12 year old.\n",
"Head First Java is a great book for any new Java programmer. It has lots of pictures, fun quips and puzzles to solve. Definitely worth the buy.\n",
"I found Python to be really ea... | [
12,
8,
5,
3,
2,
1,
0
] | [] | [] | [
"java",
"python"
] | stackoverflow_0003472634_java_python.txt |
Q:
Is there a better way to write this?
Is there a better way to do this? I feel like I am doing something wrong by being too repetitive.
O = viz.pick(1, viz.WORLD)
BackSetts = ["set_b1b", "set_b2a", "set_b1a", "set_b2b"]
LeftSetts = ["set_l1a", "set_l1b", "set_l2a", "set_l1b"]
NormSetts = ["set_nr_a", "set_nr_b"]
Maps = ["MapA","MapB"]
if O.name in BackSetts:
for i in set(BackSetts)|set(Maps):
WORLD[i].alpha(abs(WORLD[i].getAlpha()-1))
elif O.name in LeftSetts:
for i in set(LeftSetts)|set(Maps):
WORLD[i].alpha(abs(WORLD[i].getAlpha()-1))
elif O.name in NormSetts:
for i in NormSetts:
WORLD[i].alpha(abs(WORLD[i].getAlpha()-1))
A:
The trivial transformation is:
O = viz.pick(1, viz.WORLD)
BackSetts = ["set_b1b", "set_b2a", "set_b1a", "set_b2b"]
LeftSetts = ["set_l1a", "set_l1b", "set_l2a", "set_l1b"]
NormSetts = ["set_nr_a", "set_nr_b"]
Maps = ["MapA","MapB"]
anyset = []
if O.name in BackSetts:
anyset = set(BackSetts)|set(Maps)
elif O.name in LeftSetts:
anyset = set(LeftSetts)|set(Maps)
elif O.name in NormSetts:
anyset = NormSetts
for i in anyset:
WORLD[i].alpha(abs(WORLD[i].getAlpha()-1))
This takes care such that NormSetts is not union'd with Maps, as in your original code.
| Is there a better way to write this? | Is there a better way to do this? I feel like I am doing something wrong by being too repetitive.
O = viz.pick(1, viz.WORLD)
BackSetts = ["set_b1b", "set_b2a", "set_b1a", "set_b2b"]
LeftSetts = ["set_l1a", "set_l1b", "set_l2a", "set_l1b"]
NormSetts = ["set_nr_a", "set_nr_b"]
Maps = ["MapA","MapB"]
if O.name in BackSetts:
for i in set(BackSetts)|set(Maps):
WORLD[i].alpha(abs(WORLD[i].getAlpha()-1))
elif O.name in LeftSetts:
for i in set(LeftSetts)|set(Maps):
WORLD[i].alpha(abs(WORLD[i].getAlpha()-1))
elif O.name in NormSetts:
for i in NormSetts:
WORLD[i].alpha(abs(WORLD[i].getAlpha()-1))
| [
"The trivial transformation is:\nO = viz.pick(1, viz.WORLD)\n\nBackSetts = [\"set_b1b\", \"set_b2a\", \"set_b1a\", \"set_b2b\"]\nLeftSetts = [\"set_l1a\", \"set_l1b\", \"set_l2a\", \"set_l1b\"]\nNormSetts = [\"set_nr_a\", \"set_nr_b\"]\nMaps = [\"MapA\",\"MapB\"]\nanyset = []\n\nif O.name in BackSetts:\n anyset... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004047679_python.txt |
Q:
Which exception to raise if a given string does not match some format?
This is a follow up to an older question.
Given a ISBN number, e.g. 3-528-03851-5 which exception type should I raise if the passed in string doesn't match the format X-XXX-XXXXX-X?
A:
Raise a ValueError.
It's pretty much the standard way of saying "you've given me a value that doesn't make sense". For example:
>>> int("a")
Traceback (most recent call last):
File "", line 1, in
ValueError: invalid literal for int() with base 10: 'a'
>>> import shlex; shlex.split("'")
Traceback (most recent call last):
...
ValueError: No closing quotation
Contrast this with a TypeError, which is raised when a type is incorrect:
>>> d = {}
>>> d[{}]
Traceback (most recent call last):
File "", line 1, in
TypeError: unhashable type: 'dict'
A:
I think I'd make an exception class to raise in this instance since its a very specific type of exception. You can extend the ValueError class pretty easily:
class ISBNFormatException(ValueError):
"""Raised when an invalid ISBN format is found"""
pass
A:
The ValueError might be the most appropriate choice. According to its docs, it's when a value has the correct type but an inappropriate value.
http://docs.python.org/library/exceptions.html#exceptions.ValueError
| Which exception to raise if a given string does not match some format? | This is a follow up to an older question.
Given a ISBN number, e.g. 3-528-03851-5 which exception type should I raise if the passed in string doesn't match the format X-XXX-XXXXX-X?
| [
"Raise a ValueError.\nIt's pretty much the standard way of saying \"you've given me a value that doesn't make sense\". For example:\n\n>>> int(\"a\")\nTraceback (most recent call last):\n File \"\", line 1, in \nValueError: invalid literal for int() with base 10: 'a'\n>>> import shlex; shlex.split(\"'\")\nTracebac... | [
6,
3,
2
] | [] | [] | [
"exception_handling",
"python"
] | stackoverflow_0004047752_exception_handling_python.txt |
Q:
Is there something wrong with this python code, why does it run so slow compared to ruby?
I was interested in comparing ruby speed vs python so I took the simplest recursive calculation, namely print the fibonacci sequance.
This is the python code
#!/usr/bin/python2.7
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1)+fib(n-2)
i = 0
while i < 35:
print fib(i)
i = i + 1
and here is the ruby code
#!/usr/bin/ruby
def fib(n)
if n == 0
return 0
elsif n == 1
return 1
else
fib(n-1)+fib(n-2)
end
end
i = 0
while (i < 35)
puts fib(i)
i = i + 1
end
over several runs, time reports this average
real 0m4.782s
user 0m4.763s
sys 0m0.010s
thats for ruby, now python2.7 gives
real 0m11.605s
user 0m11.563s
sys 0m0.013s
Whats the deal?
A:
The recursion efficiency of python is the cause of this overhead. See this article for much more detail. The above solutions that solve this iteratively are better for python since they do not incur the function call overhead recursion does. My assumption about ruby would be that it is clearly optimizing the code while python is not. Again, that article goes into a lot detail about this using a nearly identical fib function.
A:
So for this code, Python is a bit more than two times slower than Ruby. Probably for other codes, Python will be faster than Ruby.
Your implementation of fib() has exponential run time. This can easily be avoided by using a loop. Python example:
a, b = 1, 1
for i in range(35):
a, b = b, a+b
print b
A:
Your method of calculating the first 35 numbers in the fibonacci sequence is immensely inefficient. You run a function fib() 35 times, and each time fib() has exponential run time. The generator in Python is the perfect solution to this problem and is far more efficient than what you wrote in Ruby.
def fibo_generator(n):
# gets Fibonacci numbers up to nth number using a generator
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
You can then print all fibonacci numbers up to 35 using this code:
for f in fibo_generator(35):
print f
This is by far the most efficient way to implement the fibonacci sequence in Python as well as the most versatile.
A:
I was interested in comparing ruby
speed vs python
Microbenchmarks are a really bad way to compare languages, especially before you mastered both. If you want a benchmark that has any real world meaning then you need to put a lot of effort into it - or you google for "language shootout"
Here is a better comparison of Python and Ruby
A:
Here's some more numbers to compare:
Python2.7
9.67 user 0.09 system 0:09.78 elapsed 99%CPU (0avgtext+0avgdata 16560maxresident)k
0inputs+0outputs (0major+1169minor)pagefaults 0swaps
ruby 1.8.7 (2010-06-23 patchlevel 299) [x86_64-linux]
28.37 user 0.35 system 0:28.78 elapsed 99% CPU (0avgtext+0avgdata 9200maxresident)k
1896inputs+0outputs (9major+656minor)pagefaults 0swaps
ruby 1.9.2p0 (2010-08-18 revision 29036) [x86_64-linux]
6.21 user 0.08 system 0:06.36 elapsed 98% CPU (0avgtext+0avgdata 14160maxresident)k
4416inputs+0outputs (16major+953minor)pagefaults 0swaps
Python is three times faster than ruby1.8 and 30% slower than ruby1.9.1 for the code provided.
Other Python versions for comparison:
2.4.6 took 10.30 seconds
2.5.5 took 9.93 seconds
2.6.6 took 9.22 seconds
2.7 took 9.35 seconds
3.0.1 took 11.67 seconds
3.1.2 took 11.35 seconds
3.2a3+ (py3k:85895, Oct 29 2010, 01:41:57)
[GCC 4.4.5] took 13.09 seconds
2.5.2 (77963, Oct 15 2010, 02:00:43)
[PyPy 1.3.0] took 21.26 seconds
2.5.1 (Release_2_5_1:6813, Sep 26 2009, 13:47:54)
[OpenJDK 64-Bit Server VM (Sun Microsystems Inc.)] took 8.81 seconds
| Is there something wrong with this python code, why does it run so slow compared to ruby? | I was interested in comparing ruby speed vs python so I took the simplest recursive calculation, namely print the fibonacci sequance.
This is the python code
#!/usr/bin/python2.7
def fib(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-1)+fib(n-2)
i = 0
while i < 35:
print fib(i)
i = i + 1
and here is the ruby code
#!/usr/bin/ruby
def fib(n)
if n == 0
return 0
elsif n == 1
return 1
else
fib(n-1)+fib(n-2)
end
end
i = 0
while (i < 35)
puts fib(i)
i = i + 1
end
over several runs, time reports this average
real 0m4.782s
user 0m4.763s
sys 0m0.010s
thats for ruby, now python2.7 gives
real 0m11.605s
user 0m11.563s
sys 0m0.013s
Whats the deal?
| [
"The recursion efficiency of python is the cause of this overhead. See this article for much more detail. The above solutions that solve this iteratively are better for python since they do not incur the function call overhead recursion does. My assumption about ruby would be that it is clearly optimizing the code ... | [
8,
2,
2,
2,
2
] | [] | [] | [
"fibonacci",
"performance",
"python",
"ruby"
] | stackoverflow_0004046514_fibonacci_performance_python_ruby.txt |
Q:
How to call a python script with command line args?
I have a script, client.py, that reads command line args straight as a script (not wrapped in a function like main()), like so:
opts, args = getopt.getopt(sys.argv[1:], "l:r:a:j:b:f:n:u:")
and prints a bunch of stuff.
I need to call this script from my code (on Google App Engine, if that matters). It seems that calling
import client
runs client.py as a script, but how do I specify the arguments?
A:
You shouldn't do this unless you have to: if you have two Python scripts they can communicate in Python instead of through a command line parser. Rewrite client.py with an if __name__ == "__main__" check and then call its main function directly from your script.
If you don't have the option of doing that (and you should avoid this case if at all possible), you might be able to set sys.argv; I'm not sure if GAE allows you to do that. YOu may also be able to use subprocess.Popen.
A:
Google AppEngine uses a significantly modified version of Python and disables a lot of system and subprocess libraries as well as most C python modules. To call that script you'll need to import an entrypoint and call that. I believe on convention is to call your entrypoint main and call that, passing any args it might need. This is a good practice in general. For example in the calling application:
from client import main
main()
A:
You can't. Use subprocess or os.exec*(), or modify the other script to use a main sentinel that parses the arguments then passes them to a main() function, then call main() yourself with the appropriate arguments.
Also, import client.
| How to call a python script with command line args? | I have a script, client.py, that reads command line args straight as a script (not wrapped in a function like main()), like so:
opts, args = getopt.getopt(sys.argv[1:], "l:r:a:j:b:f:n:u:")
and prints a bunch of stuff.
I need to call this script from my code (on Google App Engine, if that matters). It seems that calling
import client
runs client.py as a script, but how do I specify the arguments?
| [
"You shouldn't do this unless you have to: if you have two Python scripts they can communicate in Python instead of through a command line parser. Rewrite client.py with an if __name__ == \"__main__\" check and then call its main function directly from your script.\nIf you don't have the option of doing that (and y... | [
2,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004047656_python.txt |
Q:
Does FastCGI or Apache2 limit upload sizes?
I'm having a problem with file uploading. I'm using FastCGI on Apache2 (unix) to run a WSGI-compliant application. File uploads, in the form of images, are begin saved in a MySQL database. However, larger images are being truncated at 65535 bytes. As far as I can tell, nothing should be limiting the size of the files and I'm not sure which one of the pieces in my solution would be causing the problem.
Is it FastCGI; can it limit file upload sizes?
Is it Python? The cgi.FieldStorage object gives me a file handle to the uploaded file which I then read: file.read(). Does this limit file sizes in any way?
Is it MySQL? The type of the column for saving the image data is a longblob. I figured this could store a couple of GB worth of data. So a few MB shouldn't be a problem, right?
Is it the flups WSGIServer? I can't find any information regarding this.
My file system can definitely handle huge files, so that's not a problem. Any ideas?
UPDATE:
It is MySQL. I got python to output the number of bytes uploaded and it's greater than 65535. So I looked into max_allowed_packet for mysqld and set it to 128M. Overkill, but wanting to be sure for the moment.
My only problem now is getting python's MySQLdb to allow the transfer of more than 65535 bytes. Does anyone know how to do this? Might post as a separate question.
A:
If the web server/gateway layer were truncating incoming form submissions I'd expect an error from FieldStorage, since the truncation would not just interrupt the file upload but also the whole multipart/form-data structure. Even if cgi.py tolerated this, it would be very unlikely to have truncated the multipart at just the right place to leave exactly 2**16-1 bytes of file upload.
So I would suspect MySQL. LONGBLOB should be fine up to 2**32-1, but 65535 would be the maximum length of a normal BLOB. Are you sure the types are what you think? Check with SHOW CREATE TABLE x. Which database layer are you using to get the data in?
| Does FastCGI or Apache2 limit upload sizes? | I'm having a problem with file uploading. I'm using FastCGI on Apache2 (unix) to run a WSGI-compliant application. File uploads, in the form of images, are begin saved in a MySQL database. However, larger images are being truncated at 65535 bytes. As far as I can tell, nothing should be limiting the size of the files and I'm not sure which one of the pieces in my solution would be causing the problem.
Is it FastCGI; can it limit file upload sizes?
Is it Python? The cgi.FieldStorage object gives me a file handle to the uploaded file which I then read: file.read(). Does this limit file sizes in any way?
Is it MySQL? The type of the column for saving the image data is a longblob. I figured this could store a couple of GB worth of data. So a few MB shouldn't be a problem, right?
Is it the flups WSGIServer? I can't find any information regarding this.
My file system can definitely handle huge files, so that's not a problem. Any ideas?
UPDATE:
It is MySQL. I got python to output the number of bytes uploaded and it's greater than 65535. So I looked into max_allowed_packet for mysqld and set it to 128M. Overkill, but wanting to be sure for the moment.
My only problem now is getting python's MySQLdb to allow the transfer of more than 65535 bytes. Does anyone know how to do this? Might post as a separate question.
| [
"If the web server/gateway layer were truncating incoming form submissions I'd expect an error from FieldStorage, since the truncation would not just interrupt the file upload but also the whole multipart/form-data structure. Even if cgi.py tolerated this, it would be very unlikely to have truncated the multipart a... | [
2
] | [] | [] | [
"apache2",
"fastcgi",
"file_upload",
"mysql",
"python"
] | stackoverflow_0004047899_apache2_fastcgi_file_upload_mysql_python.txt |
Q:
What about this mess? Ideas to better rewrite it?
This mess is working well, but if somebody has any ideas to make it look/perform better, it would be greatly appreciated!
def OnButtonClick(b, e, f="none"):
if b == Gui["goleft"] and e == viz.UP: do_Cam([1.475, 7.862, 10.293])
if b == Gui["gocenter"] and e == viz.UP: do_Cam([0, 1, 52])
if b == Gui["goright"] and e == viz.UP: do_Cam([0, 11, 5])
if b == Gui["godown"] and e == viz.UP: do_Cam([0, 16, 53])
def OnSliders(POS, S):
if S == 1:
Gui["bars_alpha"].message(str('%.2f'%(POS)))
CFG["BAR_alpha"] = POS
for i in BAR_Items: BAR_Items[i].alpha(POS)
elif S == 2:
Gui["shps_alpha"].message(str('%.2f'%(POS)))
CFG["SHP_alpha"] = POS
for i in ISOS.keys(): SHAPE[i+"_SHP"].alpha(POS)
elif S == 3:
Gui["bars_sizes"].message(str('%.2f'%(POS)))
CFG["BAR_scale"] = [POS, 0.15, POS]
for i in BAR_Items: BAR_Items[i].scale(POS, BAR_Items[i].getScale()[1], POS)
elif S == 4:
Gui["label_alpha"].message(str('%.2f'%(POS)))
CFG["BARTXT_alpha"] = POS
for i in BAR_Label: BAR_Label[i].alpha(POS)
elif S == 5:
Gui["label_size"].message(str('%.2f'%(POS)))
CFG["BARTXT_scale"] = [POS, POS, POS]
for i in BAR_Label: BAR_Label[i].scale(POS, POS, POS)
elif S == 6:
Gui["grid_alpha"].message(str('%.2f'%(POS)))
CFG["grid_alpha"] = POS
[Griditema[i].alpha(POS) for i in Griditema]
[Griditemb[i].alpha(POS) for i in Griditemb]
After following some of the initial recommendations I received, I now have:
def OnButtonClick(b, e, f="none"):
if e != viz.UP: return
if b == Gui["goleft"] : do_Cam([1.475, 7.862, 10.293])
elif b == Gui["gocenter"] : do_Cam([0, 1, 5])
elif b == Gui["goright"] : do_Cam([0, 1, 5])
elif b == Gui["godown"] : do_Cam([0, 1, 5])
def OnSliders(POS, S):
if S == 1:
CFG["BAR_alpha"] = POS
for i in BAR_Items: BAR_Items[i].alpha(POS)
elif S == 2:
CFG["SHP_alpha"] = POS
for i in ISOS.keys(): SHAPE[i+"_SHP"].alpha(POS)
elif S == 3:
CFG["BAR_scale"] = [POS, 0.15, POS]
for i in BAR_Items: BAR_Items[i].scale(POS, BAR_Items[i].getScale()[1], POS)
elif S == 4:
CFG["BARTXT_alpha"] = POS
for i in BAR_Label: BAR_Label[i].alpha(POS)
elif S == 5:
CFG["BARTXT_scale"] = [POS, POS, POS]
for i in BAR_Label: BAR_Label[i].scale(POS, POS, POS)
elif S == 6:
CFG["grid_alpha"] = POS
for i in Griditema: Griditema[i].alpha(POS)
for i in Griditemb: Griditemb[i].alpha(POS)
mydict = {1:"bars_alpha", 2:"shps_alpha", 3:"bars_sizes", 4:"label_alpha", 5:"label_size", 6:"grid_alpha"}
Gui[mydict[S]].message('%.2f' % POS)
This is how it ended:
def OnButtonClick(b, e, f="none"):
if e != viz.UP: return
if b == Gui["goleft"] : do_Cam([1.475, 7.862, 10.293])
elif b == Gui["gocenter"]: do_Cam([0, 1, 5])
elif b == Gui["goright"] : do_Cam([0, 1, 5])
elif b == Gui["godown"] : do_Cam([0, 1, 5])
def OnSliders(POS, S):
D = {1:"BAR_alpha", 2:"SHP_alpha", 3:"BAR_scale", 4:"TXT_alpha", 5:"TXT_scale", 6:"grid_alpha"}
if S == 1: CFG[D[S]] = POS; [BAR_Items[i].alpha(POS) for i in BAR_Items]
elif S == 2: CFG[D[S]] = POS; [SHAPE[i+"_SHP"].alpha(POS) for i in ISOS.keys()]
elif S == 3: CFG[D[S]] = [POS, 0.15, POS]; [BAR_Items[i].scale(POS, BAR_Items[i].getScale()[1], POS) for i in BAR_Items]
elif S == 4: CFG[D[S]] = POS; [BAR_Label[i].alpha(POS) for i in BAR_Label]
elif S == 5: CFG[D[S]] = [POS, POS, POS]; [BAR_Label[i].scale(POS, POS, POS) for i in BAR_Label]
elif S == 6: CFG[D[S]] = POS; [Griditema[i].alpha(POS) for i in Griditema]; [Griditemb[i].alpha(POS) for i in Griditemb]
Gui[D[S]].message('%.2f' % POS)
Thanks for the help!
A:
I would follow Preet Sangha's advice with these additional improvements.
Replace
str('%.2f'%(POS))
with
'%.2f' % POS
I think it is a bad practice to use list comprehension to produce side effects.
[Griditema[i].alpha(POS) for i in Griditema]
Assuming Griditema is a dict.
for item in Griditema.itervalues():
item.alpha(POS)
A:
First thing I would do it replace the repeated code with functions..
such as
Gui["bars_alpha"].message(str('%.2f'%(POS)))
CFG["BAR_alpha"] = POS
with
def DoIt(pos):
Gui[pos].message(str('%.2f'%(POS)))
CFG[pos] = POS
Then I'd replace the big if/else with a dictionary of llamdas
A:
You could replace the first line of each case with a single array lookup (Gui[keys[S]]...), but frankly I don't think there's much to be gained. The code does look complex, but the complexity is real, not just an artefact of how you coded it.
A:
def OnButtonClick(b, e, f="none"):
if e != viz.UP: return
if b == Gui["goleft"]: do_Cam([1.475, 7.862, 10.293])
if b == Gui["gocenter"]: do_Cam([0, 1, 52])
...
A:
I think that mess is derived by others mess in the design of the application.
My suspicion is that you don't have any action object for all of those actions.
| What about this mess? Ideas to better rewrite it? | This mess is working well, but if somebody has any ideas to make it look/perform better, it would be greatly appreciated!
def OnButtonClick(b, e, f="none"):
if b == Gui["goleft"] and e == viz.UP: do_Cam([1.475, 7.862, 10.293])
if b == Gui["gocenter"] and e == viz.UP: do_Cam([0, 1, 52])
if b == Gui["goright"] and e == viz.UP: do_Cam([0, 11, 5])
if b == Gui["godown"] and e == viz.UP: do_Cam([0, 16, 53])
def OnSliders(POS, S):
if S == 1:
Gui["bars_alpha"].message(str('%.2f'%(POS)))
CFG["BAR_alpha"] = POS
for i in BAR_Items: BAR_Items[i].alpha(POS)
elif S == 2:
Gui["shps_alpha"].message(str('%.2f'%(POS)))
CFG["SHP_alpha"] = POS
for i in ISOS.keys(): SHAPE[i+"_SHP"].alpha(POS)
elif S == 3:
Gui["bars_sizes"].message(str('%.2f'%(POS)))
CFG["BAR_scale"] = [POS, 0.15, POS]
for i in BAR_Items: BAR_Items[i].scale(POS, BAR_Items[i].getScale()[1], POS)
elif S == 4:
Gui["label_alpha"].message(str('%.2f'%(POS)))
CFG["BARTXT_alpha"] = POS
for i in BAR_Label: BAR_Label[i].alpha(POS)
elif S == 5:
Gui["label_size"].message(str('%.2f'%(POS)))
CFG["BARTXT_scale"] = [POS, POS, POS]
for i in BAR_Label: BAR_Label[i].scale(POS, POS, POS)
elif S == 6:
Gui["grid_alpha"].message(str('%.2f'%(POS)))
CFG["grid_alpha"] = POS
[Griditema[i].alpha(POS) for i in Griditema]
[Griditemb[i].alpha(POS) for i in Griditemb]
After following some of the initial recommendations I received, I now have:
def OnButtonClick(b, e, f="none"):
if e != viz.UP: return
if b == Gui["goleft"] : do_Cam([1.475, 7.862, 10.293])
elif b == Gui["gocenter"] : do_Cam([0, 1, 5])
elif b == Gui["goright"] : do_Cam([0, 1, 5])
elif b == Gui["godown"] : do_Cam([0, 1, 5])
def OnSliders(POS, S):
if S == 1:
CFG["BAR_alpha"] = POS
for i in BAR_Items: BAR_Items[i].alpha(POS)
elif S == 2:
CFG["SHP_alpha"] = POS
for i in ISOS.keys(): SHAPE[i+"_SHP"].alpha(POS)
elif S == 3:
CFG["BAR_scale"] = [POS, 0.15, POS]
for i in BAR_Items: BAR_Items[i].scale(POS, BAR_Items[i].getScale()[1], POS)
elif S == 4:
CFG["BARTXT_alpha"] = POS
for i in BAR_Label: BAR_Label[i].alpha(POS)
elif S == 5:
CFG["BARTXT_scale"] = [POS, POS, POS]
for i in BAR_Label: BAR_Label[i].scale(POS, POS, POS)
elif S == 6:
CFG["grid_alpha"] = POS
for i in Griditema: Griditema[i].alpha(POS)
for i in Griditemb: Griditemb[i].alpha(POS)
mydict = {1:"bars_alpha", 2:"shps_alpha", 3:"bars_sizes", 4:"label_alpha", 5:"label_size", 6:"grid_alpha"}
Gui[mydict[S]].message('%.2f' % POS)
This is how it ended:
def OnButtonClick(b, e, f="none"):
if e != viz.UP: return
if b == Gui["goleft"] : do_Cam([1.475, 7.862, 10.293])
elif b == Gui["gocenter"]: do_Cam([0, 1, 5])
elif b == Gui["goright"] : do_Cam([0, 1, 5])
elif b == Gui["godown"] : do_Cam([0, 1, 5])
def OnSliders(POS, S):
D = {1:"BAR_alpha", 2:"SHP_alpha", 3:"BAR_scale", 4:"TXT_alpha", 5:"TXT_scale", 6:"grid_alpha"}
if S == 1: CFG[D[S]] = POS; [BAR_Items[i].alpha(POS) for i in BAR_Items]
elif S == 2: CFG[D[S]] = POS; [SHAPE[i+"_SHP"].alpha(POS) for i in ISOS.keys()]
elif S == 3: CFG[D[S]] = [POS, 0.15, POS]; [BAR_Items[i].scale(POS, BAR_Items[i].getScale()[1], POS) for i in BAR_Items]
elif S == 4: CFG[D[S]] = POS; [BAR_Label[i].alpha(POS) for i in BAR_Label]
elif S == 5: CFG[D[S]] = [POS, POS, POS]; [BAR_Label[i].scale(POS, POS, POS) for i in BAR_Label]
elif S == 6: CFG[D[S]] = POS; [Griditema[i].alpha(POS) for i in Griditema]; [Griditemb[i].alpha(POS) for i in Griditemb]
Gui[D[S]].message('%.2f' % POS)
Thanks for the help!
| [
"I would follow Preet Sangha's advice with these additional improvements.\nReplace\nstr('%.2f'%(POS))\n\nwith\n'%.2f' % POS\n\nI think it is a bad practice to use list comprehension to produce side effects.\n[Griditema[i].alpha(POS) for i in Griditema]\n\nAssuming Griditema is a dict.\nfor item in Griditema.iterval... | [
3,
2,
1,
1,
0
] | [] | [] | [
"python"
] | stackoverflow_0004047922_python.txt |
Q:
Differences in regex syntax in Python and Java
I have a following working regex in Python and I am trying to convert it to Java, I thought that regex works the same in both languages, but obviously it doesn't.
Python regex: ^\d+;\d+-\d+
My Java attempt: ^\\d+;\\d+-\\d+
Example strings that should be matched:
3;1-2,2-3
68;12-15,1-16,66-1,1-2
What is the right solution in Java?
Thank you, Tomas
A:
The regex is faulty for the input, don't know what you were doing in Python, but this isn't matching the whole strings in any regex I know.
This should do the trick (escaping characters are omitted):
^\d+;(\d+-\d+,?)+
I.e. you need to continue matching the number pairs separated by commas.
| Differences in regex syntax in Python and Java | I have a following working regex in Python and I am trying to convert it to Java, I thought that regex works the same in both languages, but obviously it doesn't.
Python regex: ^\d+;\d+-\d+
My Java attempt: ^\\d+;\\d+-\\d+
Example strings that should be matched:
3;1-2,2-3
68;12-15,1-16,66-1,1-2
What is the right solution in Java?
Thank you, Tomas
| [
"The regex is faulty for the input, don't know what you were doing in Python, but this isn't matching the whole strings in any regex I know. \nThis should do the trick (escaping characters are omitted):\n^\\d+;(\\d+-\\d+,?)+\n\nI.e. you need to continue matching the number pairs separated by commas.\n"
] | [
2
] | [] | [] | [
"java",
"python",
"regex"
] | stackoverflow_0004048088_java_python_regex.txt |
Q:
textarea to list
textarea returns this
[u'a\r\nb\r\nc\r\nd\r\ne']
what is the best way to turn that into a list
['a', 'b', 'c', 'd', 'e']
Thanks!
A:
>>> L = [u'a\r\nb\r\nc\r\nd\r\ne']
>>> L[0].split('\r\n')
[u'a', u'b', u'c', u'd', u'e']
| textarea to list | textarea returns this
[u'a\r\nb\r\nc\r\nd\r\ne']
what is the best way to turn that into a list
['a', 'b', 'c', 'd', 'e']
Thanks!
| [
">>> L = [u'a\\r\\nb\\r\\nc\\r\\nd\\r\\ne']\n>>> L[0].split('\\r\\n')\n[u'a', u'b', u'c', u'd', u'e']\n\n"
] | [
9
] | [] | [] | [
"python",
"textarea"
] | stackoverflow_0004048109_python_textarea.txt |
Q:
Checking if an ISBN number is correct
I'm given some ISBN numbers e.g. 3-528-03851 (not valid) , 3-528-16419-0 (valid). I'm supposed to write a program which tests if the ISBN number is valid.
Here' my code:
def check(isbn):
check_digit = int(isbn[-1])
match = re.search(r'(\d)-(\d{3})-(\d{5})', isbn[:-1])
if match:
digits = match.group(1) + match.group(2) + match.group(3)
result = 0
for i, digit in enumerate(digits):
result += (i + 1) * int(digit)
return True if (result % 11) == check_digit else False
return False
I've used a regular expression to check a) if the format is valid and b) extract the digits in the ISBN string. While it seems to work, being a Python beginner I'm eager to know how I could improve my code. Suggestions?
A:
First, try to avoid code like this:
if Action():
lots of code
return True
return False
Flip it around, so the bulk of code isn't nested. This gives us:
def check(isbn):
check_digit = int(isbn[-1])
match = re.search(r'(\d)-(\d{3})-(\d{5})', isbn[:-1])
if not match:
return False
digits = match.group(1) + match.group(2) + match.group(3)
result = 0
for i, digit in enumerate(digits):
result += (i + 1) * int(digit)
return True if (result % 11) == check_digit else False
There are some bugs in the code:
If the check digit isn't an integer, this will raise ValueError instead of returning False: "0-123-12345-Q".
If the check digit is 10 ("X"), this will raise ValueError instead of returning True.
This assumes that the ISBN is always grouped as "1-123-12345-1". That's not the case; ISBNs are grouped arbitrarily. For example, the grouping "12-12345-12-1" is valid. See http://www.isbn.org/standards/home/isbn/international/html/usm4.htm.
This assumes the ISBN is grouped by hyphens. Spaces are also valid.
It doesn't check that there are no extra characters; '0-123-4567819' returns True, ignoring the extra 1 at the end.
So, let's simplify this. First, remove all spaces and hyphens, and make sure the regex matches the whole line by bracing it in '^...$'. That makes sure it rejects strings which are too long.
def check(isbn):
isbn = isbn.replace("-", "").replace(" ", "");
check_digit = int(isbn[-1])
match = re.search(r'^(\d{9})$', isbn[:-1])
if not match:
return False
digits = match.group(1)
result = 0
for i, digit in enumerate(digits):
result += (i + 1) * int(digit)
return True if (result % 11) == check_digit else False
Next, let's fix the "X" check digit problem. Match the check digit in the regex as well, so the entire string is validated by the regex, then convert the check digit correctly.
def check(isbn):
isbn = isbn.replace("-", "").replace(" ", "").upper();
match = re.search(r'^(\d{9})(\d|X)$', isbn)
if not match:
return False
digits = match.group(1)
check_digit = 10 if match.group(2) == 'X' else int(match.group(2))
result = 0
for i, digit in enumerate(digits):
result += (i + 1) * int(digit)
return True if (result % 11) == check_digit else False
Finally, using a generator expression and max is a more idiomatic way of doing the final calculation in Python, and the final conditional can be simplified.
def check(isbn):
isbn = isbn.replace("-", "").replace(" ", "").upper();
match = re.search(r'^(\d{9})(\d|X)$', isbn)
if not match:
return False
digits = match.group(1)
check_digit = 10 if match.group(2) == 'X' else int(match.group(2))
result = sum((i + 1) * int(digit) for i, digit in enumerate(digits))
return (result % 11) == check_digit
A:
Pointless improvement: replace return True if (result % 11) == check_digit else False with return (result % 11) == check_digit
A:
The check_digit initialization can raise a ValueError if the last character isn't a decimal digit. Why not pull out the check digit with your regex instead of using slicing?
Instead of search, you should probably use match, unless you want to allow arbitrary junk as the prefix. (Also, as a rule of thumb I'd anchor the end with $, though in your case that won't matter as your regex is fixed-width.)
Instead of manually listing the groups, you could just use ''.join(match.groups()), and pull the check_digit out afterwards. You might as well do the conversion to ints before pulling it out, as you want to convert all of them to ints anyway.
your for loop could be replaced by a list/generator comprehension. Just use sum() to add up the elements.
True if (expression) else False can generally be replaced with simply expression. Likewise, False if (expression) else True can always be replaced with simply not expression
Putting that all together:
def check(isbn):
match = re.match(r'(\d)-(\d{3})-(\d{5})-(\d)$', isbn)
if match:
digits = [int(x) for x in ''.join(match.groups())]
check_digit = digits.pop()
return check_digit == sum([(i + 1) * digit
for i, digit in enumerate(digits)]) % 11
return False
The last line is arguably unnecessary, as the default behavior would be to return None (which is falsy), but explicit returns from some paths and not from others looks like a bug to me, so I think it's more readable to leave it in.
A:
All that regex stuff is great if you belong to the isbn.org compliance inspectorate.
However, if you want to know if what the potential customers type into their browser is worth pushing into a query of your database of books for sale, you don't want all that nice red uniform caper. Simply throw away everything but 0-9 and X ... oh yeah nobody uses the shift key so we'd better allow x as well. Then if it's length 10 and passes the check-digit test, it's worth doing the query.
From http://www.isbn.org/standards/home/isbn/international/html/usm4.htm
The check digit is the last digit of
an ISBN. It is calculated on a modulus
11 with weights 10-2, using X in lieu
of 10 where ten would occur as a check
digit.
This means that each of the first nine
digits of the ISBN -- excluding the
check digit itself -- is multiplied by
a number ranging from 10 to 2 and that
the resulting sum of the products,
plus the check digit, must be
divisible by 11 without a remainder.
which is a very long-winded way of saying "each of all the digits is multiplied by a number ranging from 10 to 1 and that the resulting sum of the products must be divisible by 11 without a remainder"
def isbn10_ok(s):
data = [c for c in s if c in '0123456789Xx']
if len(data) != 10: return False
if data[-1] in 'Xx': data[-1] = 10
try:
return not sum((10 - i) * int(x) for i, x in enumerate(data)) % 11
except ValueError:
# rare case: 'X' or 'x' in first 9 "digits"
return False
tests = """\
3-528-03851
3-528-16419-0
ISBN 0-8436-1072-7
0864425244
1864425244
0864X25244
1 904310 16 8
0-473-07480-x
0-473-07480-X
0-473-07480-9
0-473-07480-0
123456789
12345678901
1234567890
0000000000
""".splitlines()
for test in tests:
test = test.strip()
print repr(test), isbn10_ok(test)
Output:
'3-528-03851' False
'3-528-16419-0' True
'ISBN 0-8436-1072-7' True
'0864425244' True
'1864425244' False
'0864X25244' False
'1 904310 16 8' True
'0-473-07480-x' True
'0-473-07480-X' True
'0-473-07480-9' False
'0-473-07480-0' False
'123456789' False
'12345678901' False
'1234567890' False
'0000000000' True
'' False
Aside: a large well-known bookselling site will accept 047307480x, 047307480X, and 0-473-07480-X but not 0-473-07480-x :-O
A:
Your code is nice -- well done for writing idiomatic Python! Here are some minor things:
When you see the idiom
result = <initiator>
for elt in <iterable>:
result += elt
you can replace it by a list comprehension. In this case:
result = sum((i+1)*int(digit) for i, digit in enumerate(digits)
or even more concisely:
return sum((i+1)*int(digit) for i, digit in enumerate(digits) % 11 == check_digit
Of course, it is a value judgement whether this is better than the original. I would personally consider the second of these to be best.
Also, the extra parentheses in (result % 11) == check_digit are extraneous and I don't really think you need them for clarity. That leaves you overall with:
def validate(isbn):
check_digit = int(isbn[-1])
match = re.search(r'(\d)-(\d{3})-(\d{5})', isbn[:-1])
if match:
digits = match.group(1) + match.group(2) + match.group(3)
parity = sum((i+1)*int(digit) for i, digit in enumerate(digits)
return parity % 11 == check_digit
else:
return False
Note that you do still need the return False to catch the case that the ISBN is not even in the right format.
A:
Don't forget (though this may be outside of the scope of your assignment) to calculate the check digit of the ISBN (the final digit), to determine if the ISBN is valid and not just seemingly valid.
There's some information about the implementation of the check digit on the ISBN.org website, and implementation should be fairly straightforward. Wikipedia offers one such example (presuming you've already converted any ASCII "X" to a decimal 10):
bool is_isbn_valid(char digits[10]) {
int i, a = 0, b = 0;
for (i = 0; i < 10; i++) {
a += digits[i]; // Assumed already converted from ASCII to 0..10
b += a;
}
return b % 11 == 0;
}
Applying this for your assignment is left, well, as an exercise for you.
A:
Your check digit can take on the values 0-10, based on the fact that it's modulo-11. There's a problem with the line:
check_digit = int(isbn[-1])
as this works only for the digits 0-9. You'll need something for the case when the digit is 'X', and also for the error condition when it isn't any of the above - otherwise your program will crash.
| Checking if an ISBN number is correct | I'm given some ISBN numbers e.g. 3-528-03851 (not valid) , 3-528-16419-0 (valid). I'm supposed to write a program which tests if the ISBN number is valid.
Here' my code:
def check(isbn):
check_digit = int(isbn[-1])
match = re.search(r'(\d)-(\d{3})-(\d{5})', isbn[:-1])
if match:
digits = match.group(1) + match.group(2) + match.group(3)
result = 0
for i, digit in enumerate(digits):
result += (i + 1) * int(digit)
return True if (result % 11) == check_digit else False
return False
I've used a regular expression to check a) if the format is valid and b) extract the digits in the ISBN string. While it seems to work, being a Python beginner I'm eager to know how I could improve my code. Suggestions?
| [
"First, try to avoid code like this:\nif Action():\n lots of code\n return True\nreturn False\n\nFlip it around, so the bulk of code isn't nested. This gives us:\ndef check(isbn):\n check_digit = int(isbn[-1])\n match = re.search(r'(\\d)-(\\d{3})-(\\d{5})', isbn[:-1])\n\n if not match:\n retu... | [
17,
4,
3,
2,
1,
1,
1
] | [] | [] | [
"python"
] | stackoverflow_0004047511_python.txt |
Q:
How can I discover if a program is running from command line or from web?
I have a python script and I wanna know if the request
is from web or from command line. How can I do this?
A:
When run as a CGI, environment variables such as REQUEST_METHOD will be present. If not, then you're not running in a CGI environment.
You can check this like this:
import os
if os.getenv("REQUEST_METHOD"):
print("running as CGI")
else:
print("not running as CGI")
| How can I discover if a program is running from command line or from web? | I have a python script and I wanna know if the request
is from web or from command line. How can I do this?
| [
"When run as a CGI, environment variables such as REQUEST_METHOD will be present. If not, then you're not running in a CGI environment.\nYou can check this like this:\nimport os\nif os.getenv(\"REQUEST_METHOD\"):\n print(\"running as CGI\")\nelse:\n print(\"not running as CGI\")\n\n"
] | [
9
] | [] | [] | [
"cgi",
"command_line",
"python"
] | stackoverflow_0004048275_cgi_command_line_python.txt |
Q:
Python - A Question on String Editing
I am trying to make a simple text-based game in Python. The idea of which revolves around a deck of playing cards, representing the card face values with A,2,3,4,5,6,7,8,9,10,J,Q, and K (Joker is not used). The suit of the cards will be represented by s,d,h, and c. As an example, "Ace of Hearts" would be represented as Ah.
I am using two random.choice() functions to choose a random face value and a random suit, with 10 being represented by 'X'. This is where I encounter my problem. Ideally, I would like to change 'X' when it appears to '10'. Here is my "test" code for generating a random card:
import random
firstvar = random.choice('A23456789XJQK')
secondvar = random.choice('sdhc')
newvar = firstvar + secondvar
if newvar[0] == 'X':
newvar[0] = '10'
print newvar
else:
print newvar
I quickly found out that this causes an error.
TypeError: 'str' object does not support item assignment
In short, my question is: "How would I go about changing 'X' in my program to '10'?
Thanks for any help you can offer.
A:
Change it before you concatenate.
firstvar = random.choice('A23456789XJQK')
secondvar = random.choice('sdhc')
newvar = (firstvar + secondvar) if firstvar != 'X' else ('10' + secondvar)
Alternatively, don't use 'X' to begin with:
firstvar = random.choice(['A', '2', '3', ..., '10', ...])
Another alternative would be the replace method on strings:
newvar = firstvar.replace('X', '10') + secondvar
The second method is probably best for this situation unless you need to use 'X' elsewhere in your code and that can't be changed. It is worth looking at other methods for dealing with immutable strings though because the second isn't always appropriate.
A:
In python you cannot modify a string. You could deal with this by creating a new string combing the '10' and the rest of the original string
newvar = '10' + newvar[1:]
But that is really ugly. You are better of constructing the string correctly in the first place:
firstvar = random.choice(['A','2','3','4','5','6','7','8','9','10','J','Q', 'K'])
secondvar = random.choice('sdhc')
newvar = firstvar + secondvar
If you are coming from other languages you may be used to thinking about operations as modifying strings. You are better off to create your string correctly in the first place. Of course, if you are dealing with strings from user input that is different.
| Python - A Question on String Editing | I am trying to make a simple text-based game in Python. The idea of which revolves around a deck of playing cards, representing the card face values with A,2,3,4,5,6,7,8,9,10,J,Q, and K (Joker is not used). The suit of the cards will be represented by s,d,h, and c. As an example, "Ace of Hearts" would be represented as Ah.
I am using two random.choice() functions to choose a random face value and a random suit, with 10 being represented by 'X'. This is where I encounter my problem. Ideally, I would like to change 'X' when it appears to '10'. Here is my "test" code for generating a random card:
import random
firstvar = random.choice('A23456789XJQK')
secondvar = random.choice('sdhc')
newvar = firstvar + secondvar
if newvar[0] == 'X':
newvar[0] = '10'
print newvar
else:
print newvar
I quickly found out that this causes an error.
TypeError: 'str' object does not support item assignment
In short, my question is: "How would I go about changing 'X' in my program to '10'?
Thanks for any help you can offer.
| [
"Change it before you concatenate.\nfirstvar = random.choice('A23456789XJQK') \nsecondvar = random.choice('sdhc') \nnewvar = (firstvar + secondvar) if firstvar != 'X' else ('10' + secondvar)\n\nAlternatively, don't use 'X' to begin with:\nfirstvar = random.choice(['A', '2', '3', ..., '10', ...])\n\nAnother alternat... | [
2,
0
] | [] | [] | [
"python",
"string"
] | stackoverflow_0004048447_python_string.txt |
Q:
parsing options in a config module
I use config module to store variables global to all modules. Is it a good place to parse the script arguments? (Note: config module is my own module, it just contains a bunch of global variables.)
----- config.py -----
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-t", "--test", action = "store_true", dest = "test")
#add other options here
(options, args) = parser.parse_args()
------ file1.py ------
import config.py
if config.options.test:
#do something
------ file2.py ------
import config.py
if config.options.test:
#do something
I am concerned about executing the parse_args() function in a file other than the "main" file (invoked from the command line).
A:
What are you trying to do? There are 2 ways you can try -
Pass argument values to your program from command-line (using optparse).
or write a config.py import it in your program & proceed.
Why would you want to do both (& that too in your config file)?
I see that you have written your config module as .py (which is good). But this file should contain minimal code in it. Just config settings. It would help you to keep code & config separate.
The general rule I follow is, if the arguments that need to be passed to my program is more than 6-7, I use a config file. Otherwise optparse it is.
| parsing options in a config module | I use config module to store variables global to all modules. Is it a good place to parse the script arguments? (Note: config module is my own module, it just contains a bunch of global variables.)
----- config.py -----
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-t", "--test", action = "store_true", dest = "test")
#add other options here
(options, args) = parser.parse_args()
------ file1.py ------
import config.py
if config.options.test:
#do something
------ file2.py ------
import config.py
if config.options.test:
#do something
I am concerned about executing the parse_args() function in a file other than the "main" file (invoked from the command line).
| [
"What are you trying to do? There are 2 ways you can try - \n\nPass argument values to your program from command-line (using optparse).\nor write a config.py import it in your program & proceed.\n\nWhy would you want to do both (& that too in your config file)?\nI see that you have written your config module as .py... | [
0
] | [] | [] | [
"command_line",
"python",
"python_3.x"
] | stackoverflow_0004048495_command_line_python_python_3.x.txt |
Q:
Lock-free implementation of a Thread Library
I have been going through a few published papers which details algorithms and data structures which can be used for implementation of a thread library. I searched online to view any existing implementation of the same, and I could only find LFThreads(only its documentation, not its source code).
Have any of you worked on/used a lock-free thread library? I would like to go through its source and a see a few examples of how exactly it is used.
A:
Have you looked at Intel Threading Building Blocks? It's C++, which is not in your tags, but I thought you might be interested since it's open source.
| Lock-free implementation of a Thread Library | I have been going through a few published papers which details algorithms and data structures which can be used for implementation of a thread library. I searched online to view any existing implementation of the same, and I could only find LFThreads(only its documentation, not its source code).
Have any of you worked on/used a lock-free thread library? I would like to go through its source and a see a few examples of how exactly it is used.
| [
"Have you looked at Intel Threading Building Blocks? It's C++, which is not in your tags, but I thought you might be interested since it's open source.\n"
] | [
1
] | [] | [] | [
"c",
"concurrency",
"java",
"lock_free",
"python"
] | stackoverflow_0004029237_c_concurrency_java_lock_free_python.txt |
Q:
plotting a parabola within part of a repeating signal using numpy
I have a repeating signal that varies a little bit with each cycle of a process that repeats roughly every second, though the duration and the contents of each cycle vary from each other a little bit within some parameters. There are a thousand x,y coordinates for every second of my signal data. A small, but important, segment of the data within each cycle is corrupted, and I want to replace each corrupted segment with an upward facing parabola.
For each data segment that needs to be replaced by the parabola, I have the x,y coordinates of three points. The vertex/minimum is one of those points. And the other two points are the left and right tops of the upward-facing U-shape that is the parabola. In other words, the left top is the x,y coordinate pair of the lowest x value in the domain of this function, while the right top is the x,y coordinate pair of the highest x value in the domain of this function. The y-coordinates of the left top and right top are equal to each other, and are the two highest y-values in the data segment.
How can I write the code to plot the remaining data points in this upward facing parabola? Remember that this function needs to be called 60 or 70 times for every minute of data, and that the shape/formula of the parabola will need to change every time this function is called, in order to account for different relationships between these three pairs of x,y coordinates in each resulting parabola.
def ReplaceCorruptedDataWithParabola(Xarray, Yarray, LeftTopX, LeftTopY
, LeftTopIndex, MinX, MinY, MinIndex
, RightTopX, RightTopY, RightTopIndex):
# Step One: Derive the formula for the upward-facing parabola using
# the following data from the three points:
LeftTopX,LeftTopY,LeftTopIndex
MinX,MinY,MinIndex
RightTopX,RightTopY,RightTopIndex
# Step Two: Use the formula derived in step one to plot the parabola in
# the places where the corrupted data used to reside:
for n in Xarray[LeftTopX:RightTopX]:
Yarray[n]=[_**The formula goes here**_]
return Yarray
Note: Xarray and Yarray are each single-column vectors with data at each index that links the two arrays as sets of x,y coordinates. They are both numpy arrays. Xarray contains time information and does not change, but Yarray contains signal data, including the corrupted segment that will be replaced with the parabolic data that needs to be calculated by this function.
A:
So, as I understand it, you have 3 points that you want to fit a parabola to.
Normally, it's simplest to just use numpy.polyfit, but if you're really worried about speed, and you're fitting exactly three points, there's no point in using a least-squares fit.
Instead, we have an even-determined system (fitting a parabola to 3 x,y points), and we can get an exact solution with simple linear algebra.
So, all in all, you might do something like this (most of this is plotting the data):
import numpy as np
import matplotlib.pyplot as plt
def main():
# Generate some random data
x = np.linspace(0, 10, 100)
y = np.cumsum(np.random.random(100) - 0.5)
# Just selecting these arbitrarly
left_idx, right_idx = 20, 50
# Using the mininum y-value within the arbitrary range
min_idx = np.argmin(y[left_idx:right_idx]) + left_idx
# Replace the data within the range with a fitted parabola
new_y = replace_data(x, y, left_idx, right_idx, min_idx)
# Plot the data
fig = plt.figure()
indicies = [left_idx, min_idx, right_idx]
ax1 = fig.add_subplot(2, 1, 1)
ax1.axvspan(x[left_idx], x[right_idx], facecolor='red', alpha=0.5)
ax1.plot(x, y)
ax1.plot(x[indicies], y[indicies], 'ro')
ax2 = fig.add_subplot(2, 1, 2)
ax2.axvspan(x[left_idx], x[right_idx], facecolor='red', alpha=0.5)
ax2.plot(x,new_y)
ax2.plot(x[indicies], y[indicies], 'ro')
plt.show()
def fit_parabola(x, y):
"""Fits the equation "y = ax^2 + bx + c" given exactly 3 points as two
lists or arrays of x & y coordinates"""
A = np.zeros((3,3), dtype=np.float)
A[:,0] = x**2
A[:,1] = x
A[:,2] = 1
a, b, c = np.linalg.solve(A, y)
return a, b, c
def replace_data(x, y, left_idx, right_idx, min_idx):
"""Replace the section of "y" between the indicies "left_idx" and
"right_idx" with a parabola fitted to the three x,y points represented
by "left_idx", "min_idx", and "right_idx"."""
x_fit = x[[left_idx, min_idx, right_idx]]
y_fit = y[[left_idx, min_idx, right_idx]]
a, b, c = fit_parabola(x_fit, y_fit)
new_x = x[left_idx:right_idx]
new_y = a * new_x**2 + b * new_x + c
y = y.copy() # Remove this if you want to modify y in-place
y[left_idx:right_idx] = new_y
return y
if __name__ == '__main__':
main()
Hope that helps a bit...
| plotting a parabola within part of a repeating signal using numpy | I have a repeating signal that varies a little bit with each cycle of a process that repeats roughly every second, though the duration and the contents of each cycle vary from each other a little bit within some parameters. There are a thousand x,y coordinates for every second of my signal data. A small, but important, segment of the data within each cycle is corrupted, and I want to replace each corrupted segment with an upward facing parabola.
For each data segment that needs to be replaced by the parabola, I have the x,y coordinates of three points. The vertex/minimum is one of those points. And the other two points are the left and right tops of the upward-facing U-shape that is the parabola. In other words, the left top is the x,y coordinate pair of the lowest x value in the domain of this function, while the right top is the x,y coordinate pair of the highest x value in the domain of this function. The y-coordinates of the left top and right top are equal to each other, and are the two highest y-values in the data segment.
How can I write the code to plot the remaining data points in this upward facing parabola? Remember that this function needs to be called 60 or 70 times for every minute of data, and that the shape/formula of the parabola will need to change every time this function is called, in order to account for different relationships between these three pairs of x,y coordinates in each resulting parabola.
def ReplaceCorruptedDataWithParabola(Xarray, Yarray, LeftTopX, LeftTopY
, LeftTopIndex, MinX, MinY, MinIndex
, RightTopX, RightTopY, RightTopIndex):
# Step One: Derive the formula for the upward-facing parabola using
# the following data from the three points:
LeftTopX,LeftTopY,LeftTopIndex
MinX,MinY,MinIndex
RightTopX,RightTopY,RightTopIndex
# Step Two: Use the formula derived in step one to plot the parabola in
# the places where the corrupted data used to reside:
for n in Xarray[LeftTopX:RightTopX]:
Yarray[n]=[_**The formula goes here**_]
return Yarray
Note: Xarray and Yarray are each single-column vectors with data at each index that links the two arrays as sets of x,y coordinates. They are both numpy arrays. Xarray contains time information and does not change, but Yarray contains signal data, including the corrupted segment that will be replaced with the parabolic data that needs to be calculated by this function.
| [
"So, as I understand it, you have 3 points that you want to fit a parabola to.\nNormally, it's simplest to just use numpy.polyfit, but if you're really worried about speed, and you're fitting exactly three points, there's no point in using a least-squares fit.\nInstead, we have an even-determined system (fitting a ... | [
8
] | [] | [] | [
"numpy",
"python",
"scientific_computing",
"scipy",
"signal_processing"
] | stackoverflow_0004047804_numpy_python_scientific_computing_scipy_signal_processing.txt |
Q:
How is the second argument of the eval function different from the third argument?
class all_items(dict):
def __getitem__(self, key):
return 1
>>> eval("undefined",dict(),all_items())
1
>>> eval("undefined",all_items(),dict())
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
eval("undefined",all_items(),dict())
File "<string>", line 1, in <module>
NameError: name 'undefined' is not defined
The all_items class of dictionary should return 1 for any value. Using the eval function, I want "undefined" to evaluate to 1, even though it isn't defined. This works when the all_items dictionary is the third argument of the eval statement, but not when it is the second argument. My question is why doesn't the second statment evaluate to 1? (And how could I make it work?) I'm using Python 2.5.
A:
The second argument must be a dictionary. Implementing the mapping protocol isn't enough.
| How is the second argument of the eval function different from the third argument? | class all_items(dict):
def __getitem__(self, key):
return 1
>>> eval("undefined",dict(),all_items())
1
>>> eval("undefined",all_items(),dict())
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
eval("undefined",all_items(),dict())
File "<string>", line 1, in <module>
NameError: name 'undefined' is not defined
The all_items class of dictionary should return 1 for any value. Using the eval function, I want "undefined" to evaluate to 1, even though it isn't defined. This works when the all_items dictionary is the third argument of the eval statement, but not when it is the second argument. My question is why doesn't the second statment evaluate to 1? (And how could I make it work?) I'm using Python 2.5.
| [
"The second argument must be a dictionary. Implementing the mapping protocol isn't enough.\n"
] | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004048830_python.txt |
Q:
Cleaning and stripping of strings/HTML - Python
I have a set of questions, of which I do not have an answer to.
1) Stripping lists of string
input:
'item1, item2, \t\t\t item3, \n\n\n \t, item4, , , item5, '
output:
['item1', 'item2', 'item3', 'item4', 'item5']
Anything more efficient than doing the following?
[x.strip() for x in l.split(',') if x.strip()]
2) Cleaning/Sanitizing HTML
keeping basic tags e.g. strong, p, br, ...
removing malicious javascript, css and divs
3) Unicode handling...
what would you recommend for dealing with unicode parsed within documents?
Any ideas? :) Thanks guys!
A:
For the first one you can use split then a list comprehension to trim the extra whitespace:
result = [x.strip() for x in i.split(',')]
And to remove the empty strings from the list:
result = [x for x in result if x]
A:
To clean HTML use lxml.html
import lxml.html
text = lxml.html.fromstring("...")
text.text_content()
A:
I am somewhat of a beginner at python web development, but for cleaning/sanitizing html I have found that the markdown2 library has some very nice features. You can use it with the MarkItUp! jQuery-based editor. They may not solve all your problems but might help you do a lot of work in a short time.
A:
1) you can use the strip method
2) you can use sanitize , http://wonko.com/post/sanitize
3) some unicode tips here: http://blog.trydionel.com/2010/03/23/some-unicode-tips-for-ruby/
A:
1) [j.strip() for j in a.split(',') if j.strip()]
2) check tidy
A:
I tend to write multiple cascading generators, particularly if I want to some output to be part of a test:
stripped_iter = (x.strip() for x in l.split(','))
non_empty_iter = (x for x in stripped_iter if x)
The inspiration is Beazley's presentation on coroutines.
| Cleaning and stripping of strings/HTML - Python | I have a set of questions, of which I do not have an answer to.
1) Stripping lists of string
input:
'item1, item2, \t\t\t item3, \n\n\n \t, item4, , , item5, '
output:
['item1', 'item2', 'item3', 'item4', 'item5']
Anything more efficient than doing the following?
[x.strip() for x in l.split(',') if x.strip()]
2) Cleaning/Sanitizing HTML
keeping basic tags e.g. strong, p, br, ...
removing malicious javascript, css and divs
3) Unicode handling...
what would you recommend for dealing with unicode parsed within documents?
Any ideas? :) Thanks guys!
| [
"For the first one you can use split then a list comprehension to trim the extra whitespace:\nresult = [x.strip() for x in i.split(',')]\n\nAnd to remove the empty strings from the list:\nresult = [x for x in result if x]\n\n",
"To clean HTML use lxml.html\nimport lxml.html\ntext = lxml.html.fromstring(\"...\")\n... | [
2,
2,
1,
1,
1,
1
] | [] | [] | [
"html",
"python",
"sanitization",
"string",
"unicode"
] | stackoverflow_0004047344_html_python_sanitization_string_unicode.txt |
Q:
Java: updated class files not used
I'm developing a Java program through Eclipse locally, and debugging on a remote machine. Whenever I make a change to my program, I copy the corresponding class file to the bin directory on the remote machine. I run my program (a simulator) through a python script via the OS.system command.
The problem is that my program sometimes does not use the updated class files after they have been moved over.
The problem persists even if I log out and back into the remote machine. What's really strange is that, as a test, I deleted the bin directory entirely on the remote machine, and was still able to run my program.
Can anyone explain this?
A:
I would bet dollars for donuts that under some conditions you are not restarting the JVM between tests.
The other obvious thought is that the class is not being copied to the target system as expected, or not to the correct location. Or, of course, the program is not being run from where you expect (i.e. there is another copy of the class files, perhaps in a JAR, which is actually be run).
Explicitly recheck all your assumptions.
| Java: updated class files not used | I'm developing a Java program through Eclipse locally, and debugging on a remote machine. Whenever I make a change to my program, I copy the corresponding class file to the bin directory on the remote machine. I run my program (a simulator) through a python script via the OS.system command.
The problem is that my program sometimes does not use the updated class files after they have been moved over.
The problem persists even if I log out and back into the remote machine. What's really strange is that, as a test, I deleted the bin directory entirely on the remote machine, and was still able to run my program.
Can anyone explain this?
| [
"I would bet dollars for donuts that under some conditions you are not restarting the JVM between tests.\nThe other obvious thought is that the class is not being copied to the target system as expected, or not to the correct location. Or, of course, the program is not being run from where you expect (i.e. there i... | [
1
] | [] | [] | [
"java",
"python"
] | stackoverflow_0004048821_java_python.txt |
Q:
Sharing queues between processes using nested classes (Python)
I have a question about sharing queues between processes in Python. Below, I have three queues, one main process, and three inner processes. Each inner process will be adding and getting values from the various queues (they need easy access to the queues).
I think it works as it is right now, but this code is the foundation of a big project I'm going to work on and I want to make sure that there is not a better way of doing this that I don't know about. I just sort of came up with this idea. It appears from some other posts that nested classes is not very Python-like.
Any advice? Is this code easy or hard to read? Abandon nested classes or leave it as it is?
Thanks all.
class MainController(Process):
def __init__(self):
self.queue_stream = Queue()
self.queue_language = Queue()
self.queue_expander = Queue()
self.control_stream = self.StreamController(self).start()
self.control_language = self.LanguageController(self).start()
self.control_expander = self.ExpanderController(self).start()
print 'Launching Main Controller'
class StreamController(Process):
def __init__(self, main):
Process.__init__(self)
self.main = main
print 'Launching Stream Controller'
def run(self):
while True:
self.main.queue_stream.put('hello, stream')
class LanguageController(Process):
def __init__(self, main):
Process.__init__(self)
self.main = main
print 'Launching Language Controller'
def run(self):
while True:
print self.main.queue_stream.get()
self.main.queue_language.put('hello, language')
class ExpanderController(Process):
def __init__(self, main):
Process.__init__(self)
self.main = main
print 'Launching Expander Controller'
def run(self):
while True:
print self.main.queue_language.get()
self.main.queue_expander.put('hello, expander')
def main():
# Launch all queues for the system
control_main = MainController()
if __name__ == '__main__':
print 'Launching System...'
main()
A:
I recommend you to use the threading module instead of process. I suggest you to use nested classes only if the child classes are extending on functionality the parent class.
class WorkerThread(threading.Thread):
Another recommendation is to use a shared lock between your child threads in order to prevent race conditions on your shared Queue.
tasks_lock.acquire()
ret = tasks_queue.get()
tasks_lock.release()
Take a look on this Example
A:
The child now have to know about the implementation of the father. I discourage that
def infinite_producer(queue):
while True:
queue.put('hello, stream')
class MainController(Process):
def __init__(self):
self.queue_stream = Queue()
self.queue_language = Queue()
self.queue_expander = Queue()
self.self.control_stream = Process(target=infinite_producer,self.queue_stream)
def run(self):
self.control_stream.start()
#... etc you get the idea.
if __name__ == '__main__':
print 'Launching System...'
control_main = MainController()
control_main.start()
| Sharing queues between processes using nested classes (Python) | I have a question about sharing queues between processes in Python. Below, I have three queues, one main process, and three inner processes. Each inner process will be adding and getting values from the various queues (they need easy access to the queues).
I think it works as it is right now, but this code is the foundation of a big project I'm going to work on and I want to make sure that there is not a better way of doing this that I don't know about. I just sort of came up with this idea. It appears from some other posts that nested classes is not very Python-like.
Any advice? Is this code easy or hard to read? Abandon nested classes or leave it as it is?
Thanks all.
class MainController(Process):
def __init__(self):
self.queue_stream = Queue()
self.queue_language = Queue()
self.queue_expander = Queue()
self.control_stream = self.StreamController(self).start()
self.control_language = self.LanguageController(self).start()
self.control_expander = self.ExpanderController(self).start()
print 'Launching Main Controller'
class StreamController(Process):
def __init__(self, main):
Process.__init__(self)
self.main = main
print 'Launching Stream Controller'
def run(self):
while True:
self.main.queue_stream.put('hello, stream')
class LanguageController(Process):
def __init__(self, main):
Process.__init__(self)
self.main = main
print 'Launching Language Controller'
def run(self):
while True:
print self.main.queue_stream.get()
self.main.queue_language.put('hello, language')
class ExpanderController(Process):
def __init__(self, main):
Process.__init__(self)
self.main = main
print 'Launching Expander Controller'
def run(self):
while True:
print self.main.queue_language.get()
self.main.queue_expander.put('hello, expander')
def main():
# Launch all queues for the system
control_main = MainController()
if __name__ == '__main__':
print 'Launching System...'
main()
| [
"I recommend you to use the threading module instead of process. I suggest you to use nested classes only if the child classes are extending on functionality the parent class.\nclass WorkerThread(threading.Thread):\n\nAnother recommendation is to use a shared lock between your child threads in order to prevent ra... | [
1,
0
] | [] | [] | [
"inner_classes",
"process",
"python"
] | stackoverflow_0004048789_inner_classes_process_python.txt |
Q:
Python: unit testing socket-based code?
I'm writing a Python client+server that uses gevent.socket for communication. Are there any good ways of testing the socket-level operation of the code (for example, verifying that SSL connections with an invalid certificate will be rejected)? Or is it simplest to just spawn a real server?
Edit: I don't believe that "naive" mocking will be sufficient to test the SSL components because of the complex interactions involved. Am I wrong in that? Or is there a better way to test SSL'd stuff?
A:
You can easily start a server and then access it in a test case. The gevent's own test suite does exactly that for testing gevent's built-in servers.
For example:
class SimpleServer(gevent.server.StreamServer):
def handle(self, socket, address):
socket.sendall('hello and goodbye!')
class Test(unittest.TestCase):
def test(self):
server = SimpleServer(('127.0.0.1', 0))
server.start()
client = gevent.socket.create_connection(('127.0.0.1', server.server_port))
response = client.makefile().read()
assert response == 'hello and goodbye!'
server.stop()
Using 0 for the port value means the server will use any available port. After the server is started, the actual value chosen by bind is available as server_port attribute.
StreamServer supports SSL too, pass keyfile and certfile arguments to the constructor and it will wrap each socket with SSLObject before passing it to your handler.
If you don't use StreamServer and your server is based on Greenlet then indeed spawning it is what you should do. Don't forget to kill it at the end of the test case.
Starting a server and spawning a greenlet are fast operations in gevent, much faster than creating a new thread or process and you can easily create a new server for each test case. Just don't forget to cleanup as soon as you don't need the server anymore.
I believe there's no need to mock any of gevent API, it's much easier just to use it as servers and clients can happily live within the same process.
A:
Mocking and stubbing are great, but sometimes you need to take it up to the next level of integration. Since spawning a server, even a fakeish one, can take some time, consider a separate test suite (call them integration tests) might be in order.
"Test it like you are going to use it" is my guideline, and if you mock and stub so much that your test becomes trivial it's not that useful (though almost any test is better than none). If you are concerned about handling bad SSL certs, by all means make some bad ones and write a test fixture you can feed them to. If that means spawning a server, so be it. Maybe if that bugs you enough it will lead to a refactoring that will make it testable another way.
A:
There is another (IMO better) way: You should mock the library you are using.
An example mocking helper for python is mox.
You don't need a set of servers with a valid certificate, another with an invalid certificate, with no ssl support at all, ones not responding to any packets at all, etc. You can simulate their behavior with a "dummy" client socket. The way it works with Mox is You first "teach" what it should expect and how it should react and then You execute Your real code on it while swapping the real gevent.socket for the mocked one. It requires some practice to get the hang of it, but it's worth it.
| Python: unit testing socket-based code? | I'm writing a Python client+server that uses gevent.socket for communication. Are there any good ways of testing the socket-level operation of the code (for example, verifying that SSL connections with an invalid certificate will be rejected)? Or is it simplest to just spawn a real server?
Edit: I don't believe that "naive" mocking will be sufficient to test the SSL components because of the complex interactions involved. Am I wrong in that? Or is there a better way to test SSL'd stuff?
| [
"You can easily start a server and then access it in a test case. The gevent's own test suite does exactly that for testing gevent's built-in servers.\nFor example:\nclass SimpleServer(gevent.server.StreamServer):\n\n def handle(self, socket, address):\n socket.sendall('hello and goodbye!')\n\nclass Test(... | [
19,
9,
8
] | [] | [] | [
"gevent",
"python",
"sockets",
"testing"
] | stackoverflow_0004047897_gevent_python_sockets_testing.txt |
Q:
How do I get around not being able to parse a table name into a python sqlite query?
I have a python3 program that I'm making which uses a sqlite database with several tables, I want to create a selector module to allow me to chose which table to pull data from.
I have found out that I can't use parameter substitution for a table name as shown bellow, so I'm looking for some alternative methods to accomplish this.
c.execute("SELECT * FROM ? ", DB)
Any ideas?
A:
Right. You can not use parameter substitution to specify the table.
So instead you must do string manipulation:
c.execute("SELECT * FROM {t} ".format(t=tablename))
A:
I don't know if this is a python3 thing but it seems easiest to just do this:
c.execute("SELECT * FROM %s "% tablename)
A:
Blockquote *
Right. You can not use parameter
substitution to specify the table. So
instead you must do string
manipulation: c.execute("SELECT * FROM
{t} ".format(t=tablename))*
Blockquote
Thanks unutbu, this is just what I needed.
| How do I get around not being able to parse a table name into a python sqlite query? | I have a python3 program that I'm making which uses a sqlite database with several tables, I want to create a selector module to allow me to chose which table to pull data from.
I have found out that I can't use parameter substitution for a table name as shown bellow, so I'm looking for some alternative methods to accomplish this.
c.execute("SELECT * FROM ? ", DB)
Any ideas?
| [
"Right. You can not use parameter substitution to specify the table.\nSo instead you must do string manipulation:\nc.execute(\"SELECT * FROM {t} \".format(t=tablename))\n\n",
"I don't know if this is a python3 thing but it seems easiest to just do this:\nc.execute(\"SELECT * FROM %s \"% tablename)\n\n",
"\nBloc... | [
1,
1,
0
] | [] | [] | [
"parsing",
"python",
"sqlite"
] | stackoverflow_0004044512_parsing_python_sqlite.txt |
Q:
Is it safe to use SQLalchemy with gevent?
I know that some database drivers and other libraries providing connection to external services are incompatible with coroutine-based network libraries. However, I couldn't find out if SQLAlchemy can be safely used with such libraries (namely, gevent), and if any workarounds should be applied to exclude possible errors.
Can you either tell me that or point me to an article where I can read this information? An additional 'thank you' if the provided answer also contains explanation of the mechanics of why it is okay or why it isn't. :-)
A:
Did you try searching gevent google group for SQLAlchemy?
I found this report of using SQLAlchemy + mysql-connector successfully and this of using SQLAlchemy + psycopg2 successfully (make sure you've read this)
I would think SQLAlchemy should be safe to use with gevent as long as the database driver that SQLAlchemy uses is safe, but I've not tried it myself and only basing this on the reports from other users.
| Is it safe to use SQLalchemy with gevent? | I know that some database drivers and other libraries providing connection to external services are incompatible with coroutine-based network libraries. However, I couldn't find out if SQLAlchemy can be safely used with such libraries (namely, gevent), and if any workarounds should be applied to exclude possible errors.
Can you either tell me that or point me to an article where I can read this information? An additional 'thank you' if the provided answer also contains explanation of the mechanics of why it is okay or why it isn't. :-)
| [
"Did you try searching gevent google group for SQLAlchemy?\nI found this report of using SQLAlchemy + mysql-connector successfully and this of using SQLAlchemy + psycopg2 successfully (make sure you've read this)\nI would think SQLAlchemy should be safe to use with gevent as long as the database driver that SQLAlch... | [
23
] | [] | [] | [
"gevent",
"python",
"sqlalchemy",
"thread_safety"
] | stackoverflow_0004033475_gevent_python_sqlalchemy_thread_safety.txt |
Q:
Analyse source code in Java using Python?
i would like to create a source code analyser for Java Project (like FindBugs and other static analysis programs) that would be able to detect certain method calls.
I would prefer to do it using Python, but any advice would be great !
I'm going to start by studying the FindBugs source code, but if anyone could explain to me the underlying concepts and if it's easily do-able, i would be really grateful.
Thank you for your time.
Olivier.
A:
Read the book : Language implementation Patterns. It is a very accessible book out there and you can gauge the effort that will be required to achieve what you want to achieve
http://www.pragprog.com/titles/tpdsl/language-implementation-patterns
| Analyse source code in Java using Python? | i would like to create a source code analyser for Java Project (like FindBugs and other static analysis programs) that would be able to detect certain method calls.
I would prefer to do it using Python, but any advice would be great !
I'm going to start by studying the FindBugs source code, but if anyone could explain to me the underlying concepts and if it's easily do-able, i would be really grateful.
Thank you for your time.
Olivier.
| [
"Read the book : Language implementation Patterns. It is a very accessible book out there and you can gauge the effort that will be required to achieve what you want to achieve\n\nhttp://www.pragprog.com/titles/tpdsl/language-implementation-patterns\n\n"
] | [
2
] | [] | [] | [
"java",
"python",
"static_analysis"
] | stackoverflow_0004049321_java_python_static_analysis.txt |
Q:
How to return local vars([object]) from function?
I use vars() function for the first time, and noticed this behaviour:
nodes = ['one', 'two', 'three']
for node in nodes:
vars()[node + '_'] = 'some calc ' + node
vars()[node] = vars()[node + '_']
print one
With this snippet Python outputs some calc one as expected, but if I use it inside function like this:
def main():
nodes = ['one', 'two', 'three']
for node in nodes:
vars()[node + '_'] = 'some calc ' + node
vars()[node] = vars()[node + '_']
print one
main()
it outputs NameError: global name 'one' is not defined
vars() object is dict:
{'node': 'three', 'three_': 'some calc three', 'two': 'some calc two', 'one': 'some calc one', 'two_': 'some calc two', 'three': 'some calc three', 'nodes': ['one', 'two', 'three'], 'one_': 'some calc one'}
Now, I would like to know what's going on as this function is not well documented and I can't find example how to return those variables if inside function
A:
The reason that it works when called in a modules 'global' scope, is that it is equivalent to globals() in that context which is actually a dictionary stored by python. The locals of non-global scopes are not actually a dictionary in the implementation, (this is to avoid having to lookup dictionary keys when accessing them) and so there is no real dictionary to return. Instead, Python makes one up for you but it is not in any way connected to the real array of local variables. The only way that I know of to insert new locals into an executing frame is to use exec or eval but there is almost always a better way to do what you want that doesn't involve creating locals on the fly.
If you want to create locals in a non-executing frame, then you can apply bytecode transformations to it to, e.g. turn globals into locals, cells or constants but that is some non-trivial black magic and, again, there is almost certainly a better way.
Your question makes reference to returning things but I don't see anything that you are returning. What exactly do you want to return?
I would thing that the name that you give your return values should have very little impact as this is not the name that they will be given in the calling frame. Why doesn't a simple dictionary suffice?
A:
vars() acts like locals() if called with no args, so from the docs:
Note: The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.
| How to return local vars([object]) from function? | I use vars() function for the first time, and noticed this behaviour:
nodes = ['one', 'two', 'three']
for node in nodes:
vars()[node + '_'] = 'some calc ' + node
vars()[node] = vars()[node + '_']
print one
With this snippet Python outputs some calc one as expected, but if I use it inside function like this:
def main():
nodes = ['one', 'two', 'three']
for node in nodes:
vars()[node + '_'] = 'some calc ' + node
vars()[node] = vars()[node + '_']
print one
main()
it outputs NameError: global name 'one' is not defined
vars() object is dict:
{'node': 'three', 'three_': 'some calc three', 'two': 'some calc two', 'one': 'some calc one', 'two_': 'some calc two', 'three': 'some calc three', 'nodes': ['one', 'two', 'three'], 'one_': 'some calc one'}
Now, I would like to know what's going on as this function is not well documented and I can't find example how to return those variables if inside function
| [
"The reason that it works when called in a modules 'global' scope, is that it is equivalent to globals() in that context which is actually a dictionary stored by python. The locals of non-global scopes are not actually a dictionary in the implementation, (this is to avoid having to lookup dictionary keys when acce... | [
2,
0
] | [] | [] | [
"python"
] | stackoverflow_0004049491_python.txt |
Q:
limit_choice_to all objects of a particular model classe in a ForeignKey
Example
class Base():
pass
class A(Base)
parent=models.Foreignkey("self", limit_choices_to=(all members of the B class)
class B(Base)
parent=models.Foreignkey("self", limit_choices_to=(all members of the A class)
What would be the query syntax for limit_choices_to, to get only the
objects of a certain class?)
A:
Wouldn't this work instead ?
class Base(Model):
parent=models.Foreignkey("self")
class Meta:
abstract = True
class A(Base):
parent=models.Foreignkey("B")
class B(Base):
parent=models.Foreignkey("A")
| limit_choice_to all objects of a particular model classe in a ForeignKey | Example
class Base():
pass
class A(Base)
parent=models.Foreignkey("self", limit_choices_to=(all members of the B class)
class B(Base)
parent=models.Foreignkey("self", limit_choices_to=(all members of the A class)
What would be the query syntax for limit_choices_to, to get only the
objects of a certain class?)
| [
"Wouldn't this work instead ?\nclass Base(Model):\n parent=models.Foreignkey(\"self\")\n\n class Meta:\n abstract = True\n\n\nclass A(Base):\n parent=models.Foreignkey(\"B\")\n\nclass B(Base):\n parent=models.Foreignkey(\"A\")\n\n"
] | [
1
] | [] | [] | [
"django",
"django_models",
"python"
] | stackoverflow_0004047900_django_django_models_python.txt |
Q:
how do I advance to the next item in a nested list? Python
Working with a couple of lists, iterating over each. Here's a code segment:
self.links = []
self.iter=iter(self.links)
for tgt in self.links:
for link in self.mal_list:
print(link)
if tgt == link:
print("Found Suspicious Link: {0}".format(tgt))
self.count += 1
else:
self.count += 1
self.crawl(self.iter.next())
Its advancing to the next item in the link list, just fine. For the malware signature list I tried using a similar iter item, but I'm not entirely sure if thats even the best way, and if so were to place it in my code so that each link that is urlopened from the list is compared to every item in the malware list BEFORE the loop opens up the next item in the link list. Any suggestions?
A:
Not sure, what you are trying to ask but you could simplify your code. Though this is not necessary.
self.links = []
self.non_malware_link = [link for link in self.links if link not in self.mal_list]
results = map(self.crawl, self.non_malware_link)
On some issues with your code:
self.count is exactly the same as len(self.links)
Apart from meaning of self.count, every thing else looks like it does what it needs to do.
A:
The essential way that you are doing it is fine, but it will be slow.
Try this instead:
for tgt in links:
if tgt in mal_links:
# you know that it's a bad link
else:
crawl(tgt)
I don't see why you are keeping two iterators going over the list. This will introduce a bug because you don't call next on self.iter in the case that you detect a malware link. The next time tgt isn't a bad link, when you call next, it will advance to the previously detected bad link and you will crawl that. Is there some reason that you feel the need to step over two copies of the iterator instead of just one?
Also, your initial code will crawl page once for every time it is not determined to be equal to a given malware link. This might lead to some angry web masters depending on how big your list is.
A:
Searching an item inside a list is slow, if this is what you're trying to do, then use a dict or a set instead of list for the self.mal_list:
mal_list = set(self.mal_list)
for tgt in self.links:
if tgt in mal_list:
print("Found Suspicious Link: {0}".format(tgt))
self.count += 1
else:
self.count += 1
self.crawl(self.iter.next())
or, if you can have self.links as set as well:
mal_list = set(self.mal_list)
links = set(self.links)
detected = links.intersection(mal_list)
for malware in detected:
print("Found Suspicious Link: {0}".format(tgt))
self.count += 1
| how do I advance to the next item in a nested list? Python | Working with a couple of lists, iterating over each. Here's a code segment:
self.links = []
self.iter=iter(self.links)
for tgt in self.links:
for link in self.mal_list:
print(link)
if tgt == link:
print("Found Suspicious Link: {0}".format(tgt))
self.count += 1
else:
self.count += 1
self.crawl(self.iter.next())
Its advancing to the next item in the link list, just fine. For the malware signature list I tried using a similar iter item, but I'm not entirely sure if thats even the best way, and if so were to place it in my code so that each link that is urlopened from the list is compared to every item in the malware list BEFORE the loop opens up the next item in the link list. Any suggestions?
| [
"Not sure, what you are trying to ask but you could simplify your code. Though this is not necessary.\nself.links = []\nself.non_malware_link = [link for link in self.links if link not in self.mal_list]\nresults = map(self.crawl, self.non_malware_link)\n\nOn some issues with your code:\n\nself.count is exactly the ... | [
2,
1,
1
] | [] | [] | [
"iteration",
"list",
"python"
] | stackoverflow_0004049706_iteration_list_python.txt |
Q:
Pylons: Sharing SQLAlchemy MySQL connection with external library
I am running Pylons using SQLAlchemy to connect to MySQL, so when I want to use a database connection in a controller, I can do this:
from myapp.model.meta import Session
class SomeController(BaseController):
def index(self):
conn = Session.connection()
rows = conn.execute('SELECT whatever')
...
Say my controller needs to call up an external library, that also needs a database connection, and I want to provide the connection for it from the SQLAlchemy MySQL connection that is already established:
from myapp.model.meta import Session
import mymodule
class SomeController(BaseController):
def index(self):
conn = Session.connection()
myobject = mymodule.someobject(DATABASE_OBJECT)
...
conn.close()
What should DATABSE_OBJECT be? Possibilities:
Pass Session -- and then open and close Session.connection() in the module code
Pass conn, and then call conn.close() in the controller
Just pass the connection parameters, and have the module code set up its own connection
There is another wrinkle, which is that I need to instantiate some objects in app_globals.py, and these objects need a database connection as well. It seems that app_globals.py cannot use Session's SQLAlchemy connection yet -- it's not bound yet.
Is my architecture fundamentally unsounds? Should I not be trying to share connections between Pylons and external libraries this way? Thanks!
A:
You should not manage connections yourself - it's all done by SQLAlchemy. Just use scoped session object everywhere, and you will be fine.
def init_model(engine):
sm = orm.sessionmaker(autoflush=False, autocommit=False, expire_on_commit=False, bind=engine)
meta.engine = engine
meta.Session = orm.scoped_session(sm)
def index(self):
rows = Session.execute('SELECT ...')
You can pass Session object to your external library and do queries there as you wish. There is no need to call .close() on it.
Regarding app_globals, I solved that by adding other method in globals class which is called after db initialization from environment.py
class Globals(...):
def init_model(self, config):
self.some_persistent_db_object = Session.execute('...')
def load_environment(...):
...
config['pylons.app_globals'].init_model(config)
return config
A:
What should DATABSE_OBJECT be? Possibilities:
4. pass a "proxy" or "helper" object with higher level of abstraction interface
Unless the external library really needs direct access to SQLAlchemy session, you could provide it with object that has methods like "get_account(account_no)" instead of "execute(sql)". Doing so would keep SQLAlchemy-specific code more isolated, and the code would be also easier to test.
Sorry that this is not so much an answer to your original question, more a design suggestion.
| Pylons: Sharing SQLAlchemy MySQL connection with external library | I am running Pylons using SQLAlchemy to connect to MySQL, so when I want to use a database connection in a controller, I can do this:
from myapp.model.meta import Session
class SomeController(BaseController):
def index(self):
conn = Session.connection()
rows = conn.execute('SELECT whatever')
...
Say my controller needs to call up an external library, that also needs a database connection, and I want to provide the connection for it from the SQLAlchemy MySQL connection that is already established:
from myapp.model.meta import Session
import mymodule
class SomeController(BaseController):
def index(self):
conn = Session.connection()
myobject = mymodule.someobject(DATABASE_OBJECT)
...
conn.close()
What should DATABSE_OBJECT be? Possibilities:
Pass Session -- and then open and close Session.connection() in the module code
Pass conn, and then call conn.close() in the controller
Just pass the connection parameters, and have the module code set up its own connection
There is another wrinkle, which is that I need to instantiate some objects in app_globals.py, and these objects need a database connection as well. It seems that app_globals.py cannot use Session's SQLAlchemy connection yet -- it's not bound yet.
Is my architecture fundamentally unsounds? Should I not be trying to share connections between Pylons and external libraries this way? Thanks!
| [
"You should not manage connections yourself - it's all done by SQLAlchemy. Just use scoped session object everywhere, and you will be fine.\ndef init_model(engine):\n sm = orm.sessionmaker(autoflush=False, autocommit=False, expire_on_commit=False, bind=engine)\n meta.engine = engine\n meta.Session = orm.sc... | [
2,
1
] | [] | [] | [
"mysql",
"pylons",
"python",
"sqlalchemy"
] | stackoverflow_0004047735_mysql_pylons_python_sqlalchemy.txt |
Q:
How do I see the arguments (and types) of a python method?
$ py twitterDump2.py
Traceback (most recent call last):
File "twitterDump2.py", line 30, in <module>
stream=tweepy.Stream(username,password,listener)
TypeError: __init__() takes exactly 3 arguments (4 given)
My code:
username="abc"
password="abc"
listener = StreamWatcherListener()
stream=tweepy.Stream(username,password,listener)
A:
The first argument to __init__ is usually self so it is expecting you to pass only two arguments.
Surprising the tweepy.streaming.py code suggests:
class Stream(object):
host = 'stream.twitter.com'
def __init__(self, auth, listener, **options):
self.auth = auth
self.listener = listener
The auth is created this way:
auth = tweepy.BasicAuthHandler(username, password)
Your code should be something like this
username="abc"
password="abc"
listener = StreamWatcherListener()
auth = tweepy.BasicAuthHandler(username, password)
stream=tweepy.Stream(auth,listener)
See the code at : http://github.com/joshthecoder/tweepy/blob/master/tweepy/streaming.py
A:
pyfunc has given the reasons why this is not working.
To see what arguments, type:
help(tweepy.Stream)
This will give you what arguments the Stream class requires.
This is for your reference:
def __init__(self, auth, listener, **options)
options takes a dictionary that delivers keywords arguments with the ** operator.
| How do I see the arguments (and types) of a python method? | $ py twitterDump2.py
Traceback (most recent call last):
File "twitterDump2.py", line 30, in <module>
stream=tweepy.Stream(username,password,listener)
TypeError: __init__() takes exactly 3 arguments (4 given)
My code:
username="abc"
password="abc"
listener = StreamWatcherListener()
stream=tweepy.Stream(username,password,listener)
| [
"The first argument to __init__ is usually self so it is expecting you to pass only two arguments.\nSurprising the tweepy.streaming.py code suggests:\nclass Stream(object):\n\n host = 'stream.twitter.com'\n\n def __init__(self, auth, listener, **options):\n self.auth = auth\n self.listener = lis... | [
2,
2
] | [] | [] | [
"class",
"function",
"methods",
"python",
"twitter"
] | stackoverflow_0004050108_class_function_methods_python_twitter.txt |
Q:
Homemade tiny memcache
I'm moving a Google App Engine web application outside "the cloud" to a standard web framework (webpy) and I would like to know how to implement a memcache feature available on Gae.
In my app I just use this cache to store a bunch of data retrieved from a remote api every X hours; in other words I don't stress this cache too much.
I've naively implemented something like this:
class TinyCache():
class _Container():
def __init__(self, value, seconds):
self.value = value
self.cache_age = datetime.now()
self.cache_time = timedelta(seconds = seconds)
def is_stale(self):
return self.cache_age + self.cache_time < datetime.now()
def __init__(self):
self.dict_cache={}
def add(self, key, value, seconds = 7200):
self.dict_cache[key] = self._Container(value, seconds)
def get(self, key):
if key in self.dict_cache:
if self.dict_cache[key].is_stale():
del self.dict_cache[key]
return None
else:
return self.dict_cache[key].value
else:
return None
A typical usage would be:
data = tinycache.get("remote_api_data")
if data is not None:
return data
else:
data = self.api_call()
tinycache.add("remote_api_data", data, 7200)
return data
How could I improve it?
Do I need to make it Thread-Safe?
A:
It seems to me that your cache can grow inefficiently since it will keep entries that are rarely used. Because, it seems that the entries in your cache don't get removed unless a get operation is requested for an specific key.
If you want to improve your cache I'd add the following two simple features:
When an Item is requested I would restart seconds to the initial value. So to keep the elements that your system is often using.
I would implement in a separate thread a mechanism to traverse the cache and delete entries that are too old.
you also can get some ideas from this Fixed size cache
Edited
I just found this recipe, it's super-cool. Basically you can wrapped up with function decorators the logic you want to cache. Something like:
@lru_cache(maxsize=20)
def my_expensive_function(x, y):
# my expensive logic here
return result
These LRU and LFU cache decorator decorators will implement for you the cache logic. Least Recently Used (LRU) or Least Frequently Used (LFU) (see Cache_algorithms for reference on these)
A:
In my app I just use this cache to store a bunch of data retrieved from a remote api every X hours; in other words I don't stress this cache too much.
…
How could I improve it?
If your code works for you, why bother?
However as you explicitly asked for comments, I try to add my ideas anyway. To me it sounds like you could use a traditional storage like files or a database to store the data as it is only refreshed periodically. In many cases one just needs some (potentially expensive) preprocessing, so you might be able to focus on doing the work once and just storing the data in a form so access/delivery to the client is fast.
Advantages:
simple
no issues with multiple processes (e.g. FastCGI)
reduced memory foot print
Do I need to make it Thread-Safe?
That really depends on your usage pattern. However from your API I guess that's not really necessary as you compute a value twice (worst case).
| Homemade tiny memcache | I'm moving a Google App Engine web application outside "the cloud" to a standard web framework (webpy) and I would like to know how to implement a memcache feature available on Gae.
In my app I just use this cache to store a bunch of data retrieved from a remote api every X hours; in other words I don't stress this cache too much.
I've naively implemented something like this:
class TinyCache():
class _Container():
def __init__(self, value, seconds):
self.value = value
self.cache_age = datetime.now()
self.cache_time = timedelta(seconds = seconds)
def is_stale(self):
return self.cache_age + self.cache_time < datetime.now()
def __init__(self):
self.dict_cache={}
def add(self, key, value, seconds = 7200):
self.dict_cache[key] = self._Container(value, seconds)
def get(self, key):
if key in self.dict_cache:
if self.dict_cache[key].is_stale():
del self.dict_cache[key]
return None
else:
return self.dict_cache[key].value
else:
return None
A typical usage would be:
data = tinycache.get("remote_api_data")
if data is not None:
return data
else:
data = self.api_call()
tinycache.add("remote_api_data", data, 7200)
return data
How could I improve it?
Do I need to make it Thread-Safe?
| [
"It seems to me that your cache can grow inefficiently since it will keep entries that are rarely used. Because, it seems that the entries in your cache don't get removed unless a get operation is requested for an specific key.\nIf you want to improve your cache I'd add the following two simple features:\n\nWhen an... | [
2,
0
] | [] | [] | [
"memcached",
"python"
] | stackoverflow_0004004362_memcached_python.txt |
Q:
Impossible to create a configuration file for an python application inside Google App Engine
I try to create a configuration file, where I can store constants.
Whenever I try with ConfigParser, I get an error
Traceback (most recent call last):
File "/home/baun/google_appengine/google/appengine/ext/webapp /__init__.py", line 511, in __call__
handler.get(*groups)
File "/home/baun/workspace/octopuscloud/s3/S3.py", line 138, in get
test = parser.get('bucket', 'bucketname')
File "/usr/lib/python2.5/ConfigParser.py", line 511, in get
raise NoSectionError(section)
NoSectionError: No section: 'bucket'
simple.cfg:
[bucket]
bucketname: 'octopus_storage'
s3.py:
...
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read('simple.cfg')
...
# Get values from the config file
test = parser.get('bucket', 'bucketname')
...
How can I fix this?
===============================
The problem is fixed. The code was correct, but simple.cfg was in the wrong directory.
A:
[bucket]
bucketname= octopus_storage
| Impossible to create a configuration file for an python application inside Google App Engine | I try to create a configuration file, where I can store constants.
Whenever I try with ConfigParser, I get an error
Traceback (most recent call last):
File "/home/baun/google_appengine/google/appengine/ext/webapp /__init__.py", line 511, in __call__
handler.get(*groups)
File "/home/baun/workspace/octopuscloud/s3/S3.py", line 138, in get
test = parser.get('bucket', 'bucketname')
File "/usr/lib/python2.5/ConfigParser.py", line 511, in get
raise NoSectionError(section)
NoSectionError: No section: 'bucket'
simple.cfg:
[bucket]
bucketname: 'octopus_storage'
s3.py:
...
from ConfigParser import SafeConfigParser
parser = SafeConfigParser()
parser.read('simple.cfg')
...
# Get values from the config file
test = parser.get('bucket', 'bucketname')
...
How can I fix this?
===============================
The problem is fixed. The code was correct, but simple.cfg was in the wrong directory.
| [
"[bucket]\nbucketname= octopus_storage\n\n"
] | [
2
] | [] | [] | [
"configparser",
"configuration",
"configuration_files",
"google_app_engine",
"python"
] | stackoverflow_0004050405_configparser_configuration_configuration_files_google_app_engine_python.txt |
Q:
Python/Tkinter: Using custom mouse cursors under Windows?
Python 2.7/Windows: My understanding is that we can load custom mouse cursors using the cursor='@file.cur' syntax:
widget = tkinter.Label( ..., cursor='@help.cur' )
Here's the traceback I receive:
Traceback (most recent call last):
File "<pyshell#82>", line 1, in <module>
widget.config( cursor='@help.cur' )
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1202, in configure
return self._configure('configure', cnf, kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1193, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
TclError: bad cursor spec "@help.cur"
Is it possible to load custom mouse cursors under Windows using Tkinter, a Tkinter extension, or via a Win32 API call?
A:
lbl=Label(root, text="toto", cursor="@toto.cur") works for me on Python 2.6 and Vista. Make sure that the cur file is in the working directory of your script (I have a similar traceback if I try to load a non-existing cursor) and that the file is not corrupted.
As an alternative, here is a list of internal cursors: http://www.tcl.tk/man/tcl8.4/TkCmd/cursors.htm
| Python/Tkinter: Using custom mouse cursors under Windows? | Python 2.7/Windows: My understanding is that we can load custom mouse cursors using the cursor='@file.cur' syntax:
widget = tkinter.Label( ..., cursor='@help.cur' )
Here's the traceback I receive:
Traceback (most recent call last):
File "<pyshell#82>", line 1, in <module>
widget.config( cursor='@help.cur' )
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1202, in configure
return self._configure('configure', cnf, kw)
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1193, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
TclError: bad cursor spec "@help.cur"
Is it possible to load custom mouse cursors under Windows using Tkinter, a Tkinter extension, or via a Win32 API call?
| [
"lbl=Label(root, text=\"toto\", cursor=\"@toto.cur\") works for me on Python 2.6 and Vista. Make sure that the cur file is in the working directory of your script (I have a similar traceback if I try to load a non-existing cursor) and that the file is not corrupted.\nAs an alternative, here is a list of internal cu... | [
5
] | [] | [] | [
"icons",
"python",
"tkinter",
"user_interface"
] | stackoverflow_0004049612_icons_python_tkinter_user_interface.txt |
Q:
Broken anydbm.py on ubuntu 10.04 with python 2.6.5?
When trying to run django-celery with beat scheduler:
bin/django celeryd -B --settings=app.development --loglevel=INFO
I got this exception:
Process Beat:
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/multiprocessing/process.py", line 237, in _bootstrap
self.run()
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/beat.py", line 388, in run
self.service.start(embedded_process=True)
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/beat.py", line 318, in start
humanize_seconds(self.scheduler.max_interval)))
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/beat.py", line 358, in scheduler
self._scheduler = self.get_scheduler()
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/beat.py", line 350, in get_scheduler
lazy=lazy)
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/utils/__init__.py", line 362, in instantiate
return get_cls_by_name(name)(*args, **kwargs)
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/beat.py", line 270, in __init__
Scheduler.__init__(self, *args, **kwargs)
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/beat.py", line 146, in __init__
self.setup_schedule()
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/beat.py", line 273, in setup_schedule
self._store = self.persistence.open(self.schedule_filename)
File "/usr/lib/python2.6/shelve.py", line 239, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File "/usr/lib/python2.6/shelve.py", line 223, in __init__
Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback)
AttributeError: 'module' object has no attribute 'open'
My own investigation led me to discovering that the anydbm python module found in
/usr/lib/python2.6/anydbm.py
is an empty file. But the python2.6.5 doc says there is an
anydbm.open(filename[, flag[, mode]])
method.
Am I missing something? I think the anydbm [ubuntu] python module is broken.
I'm using:
Ubuntu 10.04
Python 2.6.5
django-celery 2.1.1
celery installed with buildout
A:
If /usr/lib/python2.6/anydbm.py is an empty file for you, then yes, your installation is broken. /usr/lib/python2.6/anydbm.py is the correct file, with contents, on my Ubuntu 10.04 system, with python2.6_2.6.5-1ubuntu6 installed. You'll want to make sure you have the latest package installed, and possibly reinstall it.
| Broken anydbm.py on ubuntu 10.04 with python 2.6.5? | When trying to run django-celery with beat scheduler:
bin/django celeryd -B --settings=app.development --loglevel=INFO
I got this exception:
Process Beat:
Traceback (most recent call last):
File "/usr/local/lib/python2.6/dist-packages/multiprocessing/process.py", line 237, in _bootstrap
self.run()
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/beat.py", line 388, in run
self.service.start(embedded_process=True)
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/beat.py", line 318, in start
humanize_seconds(self.scheduler.max_interval)))
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/beat.py", line 358, in scheduler
self._scheduler = self.get_scheduler()
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/beat.py", line 350, in get_scheduler
lazy=lazy)
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/utils/__init__.py", line 362, in instantiate
return get_cls_by_name(name)(*args, **kwargs)
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/beat.py", line 270, in __init__
Scheduler.__init__(self, *args, **kwargs)
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/beat.py", line 146, in __init__
self.setup_schedule()
File "/home/user/eggs/celery-2.1.1-py2.6.egg/celery/beat.py", line 273, in setup_schedule
self._store = self.persistence.open(self.schedule_filename)
File "/usr/lib/python2.6/shelve.py", line 239, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File "/usr/lib/python2.6/shelve.py", line 223, in __init__
Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback)
AttributeError: 'module' object has no attribute 'open'
My own investigation led me to discovering that the anydbm python module found in
/usr/lib/python2.6/anydbm.py
is an empty file. But the python2.6.5 doc says there is an
anydbm.open(filename[, flag[, mode]])
method.
Am I missing something? I think the anydbm [ubuntu] python module is broken.
I'm using:
Ubuntu 10.04
Python 2.6.5
django-celery 2.1.1
celery installed with buildout
| [
"If /usr/lib/python2.6/anydbm.py is an empty file for you, then yes, your installation is broken. /usr/lib/python2.6/anydbm.py is the correct file, with contents, on my Ubuntu 10.04 system, with python2.6_2.6.5-1ubuntu6 installed. You'll want to make sure you have the latest package installed, and possibly reinstal... | [
0
] | [] | [] | [
"python"
] | stackoverflow_0004050519_python.txt |
Q:
Retrieving hierarchial data from datastore
I am building an app with Google App Engine (and Python). I have two questions about retrieving data from datastore.
I have information about users and information about posts made by users. Here is part of DB Models:
class User(db.Model):
country = db.StringProperty()
# many other entities
class Post(db.Model):
author = db.ReferenceProperty(User)
# many other entities
I want to retrieve Posts, that are made by users from certain country. I tried it this way:
posts_query = Post.all().filter(' author.country == ', country)
posts = posts_query.fetch(limit = 100)
But this query does not return any results (the country variable has a value that exists in the datastore). What I need to correct in my query, so it works?
And the second question: how (in the given situation) I can retrieve all posts from datastore, if the post count is unknown (and may be > 100)?
Thanks in advance,
-skazhy
A:
If you want to do this, you need to denormalize: store a copy of the user's country on all their posts, and query on that. The datastore doesn't support joins, which would be required to satisfy this query, and in any case denormalizing is a lot more efficient.
As far as retrieving 'all' results goes, you can specify an arbitrarily large limit, but consider: do you really want to do this? There's a limit on how many results you can sensibly present to a user in one go; if you have more results than that, you almost certainly want to paginate, instead.
A:
Seconding denormalization. If country is a specific thing you need to query on frequently, you could add a new model just for it. The Country then becomes a ReferenceProperty for both the user and the Post:
class User(db.Model):
country = db.ReferenceProperty(Country,collection_name=users)
# many other entities
class Post(db.Model):
author = db.ReferenceProperty(User)
country = db.ReferenceProperty(Country,collection_name=posts)
# many other entities
class Country(db.Model):
name = db.StringProperty()
# posts from everyone in the user's country:
# user.country.posts.all()
In response to your second question, you can use your posts_query as an iterable to retrieve all results. See the App Engine docs: http://code.google.com/appengine/docs/python/datastore/queryclass.html#Query_fetch
| Retrieving hierarchial data from datastore | I am building an app with Google App Engine (and Python). I have two questions about retrieving data from datastore.
I have information about users and information about posts made by users. Here is part of DB Models:
class User(db.Model):
country = db.StringProperty()
# many other entities
class Post(db.Model):
author = db.ReferenceProperty(User)
# many other entities
I want to retrieve Posts, that are made by users from certain country. I tried it this way:
posts_query = Post.all().filter(' author.country == ', country)
posts = posts_query.fetch(limit = 100)
But this query does not return any results (the country variable has a value that exists in the datastore). What I need to correct in my query, so it works?
And the second question: how (in the given situation) I can retrieve all posts from datastore, if the post count is unknown (and may be > 100)?
Thanks in advance,
-skazhy
| [
"If you want to do this, you need to denormalize: store a copy of the user's country on all their posts, and query on that. The datastore doesn't support joins, which would be required to satisfy this query, and in any case denormalizing is a lot more efficient.\nAs far as retrieving 'all' results goes, you can spe... | [
3,
0
] | [] | [] | [
"google_app_engine",
"google_cloud_datastore",
"python"
] | stackoverflow_0004041967_google_app_engine_google_cloud_datastore_python.txt |
Q:
BDD in Google App Engine (Python)
I have seen some mention of some form of TDD for Python with Google App Engine, however I've not really seen a discussion of a BDD approach. Is someone familiar with how to string this together properly with GAE? I'm hopeful that things may be in a better position for this now than they were from notes and articles I saw from about a year ago.
A:
I did a little bit of development with GAE and the app engine.
BDD really is a development approach rather than a framework, so you can use any existing test tools. If you're happy switching to Ruby for your scenarios you can always use Cucumber with the Ruby-based web tool of your choice; otherwise you can use your unit-test framework and make yourself a little DSL (C# version of this just to show the principles of BDD DSLs is here). I honestly can't remember which approach we used, but Twill looks interesting.
For unit-level BDD, we used pytest. We wrapped the Google App Engine code in our own abstraction so that we could mock it out. That approach felt like overkill to start with, but started paying itself back very quickly; the BDD approach let us separate the descriptions of what we were doing from what the GAE was doing for us, which accelerated our learning and appreciation of the GAE as well as helping us understand what it didn't do. I can't remember whether pytest let us start the tests with "should"; we might have started them with "test_should".
Sorry this isn't more fleshed out. BDD is more to do with conversations and the mindset around the responsibilities of your code than it is to do with language and technology choices. I hope this encourages and helps you.
| BDD in Google App Engine (Python) | I have seen some mention of some form of TDD for Python with Google App Engine, however I've not really seen a discussion of a BDD approach. Is someone familiar with how to string this together properly with GAE? I'm hopeful that things may be in a better position for this now than they were from notes and articles I saw from about a year ago.
| [
"I did a little bit of development with GAE and the app engine.\nBDD really is a development approach rather than a framework, so you can use any existing test tools. If you're happy switching to Ruby for your scenarios you can always use Cucumber with the Ruby-based web tool of your choice; otherwise you can use y... | [
2
] | [] | [] | [
"bdd",
"google_app_engine",
"python",
"tdd"
] | stackoverflow_0003895239_bdd_google_app_engine_python_tdd.txt |
Q:
How do you generate a random double between these points?
37.807614 to 37.786996
The randomly generated double must have the same precision (num of digits) as those above.
For example, 37.792242 would be good, whereas 37.7823423425 would be bad.
A:
round(random.uniform(num1, num2), 6)
You will occasionally get numbers that end with ...0001 or ...9999 or so due to IEEE 754 inaccuracies though.
A:
Not sure if I'm missing something, but to avoid rounding, and since you want exactly that precision, isn't it easiest to work in integers and then convert to floating point by division? I.e.
offset = float(random.randint(0,20618))
num = (offset + 37786996.0) / 1000000.0
| How do you generate a random double between these points? | 37.807614 to 37.786996
The randomly generated double must have the same precision (num of digits) as those above.
For example, 37.792242 would be good, whereas 37.7823423425 would be bad.
| [
"round(random.uniform(num1, num2), 6)\n\nYou will occasionally get numbers that end with ...0001 or ...9999 or so due to IEEE 754 inaccuracies though.\n",
"Not sure if I'm missing something, but to avoid rounding, and since you want exactly that precision, isn't it easiest to work in integers and then convert to ... | [
5,
0
] | [] | [] | [
"double",
"int",
"python",
"types"
] | stackoverflow_0004050580_double_int_python_types.txt |
Q:
Script to convert Huge Three column table into table
I have a set of data (CSV files) in the following 3 column format:
A, B, C
3277,4733,54.1
3278,4741,51.0
3278,4750,28.4
3278,4768,36.0
3278,4776,50.1
3278,4784,51.4
3279,4792,82.6
3279,4806,78.2
3279,4814,36.4
And I need to get a three-way contingency table like: (sorry, this doesn't look completely good)
A /B 4733 4741 4750 4768 4776 4784 4792 4806 4814
3277 C 54.1
3278 51 28.4 36 50.1 51.4
3279 82.6 78.2 36.4
Similarly to an excel "pivot table", OpenOffice data pilot, or R "table(x,y,z)"
The problem is that my dataset is HUGE (more than 500,000 total rows, with about 400 different factors in A and B. (OOo, MSO and R limits prevent from achieving this)
I am sure a Python script could be used to create such a table. both A and B are numbers (but can be treated as strings).
Anyone has dealt with this?
(pseudocode or code in C or Java is also welcomed ... but I prefer python as it is faster to implement :)
Edit:
Almost have it, thanks to John Machin. The following Python script almost provides what I am looking for, however, when writing the output file I can see that the values in the "headers" I am writing (taken from the first row) do not correspond to the other rows.
from collections import defaultdict as dd
d = dd(lambda: dd(float))
input = open("input.txt")
output = open("output.txt","w")
while 1:
line = input.readline()
if not line:
break
line = line.strip('\n').strip('\r')
splitLine = line.split(',')
if (len(splitLine) <3):
break
d[splitLine[0]][splitLine[1]] = splitLine[2]
output.write("\t")
for k,v in d.items()[0][1].items():
output.write(str(k)+"\t")
output.write("\n")
for k,v in d.items():
output.write(k+"\t")
for k2,v2 in v.items():
output.write(str(v2)+"\t")
output.write("\n")
A:
When all you have is a hammer . . . . .
Conceptually, what you are trying to do is simple but because of the size of your data, it is computationally difficult. I tend to use R for it's analytic and graphics capacity, not it's data wrangling skills. When I need to move around a bunch of data, I usually just stick everything into a database.
Lately I have had quite a bit of success with SQLite and R. The best part is that you can actually use R to read in your data, which makes it easy to import large SPSS files or other sources of data that SQLite can't really handle but R can.
http://cran.r-project.org/web/packages/RSQLite/index.html
Here's my recommended work flow.
Import your data into R. (Done)
Library(RSQLite)
Move your data frame to SQLite.
Create Indexes on columns A and B.
Create a view that builds your table.
Query your view from R and coerce the returns into a table.
A:
In R I can do this:
N <- 1000000
x <- sample(1:400,N,TRUE)
y <- sample(1:400,N,TRUE)
z <- sample(1:400,N,TRUE)
w <- table(x,y,z)
And memory peak is lower then 800MB.
So what limitations you have?
EDIT. This peace of R-code:
N <- 1000000
mydata <- data.frame(
A=sample(runif(400),N,TRUE),
B=sample(runif(400),N,TRUE),
C=runif(N)
)
require(reshape)
results <- cast(mydata, A~B, value="C")
write.table(as.matrix(results),na="",sep="\t",file="results.txt")
create what you want with less then 300MB of RAM.
On my data it gives warning cause there are non-unique A-B combinations but for yours should be ok.
A:
Whole new story deserves a whole new answer.
Don't need defaultdict, don't even want defaultdict, because using it carelessly would suck memory like the Death Star's tractor beam.
This code is untested, may not even compile; I may have swapped rows and columns somewhere; fixes/explanations later ... must rush ...
d = {}
col_label_set = set()
row_label_set = set()
input = open("input.txt")
output = open("output.txt","w")
for line in input:
line = line.strip()
splat = line.split(',')
if len(splat) != 3:
break # error message???
k1, k2, v = splat
try:
subdict = d[k1]
except KeyError:
subdict = {}
d[k1] = subdict
subdict[k2] = v
row_label_set.add(k1)
col_label_set.add(k2)
col_labels = sorted(col_label_set)
row_labels = sorted(row_label_set
output.write("\t")
for v in col_labels::
output.write(v + "\t")
output.write("\n")
for r in row_labels:
output.write(r + "\t")
for c in col_labels:
output.write(d[r].get(c, "") + "\t")
output.write("\n")
Update Here's a fixed and refactored version, tested to the extent shown:
class SparseTable(object):
def __init__(self, iterable):
d = {}
col_label_set = set()
for row_label, col_label, value in iterable:
try:
subdict = d[row_label]
except KeyError:
subdict = {}
d[row_label] = subdict
subdict[col_label] = value
col_label_set.add(col_label)
self.d = d
self.col_label_set = col_label_set
def tabulate(self, row_writer, corner_label=u"", missing=u""):
d = self.d
col_labels = sorted(self.col_label_set)
row_labels = sorted(d.iterkeys())
orow = [corner_label] + col_labels
row_writer(orow)
for row_label in row_labels:
orow = [row_label]
subdict = d[row_label]
for col_label in col_labels:
orow.append(subdict.get(col_label, missing))
row_writer(orow)
if __name__ == "__main__":
import sys
test_data = u"""
3277,4733,54.1
3278,4741,51.0
3278,4750,28.4
3278,4768,36.0
3278,4776,50.1
3278,4784,51.4
3279,4792,82.6
3279,4806,78.2
3279,4814,36.4
""".splitlines(True)
def my_writer(row):
sys.stdout.write(u"\t".join(row))
sys.stdout.write(u"\n")
def my_reader(iterable):
for line in iterable:
line = line.strip()
if not line: continue
splat = line.split(u",")
if len(splat) != 3:
raise ValueError(u"expected 3 fields, found %d" % len(splat))
yield splat
table = SparseTable(my_reader(test_data))
table.tabulate(my_writer, u"A/B", u"....")
Here's the output:
A/B 4733 4741 4750 4768 4776 4784 4792 4806 4814
3277 54.1 .... .... .... .... .... .... .... ....
3278 .... 51.0 28.4 36.0 50.1 51.4 .... .... ....
3279 .... .... .... .... .... .... 82.6 78.2 36.4
A:
If you could use table(x,y,z) in R, then how about trying out the R out of memory packages that handle such huge data sets? Use the read.big.matrix function in the package bigmemory to read in the data set and the bigtable function in the package bigtabulate to create the table.
See vignettes.
A:
Your example of desired output doesn't look like a 3-way contingency table to me. That would be a mapping from (key1, key2, key3) to a count of occurences. Your example looks like a mapping from (key1, key2) to some number. You don't say what to do when (key1, key2) is duplicated: average, total, something else?
Assuming that you want a total, here's one memory-saving approach in Python, using nested defaultdicts:
>>> from collections import defaultdict as dd
>>> d = dd(lambda: dd(float))
>>> d[3277][4733] += 54.1
>>> d
defaultdict(<function <lambda> at 0x00D61DF0>, {3277: defaultdict(<type 'float'>, {4733: 54.1})})
>>> d[3278][4741] += 51.0
>>> d
defaultdict(<function <lambda> at 0x00D61DF0>, {3277: defaultdict(<type 'float'>, {4733: 54.1}), 3278: defaultdict(<type 'float'>, {4741: 51.0})})
>>>
and another approach using a single defaultdict with a composite key:
>>> d2 = dd(float)
>>> d2[3277,4733] += 54.1
>>> d2
defaultdict(<type 'float'>, {(3277, 4733): 54.1})
>>> d2[3278,4741] += 51.0
>>> d2
defaultdict(<type 'float'>, {(3277, 4733): 54.1, (3278, 4741): 51.0})
>>>
It might help if you were to say what you want to do with this data after you've got it grouped together ...
If you want (for example) an average, you have two options: (1) two data structures, one for total, one for count, then do "average = total - count" (2) sort your data on the first 2 columns, user itertools.groupby to collect your duplicates together, do your calculation, and add the results into your "average" data structure. Which of these approaches would use less memory is hard to tell; Python being Python you could try both rather quickly.
A:
A small subclasse of dict can provide you a confortable object to work with the table.
500.000 items should not be a problem on a desktop PC - if you happen to have 500.000.000 items, a similar class could map from the keys to positions in the file itself (that would be way more cool to implement :-) )
import csv
class ContingencyTable(dict):
def __init__(self):
self.a_keys=set()
self.b_keys=set()
dict.__init__(self)
def __setitem__(self, key,value):
self.a_keys.add(key[0])
self.b_keys.add(key[1])
dict.__setitem__(self, key, value)
def feed(self, file):
reader = csv.reader(file)
reader.next()
for a, b, c in reader:
self[int(a),int(b)] = float(c)
table = ContingencyTable()
table.feed(open("yourfile.csv"))
| Script to convert Huge Three column table into table | I have a set of data (CSV files) in the following 3 column format:
A, B, C
3277,4733,54.1
3278,4741,51.0
3278,4750,28.4
3278,4768,36.0
3278,4776,50.1
3278,4784,51.4
3279,4792,82.6
3279,4806,78.2
3279,4814,36.4
And I need to get a three-way contingency table like: (sorry, this doesn't look completely good)
A /B 4733 4741 4750 4768 4776 4784 4792 4806 4814
3277 C 54.1
3278 51 28.4 36 50.1 51.4
3279 82.6 78.2 36.4
Similarly to an excel "pivot table", OpenOffice data pilot, or R "table(x,y,z)"
The problem is that my dataset is HUGE (more than 500,000 total rows, with about 400 different factors in A and B. (OOo, MSO and R limits prevent from achieving this)
I am sure a Python script could be used to create such a table. both A and B are numbers (but can be treated as strings).
Anyone has dealt with this?
(pseudocode or code in C or Java is also welcomed ... but I prefer python as it is faster to implement :)
Edit:
Almost have it, thanks to John Machin. The following Python script almost provides what I am looking for, however, when writing the output file I can see that the values in the "headers" I am writing (taken from the first row) do not correspond to the other rows.
from collections import defaultdict as dd
d = dd(lambda: dd(float))
input = open("input.txt")
output = open("output.txt","w")
while 1:
line = input.readline()
if not line:
break
line = line.strip('\n').strip('\r')
splitLine = line.split(',')
if (len(splitLine) <3):
break
d[splitLine[0]][splitLine[1]] = splitLine[2]
output.write("\t")
for k,v in d.items()[0][1].items():
output.write(str(k)+"\t")
output.write("\n")
for k,v in d.items():
output.write(k+"\t")
for k2,v2 in v.items():
output.write(str(v2)+"\t")
output.write("\n")
| [
"When all you have is a hammer . . . . .\nConceptually, what you are trying to do is simple but because of the size of your data, it is computationally difficult. I tend to use R for it's analytic and graphics capacity, not it's data wrangling skills. When I need to move around a bunch of data, I usually just stick... | [
1,
1,
1,
0,
0,
0
] | [] | [] | [
"algorithm",
"import_from_csv",
"python",
"r",
"scripting"
] | stackoverflow_0004044353_algorithm_import_from_csv_python_r_scripting.txt |
Q:
Getting list of parameter names inside python function
Possible Duplicate:
Getting method parameter names in python
Is there an easy way to be inside a python function and get a list of the parameter names?
For example:
def func(a,b,c):
print magic_that_does_what_I_want()
>>> func()
['a','b','c']
Thanks
A:
Well we don't actually need inspect here.
>>> func = lambda x, y: (x, y)
>>>
>>> func.__code__.co_argcount
2
>>> func.__code__.co_varnames
('x', 'y')
>>>
>>> def func2(x,y=3):
... print(func2.__code__.co_varnames)
... pass # Other things
...
>>> func2(3,3)
('x', 'y')
>>>
>>> func2.__defaults__
(3,)
For Python 2.5 and older, use func_code instead of __code__, and func_defaults instead of __defaults__.
A:
locals() returns a dictionary with local names:
def func(a, b, c):
print(locals().keys())
prints the list of parameters. If you use other local variables those will be included in this list. But you could make a copy at the beginning of your function.
A:
If you also want the values you can use the inspect module
import inspect
def func(a, b, c):
frame = inspect.currentframe()
args, _, _, values = inspect.getargvalues(frame)
print 'function name "%s"' % inspect.getframeinfo(frame)[2]
for i in args:
print " %s = %s" % (i, values[i])
return [(i, values[i]) for i in args]
>>> func(1, 2, 3)
function name "func"
a = 1
b = 2
c = 3
[('a', 1), ('b', 2), ('c', 3)]
A:
import inspect
def func(a,b,c=5):
pass
inspect.getargspec(func) # inspect.signature(func) in Python 3
(['a', 'b', 'c'], None, None, (5,))
| Getting list of parameter names inside python function |
Possible Duplicate:
Getting method parameter names in python
Is there an easy way to be inside a python function and get a list of the parameter names?
For example:
def func(a,b,c):
print magic_that_does_what_I_want()
>>> func()
['a','b','c']
Thanks
| [
"Well we don't actually need inspect here.\n>>> func = lambda x, y: (x, y)\n>>> \n>>> func.__code__.co_argcount\n2\n>>> func.__code__.co_varnames\n('x', 'y')\n>>>\n>>> def func2(x,y=3):\n... print(func2.__code__.co_varnames)\n... pass # Other things\n... \n>>> func2(3,3)\n('x', 'y')\n>>> \n>>> func2.__defaults__\... | [
465,
278,
187,
145
] | [] | [] | [
"parameters",
"python"
] | stackoverflow_0000582056_parameters_python.txt |
Q:
Django Apps extendability - How to make your django apps easily extendable?
What are your best practises for making your django application easily extendable for other developers?
What are your approaches for enabling other to overwrite your
views
forms
templates
models
classes
In a way that enables a healthy environment for extensions to work well together?
A:
use signals and dispatchers
in your app create files..
-litseners.py
-signals.py
and then implement signals for your models and forms (views not so much)
use the django plugins pattern
ducktyping for your classes
A:
Basically, what he says. But class based views in Django 1.3 will change this pretty much. See Alex Gaynor's talk for an in-depth analysis of what class based views will bring to reusable apps.
| Django Apps extendability - How to make your django apps easily extendable? | What are your best practises for making your django application easily extendable for other developers?
What are your approaches for enabling other to overwrite your
views
forms
templates
models
classes
In a way that enables a healthy environment for extensions to work well together?
| [
"\nuse signals and dispatchers \n\nin your app create files..\n -litseners.py\n -signals.py\nand then implement signals for your models and forms (views not so much)\n\nuse the django plugins pattern\nducktyping for your classes \n\n",
"Basically, what he says. But class based views in Django ... | [
1,
0
] | [] | [] | [
"django",
"python"
] | stackoverflow_0004051010_django_python.txt |
Q:
print lists in a file in a special format in python
I have a large list of lists like:
X = [['a','b','c','d','e','f'],['c','f','r'],['r','h','l','m'],['v'],['g','j']]
each inner list is a sentence and the members of these lists are actually the word of this sentences.I want to write this list in a file such that each sentence(inner list) is in a separate line in the file, and each line has a number corresponding to the placement of this inner list(sentence) in the large this. In the case above. I want the output to look like this:
1. a b c d e f
2. c f r
3. r h l m
4.v
5.g j
I need them to be written in this format in a "text" file. Can anyone suggest me a code for it in python?
Thanks
A:
with open('somefile.txt', 'w') as fp:
for i, s in enumerate(X):
print >>fp, '%d. %s' % (i + 1, ' '.join(s))
A:
with open('file.txt', 'w') as f:
i=1
for row in X:
f.write('%d. %s'%(i, ' '.join(row)))
i+=1
| print lists in a file in a special format in python | I have a large list of lists like:
X = [['a','b','c','d','e','f'],['c','f','r'],['r','h','l','m'],['v'],['g','j']]
each inner list is a sentence and the members of these lists are actually the word of this sentences.I want to write this list in a file such that each sentence(inner list) is in a separate line in the file, and each line has a number corresponding to the placement of this inner list(sentence) in the large this. In the case above. I want the output to look like this:
1. a b c d e f
2. c f r
3. r h l m
4.v
5.g j
I need them to be written in this format in a "text" file. Can anyone suggest me a code for it in python?
Thanks
| [
"with open('somefile.txt', 'w') as fp:\n for i, s in enumerate(X):\n print >>fp, '%d. %s' % (i + 1, ' '.join(s))\n\n",
"with open('file.txt', 'w') as f:\n i=1\n for row in X:\n f.write('%d. %s'%(i, ' '.join(row)))\n i+=1\n\n"
] | [
5,
0
] | [] | [] | [
"file",
"list",
"nested_lists",
"python"
] | stackoverflow_0004051284_file_list_nested_lists_python.txt |
Q:
How do I set max_allowed_packet or equivalent for MySQLdb in python?
It seems as if MySQLdb is restricting the maximum transfer size for SQL statements. I have set the max_allowed_packet to 128M for mysqld. MySQL documentation says that this needs to be done for the client as well.
A:
You need to put max_allowed_packet into the [client] section of my.cnf on the machine where the client runs. If you want to, you can specify a different file or group in mysqldb.connect.
| How do I set max_allowed_packet or equivalent for MySQLdb in python? | It seems as if MySQLdb is restricting the maximum transfer size for SQL statements. I have set the max_allowed_packet to 128M for mysqld. MySQL documentation says that this needs to be done for the client as well.
| [
"You need to put max_allowed_packet into the [client] section of my.cnf on the machine where the client runs. If you want to, you can specify a different file or group in mysqldb.connect.\n"
] | [
1
] | [] | [] | [
"mysql",
"python"
] | stackoverflow_0004050257_mysql_python.txt |
Q:
help.....serial port programming
I want to communicate with my serial port in python. I installed pyserial, and uspp for linux. Still, when I run the following code:
import serial
ser = serial.Serial('/dev/pts/1', 19200, timeout=1)
print ser.portstr #check which port was really used
ser.write("hello") #write a string
ser.close() #
it gives the following error:
Traceback (most recent call last):
File "poi.py", line 5, in ser.open()
File "/usr/local/lib/python2.6/dist-packages/pyserial-2.5-py2.6.egg/serial/serialposix.py",
line 276,
in open raise SerialException("could not open port %s: %s" % (self._port, msg)) serial.serialutil.SerialException:
could not open port /dev/tyUSB1: [Errno 2] No such file or directory: '/dev/tyUSB1'
What should I do?
A:
/dev/tyUSB1 looks like a typo. Device nodes are normally called /dev/ttyXXX
A:
If you want to open your second USB serial port, you want /dev/ttyUSB1 instead of /dev/tyUSB1.
| help.....serial port programming | I want to communicate with my serial port in python. I installed pyserial, and uspp for linux. Still, when I run the following code:
import serial
ser = serial.Serial('/dev/pts/1', 19200, timeout=1)
print ser.portstr #check which port was really used
ser.write("hello") #write a string
ser.close() #
it gives the following error:
Traceback (most recent call last):
File "poi.py", line 5, in ser.open()
File "/usr/local/lib/python2.6/dist-packages/pyserial-2.5-py2.6.egg/serial/serialposix.py",
line 276,
in open raise SerialException("could not open port %s: %s" % (self._port, msg)) serial.serialutil.SerialException:
could not open port /dev/tyUSB1: [Errno 2] No such file or directory: '/dev/tyUSB1'
What should I do?
| [
"/dev/tyUSB1 looks like a typo. Device nodes are normally called /dev/ttyXXX\n",
"If you want to open your second USB serial port, you want /dev/ttyUSB1 instead of /dev/tyUSB1.\n"
] | [
7,
2
] | [] | [] | [
"linux",
"python",
"serial_port"
] | stackoverflow_0004051869_linux_python_serial_port.txt |
Q:
Split Python list into several lists based on index
So I've got a string of bytes which represents cubes in three dimensions. The coordinates are ordered like this:
[x0y0z0, x0y1z0, x0y2z0, ..., x0y127z0, x0y0z1, x0y1z1, ..., x15y127z15]
I'd like to split this into 128 lists, one for each Y coordinate. This code already does that, but I think inefficiently. Is there some way to split this list based on mod(128) of the index?
From the original code:
col.extend(izip_longest(*[iter(file["Level"]["Blocks"].value)]*128))
That takes quite a while, and I think it should be possible to make something better performing by avoiding the *128 part of this. But zipping is definitely not my strong side, and neither is binary file handling.
A:
# l = [x0y0z0, ...]
def bucketsofun(l, sp=16):
r = [[] for x in range(sp)]
for b, e in itertools.izip(itertools.cycle(r), l):
b.append(e)
return r
A:
Something like this might be worth trying
L = file["Level"]["Blocks"].value
col += [L[i::128] for i in range(127)]
A:
Itertools can do it too:
from itertools import izip, izip_longest, chain
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
# you have something like this
# [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
l = list(chain.from_iterable(range(5) for _ in range(5)))
# you want to put all the 0s, 1s (every 5th element) together
print list(izip(*grouper(5, l)))
# [(0, 0, 0, 0, 0), (1, 1, 1, 1, 1), ... , (4, 4, 4, 4, 4)]
| Split Python list into several lists based on index | So I've got a string of bytes which represents cubes in three dimensions. The coordinates are ordered like this:
[x0y0z0, x0y1z0, x0y2z0, ..., x0y127z0, x0y0z1, x0y1z1, ..., x15y127z15]
I'd like to split this into 128 lists, one for each Y coordinate. This code already does that, but I think inefficiently. Is there some way to split this list based on mod(128) of the index?
From the original code:
col.extend(izip_longest(*[iter(file["Level"]["Blocks"].value)]*128))
That takes quite a while, and I think it should be possible to make something better performing by avoiding the *128 part of this. But zipping is definitely not my strong side, and neither is binary file handling.
| [
"# l = [x0y0z0, ...]\ndef bucketsofun(l, sp=16):\n r = [[] for x in range(sp)]\n for b, e in itertools.izip(itertools.cycle(r), l):\n b.append(e)\n return r\n\n",
"Something like this might be worth trying\nL = file[\"Level\"][\"Blocks\"].value\ncol += [L[i::128] for i in range(127)]\n\n",
"Itertools can ... | [
3,
2,
0
] | [] | [] | [
"list",
"python"
] | stackoverflow_0004051042_list_python.txt |
Q:
Django creating object from POST
I have a question regarding Djanog views
here is a sample code
def example register ( request ) :
if request.method == ’POST ’ :
username = request.POST.get ( ’ username ’ )
password = request.POST.get ( ’ password ’ )
email = request.POST.get (’email’)
user = User.objects .create_user ( username
, email
, password )
user . save ()
return HttpResponseRedirect (
’/ example /login / ’)
In the above example we are taking the values one by one i.e username, password etc. If I have many such fields, then how can I do it in one single line, i was thinking to use dict's but can not find a way. Any help is appreciated. Thank you.
A:
you should be using forms[1] and model-forms [2] to collect such data from the request.
[1] http://docs.djangoproject.com/en/dev/topics/forms/
[2] http://docs.djangoproject.com/en/dev/topics/forms/modelforms/
A:
Why would you ever do it like that anyway?
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
and then handle it like that:
form = UserCreationForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
email = form.cleaned_data['email']
newuser = User.objects.create_user(username, email, password)
user = authenticate(username=username, password=password)
login (request, user)
return HttpResponseRedirect('/some/page/which/is/not/logginpage')#cause user is already logged in
Probably not the most elegenat way, but it should describe well enough, how to use form and then authenticate someone & log him in.
| Django creating object from POST | I have a question regarding Djanog views
here is a sample code
def example register ( request ) :
if request.method == ’POST ’ :
username = request.POST.get ( ’ username ’ )
password = request.POST.get ( ’ password ’ )
email = request.POST.get (’email’)
user = User.objects .create_user ( username
, email
, password )
user . save ()
return HttpResponseRedirect (
’/ example /login / ’)
In the above example we are taking the values one by one i.e username, password etc. If I have many such fields, then how can I do it in one single line, i was thinking to use dict's but can not find a way. Any help is appreciated. Thank you.
| [
"you should be using forms[1] and model-forms [2] to collect such data from the request.\n[1] http://docs.djangoproject.com/en/dev/topics/forms/\n[2] http://docs.djangoproject.com/en/dev/topics/forms/modelforms/\n",
"Why would you ever do it like that anyway? \nfrom django.contrib.auth.forms import UserCreationFo... | [
5,
0
] | [] | [] | [
"django",
"http",
"python"
] | stackoverflow_0004051873_django_http_python.txt |
Q:
Django / MySql not honouring unique_together
I am using django with mysql (InnoDB) and have the following in my django model:
class RowLock(models.Model):
table_name = models.CharField(blank = False, max_length = 30)
locked_row_id = models.IntegerField(null = False)
process_id = models.IntegerField(null = True)
thread_id = models.IntegerField(null = True)
class Meta:
db_table = "row_locks"
unique_together = (("table_name", "locked_row_id"),)
Running python manage.py sql app_name gives :
However within mysql client doing desc row_locks gives:
mysql> desc row_locks;
+---------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| table_name | varchar(30) | NO | | NULL | |
| locked_row_id | int(11) | NO | | NULL | |
| process_id | int(11) | YES | | NULL | |
| thread_id | int(11) | YES | | NULL | |
+---------------+-------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
Have also checked that I can enter duplicate rows with same values for table_name and locked_row_id without integrity error.
Now my assumption is that I am doing something wrong here because such an obvious thing could not be in the wild as a bug, but I can't see it,
Any fresh eyes would be appreciated
Rob
Update:
So as Dominic pointed out the problem was the south migration not creating the unique constraint. I could have looked at doing 2 migrations, one to create the table and then a subsequent one to add the unique_together - don't know if that would have worked or not - may try with more time.
In any case I got around it by manually editing the forward method in the south migration script as follows:
As generated by south:
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'RowLock'
db.create_table('row_locks', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('table_name', self.gf('django.db.models.fields.CharField')(max_length=30)),
('locked_row_id', self.gf('django.db.models.fields.IntegerField')()),
('process_id', self.gf('django.db.models.fields.IntegerField')(null=True)),
('thread_id', self.gf('django.db.models.fields.IntegerField')(null=True)),
))
db.send_create_signal('manager', ['RowLock'])
Manually edited:
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'RowLock'
db.create_table('row_locks', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('table_name', self.gf('django.db.models.fields.CharField')(max_length=30)),
('locked_row_id', self.gf('django.db.models.fields.IntegerField')()),
('process_id', self.gf('django.db.models.fields.IntegerField')(null=True)),
('thread_id', self.gf('django.db.models.fields.IntegerField')(null=True)),
))
db.create_index('row_locks', ['table_name','locked_row_id'], unique=True)
db.send_create_signal('manager', ['RowLock'])
A:
For completeness , my last update should have probably been added as an answer.
I fixed the problem by manually editing the forward method of the south migration and added the line:
db.create_index('row_locks', ['table_name','locked_row_id'], unique=True)
Rob
| Django / MySql not honouring unique_together | I am using django with mysql (InnoDB) and have the following in my django model:
class RowLock(models.Model):
table_name = models.CharField(blank = False, max_length = 30)
locked_row_id = models.IntegerField(null = False)
process_id = models.IntegerField(null = True)
thread_id = models.IntegerField(null = True)
class Meta:
db_table = "row_locks"
unique_together = (("table_name", "locked_row_id"),)
Running python manage.py sql app_name gives :
However within mysql client doing desc row_locks gives:
mysql> desc row_locks;
+---------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| table_name | varchar(30) | NO | | NULL | |
| locked_row_id | int(11) | NO | | NULL | |
| process_id | int(11) | YES | | NULL | |
| thread_id | int(11) | YES | | NULL | |
+---------------+-------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)
Have also checked that I can enter duplicate rows with same values for table_name and locked_row_id without integrity error.
Now my assumption is that I am doing something wrong here because such an obvious thing could not be in the wild as a bug, but I can't see it,
Any fresh eyes would be appreciated
Rob
Update:
So as Dominic pointed out the problem was the south migration not creating the unique constraint. I could have looked at doing 2 migrations, one to create the table and then a subsequent one to add the unique_together - don't know if that would have worked or not - may try with more time.
In any case I got around it by manually editing the forward method in the south migration script as follows:
As generated by south:
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'RowLock'
db.create_table('row_locks', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('table_name', self.gf('django.db.models.fields.CharField')(max_length=30)),
('locked_row_id', self.gf('django.db.models.fields.IntegerField')()),
('process_id', self.gf('django.db.models.fields.IntegerField')(null=True)),
('thread_id', self.gf('django.db.models.fields.IntegerField')(null=True)),
))
db.send_create_signal('manager', ['RowLock'])
Manually edited:
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'RowLock'
db.create_table('row_locks', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('table_name', self.gf('django.db.models.fields.CharField')(max_length=30)),
('locked_row_id', self.gf('django.db.models.fields.IntegerField')()),
('process_id', self.gf('django.db.models.fields.IntegerField')(null=True)),
('thread_id', self.gf('django.db.models.fields.IntegerField')(null=True)),
))
db.create_index('row_locks', ['table_name','locked_row_id'], unique=True)
db.send_create_signal('manager', ['RowLock'])
| [
"For completeness , my last update should have probably been added as an answer.\nI fixed the problem by manually editing the forward method of the south migration and added the line:\ndb.create_index('row_locks', ['table_name','locked_row_id'], unique=True)\n\nRob\n"
] | [
6
] | [] | [] | [
"django",
"mysql",
"python"
] | stackoverflow_0003916306_django_mysql_python.txt |
Q:
UnboundLocalError: local variable ... referenced before assignment
I get an UnboundLocalError because I use a template value inside an if statement which is not executed. What is the standard way to handle this situation?
class Test(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
greeting = ('Hello, ' + user.nickname())
else:
self.redirect(users.create_login_url(self.request.uri))
...
template_values = {"greeting": greeting,
}
Error:
UnboundLocalError: local variable 'greeting' referenced before assignment
A:
Just Switch:
class Test(webapp.RequestHandler):
def err_user_not_found(self):
self.redirect(users.create_login_url(self.request.uri))
def get(self):
user = users.get_current_user()
# error path
if not user:
self.err_user_not_found()
return
# happy path
greeting = ('Hello, ' + user.nickname())
...
template_values = {"greeting": greeting,}
A:
I guess I need to explain the problem first: in creating template_values, you use a greeting variable. This variable will not be set if there is no user.
There isn't a standard way to handle this situation. Common approaches are:
1. make sure that the variable is initialized in every code path (in your case: including the else case)
2. initialize the variable to some reasonable default value at the beginning
3. return from the function in the code paths which cannot provide a value for the variable.
Like Daniel, I suspect that after the redirect call, you are not supposed to produce any output, anyway, so the corrected code might read
class Test(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
greeting = ('Hello, ' + user.nickname())
else:
self.redirect(users.create_login_url(self.request.uri))
return
...
template_values = {"greeting": greeting,
}
| UnboundLocalError: local variable ... referenced before assignment | I get an UnboundLocalError because I use a template value inside an if statement which is not executed. What is the standard way to handle this situation?
class Test(webapp.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
greeting = ('Hello, ' + user.nickname())
else:
self.redirect(users.create_login_url(self.request.uri))
...
template_values = {"greeting": greeting,
}
Error:
UnboundLocalError: local variable 'greeting' referenced before assignment
| [
"Just Switch:\nclass Test(webapp.RequestHandler):\n def err_user_not_found(self):\n self.redirect(users.create_login_url(self.request.uri))\n def get(self): \n user = users.get_current_user()\n # error path\n if not user:\n self.err_user_not_found()\n ret... | [
3,
2
] | [] | [] | [
"error_handling",
"python"
] | stackoverflow_0004048745_error_handling_python.txt |
Q:
Auto-Completion In wxPython wxComboBox
I've been trying to make a ComboBox which would suggest options as you type, much like an IDE's code suggestions/code-sense, or googles suggestions when you type in a search.
The suggestions would be the items from the ComboBox dropdown, which contained the substring typed in the text box of the ComboBox.
I've tried to make a ComboBox do it, with no luck, I've tried the masked ComboBoxes, and have even tried to subclass the ComboCrtl, but I've always run into troubles either performance wise or not being able to do what I want at all
I have around 2500 items in my list of items (suggestions), and simply clearing the ComboBox and inserting the items which match is way too slow.
How would I go about making such a ComboBox, or is there even a built-in feature i could use?
I can allow a small delay before the suggestions are shown, but the whole window hanging for a second or two is not acceptable, in my oppinion.
A:
Few years ago I made a control like this by subclassing TextCtrl. It supports HTML formating for suggestions. Here you go.
There is also the Combo Box that Suggests Options
| Auto-Completion In wxPython wxComboBox | I've been trying to make a ComboBox which would suggest options as you type, much like an IDE's code suggestions/code-sense, or googles suggestions when you type in a search.
The suggestions would be the items from the ComboBox dropdown, which contained the substring typed in the text box of the ComboBox.
I've tried to make a ComboBox do it, with no luck, I've tried the masked ComboBoxes, and have even tried to subclass the ComboCrtl, but I've always run into troubles either performance wise or not being able to do what I want at all
I have around 2500 items in my list of items (suggestions), and simply clearing the ComboBox and inserting the items which match is way too slow.
How would I go about making such a ComboBox, or is there even a built-in feature i could use?
I can allow a small delay before the suggestions are shown, but the whole window hanging for a second or two is not acceptable, in my oppinion.
| [
"Few years ago I made a control like this by subclassing TextCtrl. It supports HTML formating for suggestions. Here you go.\nThere is also the Combo Box that Suggests Options\n"
] | [
10
] | [] | [] | [
"autocomplete",
"autosuggest",
"combobox",
"python",
"wxpython"
] | stackoverflow_0004051988_autocomplete_autosuggest_combobox_python_wxpython.txt |
Q:
Interpret 0x string as hex in Python
I'm appending some hex bytes into a packet = [] and I want to return these hex bytes in the form of 0x__ as hex data.
packet.append("2a")
packet.append("19")
packet.append("00")
packet.append("00")
packHex = []
for i in packet:
packHex.append("0x"+i) #this is wrong
return packHex
How do I go about converting ('2a', '19', '00', '00') in packet to get (0x2a, 0x19, 0x0, 0x0) in packHex? I need real hex data, not strings that look like hex data.
I'm assembling a packet to be sent over pcap, pcap_sendpacket(fp,packet,len(data)) where packet should be a hexadecimal list or tuple for me, maybe it can be done in decimal, haven't tried, I prefer hex. Thank you for your answer.
packetPcap[:len(data)] = packHex
Solved:
for i in packet: packHex.append(int(i,16))
If output in hex needed, this command can be used:
print ",".join(map(hex, packHex))
A:
You don't really want 'hex data', you want integers. Hexadecimal notation only makes sense when you have numbers represented as strings.
To solve your problem use a list comprehension:
[int(x, 16) for x in packet]
Or to get the result as a tuple:
tuple(int(x, 16) for x in packet)
A:
Why don't you just build a list of ints and just print them out in base 16 (either by using "%x"%value or hex) instead? If the values are given to you in this form (e.g. from some other source), you can use int with the optional second parameter to turn this into an int.
>>> int('0x'+'2a',16)
42
>>> packet=["2a","19","00","00"]
>>> packet=[int(p,16) for p in packet]
>>> packet
[42, 25, 0, 0]
>>> print ", ".join(map(hex,packet))
0x2a, 0x19, 0x0, 0x0
| Interpret 0x string as hex in Python | I'm appending some hex bytes into a packet = [] and I want to return these hex bytes in the form of 0x__ as hex data.
packet.append("2a")
packet.append("19")
packet.append("00")
packet.append("00")
packHex = []
for i in packet:
packHex.append("0x"+i) #this is wrong
return packHex
How do I go about converting ('2a', '19', '00', '00') in packet to get (0x2a, 0x19, 0x0, 0x0) in packHex? I need real hex data, not strings that look like hex data.
I'm assembling a packet to be sent over pcap, pcap_sendpacket(fp,packet,len(data)) where packet should be a hexadecimal list or tuple for me, maybe it can be done in decimal, haven't tried, I prefer hex. Thank you for your answer.
packetPcap[:len(data)] = packHex
Solved:
for i in packet: packHex.append(int(i,16))
If output in hex needed, this command can be used:
print ",".join(map(hex, packHex))
| [
"You don't really want 'hex data', you want integers. Hexadecimal notation only makes sense when you have numbers represented as strings.\nTo solve your problem use a list comprehension:\n[int(x, 16) for x in packet]\n\nOr to get the result as a tuple:\ntuple(int(x, 16) for x in packet)\n\n",
"Why don't you just ... | [
5,
4
] | [] | [] | [
"casting",
"python",
"types"
] | stackoverflow_0004052298_casting_python_types.txt |
Q:
How to automatically move specific MySQL tables from one machine to another?
I have a MySQL database with tables in the form of "shard_0", "shard_1", "shard_2", etc.
These are virtual shards. Now I want to add another DB server and move the even-numbered shards ("shard_0", "shard_2", "shard_4", ...) to the new machine.
What is the best way to do that? There are many tables so ideally I wouldn't have to type out each table name individually but do something automatically. Perhaps something like:
# pseudo code
for i in range(n):
tablename = "shard_"+str(2*i)
# Move tablename to new machine
Thanks
A:
I'd create a single (or perhaps multiple) mysqldump invocations, like so
print "mysqldump database",
for i in range(n):
print "shard_"+str(2*i),
Run this command in a shell, and move the dump file to the new machine, then run it there through mysql.
Then generate and run the "drop table" statements for the tables you have moved.
A:
I'm not sure I see the problem, but if I got it right, you can use Python to generate the export SQL script, and the import one for the other machine.
That'll save you the trouble of doing it manually. As for your code snippet, I think the best way to go about migrating a database from a server to another one is using the engine's own capabilities.
| How to automatically move specific MySQL tables from one machine to another? | I have a MySQL database with tables in the form of "shard_0", "shard_1", "shard_2", etc.
These are virtual shards. Now I want to add another DB server and move the even-numbered shards ("shard_0", "shard_2", "shard_4", ...) to the new machine.
What is the best way to do that? There are many tables so ideally I wouldn't have to type out each table name individually but do something automatically. Perhaps something like:
# pseudo code
for i in range(n):
tablename = "shard_"+str(2*i)
# Move tablename to new machine
Thanks
| [
"I'd create a single (or perhaps multiple) mysqldump invocations, like so\nprint \"mysqldump database\",\nfor i in range(n):\n print \"shard_\"+str(2*i),\n\nRun this command in a shell, and move the dump file to the new machine, then run it there through mysql.\nThen generate and run the \"drop table\" statement... | [
2,
0
] | [] | [] | [
"database",
"mysql",
"python",
"sharding"
] | stackoverflow_0004048728_database_mysql_python_sharding.txt |
Q:
How to profile combined python and c code
I have an application that consists of multiple python scripts. Some of these scripts are calling C code. The application is now running much slower than it was, so I would like to profile it to see where the problem lies. Is there a tool, software package or just a way to profile such an application? A tool that will follow the python code into the C code and profile these calls as well?
Note 1: I am well aware of the standard Python profiling tools. I'm specifically looking here for combined Python/C profiling.
Note 2: the Python modules are calling C code using ctypes (see http://docs.python.org/library/ctypes.html for details).
Thanks!
A:
Stackshots work. Since you have combined Python and C you can handle them separately. For Python, you can hit Ctrl-C while it's being slow to examine the stack. Do this several times. That will expose anything you can fix in the python code. For the C code, run the whole thing under a debugger like GDB and hit Ctrl-C to get a stack trace in C. Several of those will expose anything you can fix in the C code. I'm told OProfile can also do this. (Another way is to use lsstack if it is available.)
This is a little-known method that works on this principle: Suppose you have an infinite loop or a nearly infinite loop. How would you find it? You would halt the program and see what it was doing, right? Suppose the program only took twice as long as necessary. Each time you halted it, the chance that you would catch it doing the unnecessary thing is 50%. So all you have to do is halt it a number of times. As soon as you see it doing something that could be improved, on as few as 2 samples, you know you can fix that for a healthy speedup. Then you can repeat it to get the next problem. Measuring is not the point. Catching things you can improve is the point.
A:
The combination would be pretty hard, but you can use some of the standard profilers like valgrind, gprof or even oprofile (although I never managed to get meaningful output out of it).
| How to profile combined python and c code | I have an application that consists of multiple python scripts. Some of these scripts are calling C code. The application is now running much slower than it was, so I would like to profile it to see where the problem lies. Is there a tool, software package or just a way to profile such an application? A tool that will follow the python code into the C code and profile these calls as well?
Note 1: I am well aware of the standard Python profiling tools. I'm specifically looking here for combined Python/C profiling.
Note 2: the Python modules are calling C code using ctypes (see http://docs.python.org/library/ctypes.html for details).
Thanks!
| [
"Stackshots work. Since you have combined Python and C you can handle them separately. For Python, you can hit Ctrl-C while it's being slow to examine the stack. Do this several times. That will expose anything you can fix in the python code. For the C code, run the whole thing under a debugger like GDB and hit Ctr... | [
3,
1
] | [] | [] | [
"c",
"profiling",
"python"
] | stackoverflow_0004051117_c_profiling_python.txt |
Q:
A SuggestBox for wxPython?
Is there a widget for wxPython like the SuggestBox in Google Web Toolkit? It is basically a magic text box that can invoke some code to come up with suggestions relevant to whatever the user has entered so far. Like the search box on Google's web page.
If such a widget isn't already floating out there, I'd appreciate a sketch of how I might implement it with the existing widgets.
A:
You might want to look at Combo Box that Suggests Options.
I hope this is what you were thinking of.
A:
Few years ago I made a control like this by subclassing TextCtrl. It supports HTML formating for suggestions. Here you go.
| A SuggestBox for wxPython? | Is there a widget for wxPython like the SuggestBox in Google Web Toolkit? It is basically a magic text box that can invoke some code to come up with suggestions relevant to whatever the user has entered so far. Like the search box on Google's web page.
If such a widget isn't already floating out there, I'd appreciate a sketch of how I might implement it with the existing widgets.
| [
"You might want to look at Combo Box that Suggests Options.\nI hope this is what you were thinking of.\n",
"Few years ago I made a control like this by subclassing TextCtrl. It supports HTML formating for suggestions. Here you go.\n"
] | [
4,
1
] | [] | [] | [
"python",
"search",
"suggestbox",
"wxpython"
] | stackoverflow_0000452520_python_search_suggestbox_wxpython.txt |
Q:
Failure loading py2exe'd program when including pysvn
I am attempting to run a py2exe'd program (package.py) that includes pysvn. It is failing to run with the following error:
Traceback (most recent call last):
File "package.py", line 27, in <module>
File "zipextimporter.pyc", line 82, in load_module
File "pysvn\__init__.pyc", line 99, in <module>
File "zipextimporter.pyc", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading pysvn\_pysvn_2_6.pyd
The script runs fine for others in the office, the difference being I'm on Windows 7 x64 with them on WinXP x86. I do have _pysvn_2_6.pyd in my pysvn directory.
Py2exe's "Problems to be Fixed" page has a similar error message with WxPython where it cannot find a needed system module, but I am not using WxPython and I have the dll they refer to anyway.
The py2exe page for "Working with Various Packages and Modules" doesn't refer to pysvn, and I can't find anyone else with similar problems.
I've checked the output of py2exe as outlined by this answer, but my computer seems to have all the binary files required in the correct locations.
EDIT:
I just tried to run other py2exe created programs on this same machine and they failed as well. It seems that the problem is with my machine (ie x64) rather than the specific program I was converting; I get a similar error with another program:
Traceback (most recent call last):
File "rundemo.py", line 13, in <module>
import win32api as w32
File "zipextimporter.pyc", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading win32api.pyd
EDIT2:
I tried the py2exe programs generated from my 64 bit compy on a 32 bit machine, and they failed with the same error. I think I'm generating 32 bit exe's (py2exe docs say 64-bit support is experimental, and I haven't explicitly turned it on), but I'm not sure how to check to be sure.
A:
Install PyWin32.
A:
The py2exe project seems dead, so we rewrote our exes in C++. We can still build for Win7 x64 on our machines, but we couldn't get exe's wrote on Win7 to run on anything older.
| Failure loading py2exe'd program when including pysvn | I am attempting to run a py2exe'd program (package.py) that includes pysvn. It is failing to run with the following error:
Traceback (most recent call last):
File "package.py", line 27, in <module>
File "zipextimporter.pyc", line 82, in load_module
File "pysvn\__init__.pyc", line 99, in <module>
File "zipextimporter.pyc", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading pysvn\_pysvn_2_6.pyd
The script runs fine for others in the office, the difference being I'm on Windows 7 x64 with them on WinXP x86. I do have _pysvn_2_6.pyd in my pysvn directory.
Py2exe's "Problems to be Fixed" page has a similar error message with WxPython where it cannot find a needed system module, but I am not using WxPython and I have the dll they refer to anyway.
The py2exe page for "Working with Various Packages and Modules" doesn't refer to pysvn, and I can't find anyone else with similar problems.
I've checked the output of py2exe as outlined by this answer, but my computer seems to have all the binary files required in the correct locations.
EDIT:
I just tried to run other py2exe created programs on this same machine and they failed as well. It seems that the problem is with my machine (ie x64) rather than the specific program I was converting; I get a similar error with another program:
Traceback (most recent call last):
File "rundemo.py", line 13, in <module>
import win32api as w32
File "zipextimporter.pyc", line 98, in load_module
ImportError: MemoryLoadLibrary failed loading win32api.pyd
EDIT2:
I tried the py2exe programs generated from my 64 bit compy on a 32 bit machine, and they failed with the same error. I think I'm generating 32 bit exe's (py2exe docs say 64-bit support is experimental, and I haven't explicitly turned it on), but I'm not sure how to check to be sure.
| [
"Install PyWin32.\n",
"The py2exe project seems dead, so we rewrote our exes in C++. We can still build for Win7 x64 on our machines, but we couldn't get exe's wrote on Win7 to run on anything older.\n"
] | [
0,
0
] | [] | [] | [
"py2exe",
"pysvn",
"python"
] | stackoverflow_0003189530_py2exe_pysvn_python.txt |
Q:
Convert xml to pdf in Python
I have a problem when I try to convert a XML file in a PDF file, here I’m going to explain briefly how I try to generate a PDF file.
We suppose I get the information from a database, then the code source is the following:
import pyodbc,time,os,shutil,types
import cStringIO
import ho.pisa as pisa
import urllib
def HTML2PDF(data, filename, open=False):
"""
Simple test showing how to create a PDF file from
PML Source String. Also shows errors and tries to start
the resulting PDF
"""
pdf = pisa.CreatePDF(
cStringIO.StringIO(data),
file(filename, "wb"))
if open and (not pdf.err):
os.startfile(str(filename))
return not pdf.err
fout = open(BE_Full.xml","w")
fout.write("<?xml-stylesheet type='text/xsl' href='styles/Full_Report.xslt' alternate='no' title='Short' ?>")
fout.write("<files>")
fout.write("<validationreport>")
fout.write("xmlvalidations/" + row.country + "_validation_" + row.dbversion + ".xml")
fout.write("</validationreport>")
fout.write("<reportformat>reports/EN_Report.xml</reportformat>")
fout.write("</files>")
fout.write
fout.close()
f = urllib.urlopen("file:///C:/Documents%20and%20Settings/dmarban/Escritorio/python/BE_Full.xml")
s = f.read()
f.close()
HTML2PDF(s, "test.pdf", open=True)
The first I generate is an XML file that has the following content:
<?xml-stylesheet type='text/xsl' href='styles/Full_Report.xslt' alternate='no' title='Short' ?>
<files>
<validationreport>xmlvalidations/BE_validation_mid2010.xml</validationreport>
<reportformat>reports/EN_Report.xml</reportformat>
</files>
When I execute this code:
urllib.urlopen("file:///C:/Documents%20and%20Settings/dmarban/Escritorio/python/BE_Full.xml")
s = f.read()
f.close()
HTML2PDF(s, " BE_Full.pdf ", open=True)
It generates me the next file “BE_Full.pdf”, but instead of showing the contents of the folder “xmlvalidations/BE_validation_mid2010.xml” show me the contents of the labels that they are in pdf, It would show the following code:
xmlvalidations/BE_validation_mid2010.xml reports/EN_Report.xml
My question is, How I can parser a XML file in python, I read it as an HTML file?
A:
I'm not sure I understand the question fully, but are you expecting pisa to apply the xslt transformation? I don't think it will do that (you might want to look at lxml and use that to apply the xslt before converting to pdf with pisa)
| Convert xml to pdf in Python | I have a problem when I try to convert a XML file in a PDF file, here I’m going to explain briefly how I try to generate a PDF file.
We suppose I get the information from a database, then the code source is the following:
import pyodbc,time,os,shutil,types
import cStringIO
import ho.pisa as pisa
import urllib
def HTML2PDF(data, filename, open=False):
"""
Simple test showing how to create a PDF file from
PML Source String. Also shows errors and tries to start
the resulting PDF
"""
pdf = pisa.CreatePDF(
cStringIO.StringIO(data),
file(filename, "wb"))
if open and (not pdf.err):
os.startfile(str(filename))
return not pdf.err
fout = open(BE_Full.xml","w")
fout.write("<?xml-stylesheet type='text/xsl' href='styles/Full_Report.xslt' alternate='no' title='Short' ?>")
fout.write("<files>")
fout.write("<validationreport>")
fout.write("xmlvalidations/" + row.country + "_validation_" + row.dbversion + ".xml")
fout.write("</validationreport>")
fout.write("<reportformat>reports/EN_Report.xml</reportformat>")
fout.write("</files>")
fout.write
fout.close()
f = urllib.urlopen("file:///C:/Documents%20and%20Settings/dmarban/Escritorio/python/BE_Full.xml")
s = f.read()
f.close()
HTML2PDF(s, "test.pdf", open=True)
The first I generate is an XML file that has the following content:
<?xml-stylesheet type='text/xsl' href='styles/Full_Report.xslt' alternate='no' title='Short' ?>
<files>
<validationreport>xmlvalidations/BE_validation_mid2010.xml</validationreport>
<reportformat>reports/EN_Report.xml</reportformat>
</files>
When I execute this code:
urllib.urlopen("file:///C:/Documents%20and%20Settings/dmarban/Escritorio/python/BE_Full.xml")
s = f.read()
f.close()
HTML2PDF(s, " BE_Full.pdf ", open=True)
It generates me the next file “BE_Full.pdf”, but instead of showing the contents of the folder “xmlvalidations/BE_validation_mid2010.xml” show me the contents of the labels that they are in pdf, It would show the following code:
xmlvalidations/BE_validation_mid2010.xml reports/EN_Report.xml
My question is, How I can parser a XML file in python, I read it as an HTML file?
| [
"I'm not sure I understand the question fully, but are you expecting pisa to apply the xslt transformation? I don't think it will do that (you might want to look at lxml and use that to apply the xslt before converting to pdf with pisa)\n"
] | [
1
] | [] | [] | [
"python"
] | stackoverflow_0004043760_python.txt |
Q:
Performing unbiased program/script performance comparison
I want to perform a comparison of multiple implementations of basically the same algorithm, written in Java, C++ and Python, the latter executed using Pypy, Jython and CPython on a Mac OS X 10.6.4 Macbook Pro with normal (non-SSD) HDD.
It's a "decode a stream of data from a file" type of algorithm, where the relevant measurement is total execution time, and I want to prevent bias through e.g. OS an HDD caches, other programs running simultaneously, too large/small sample file etc. What do I need to pay attention to to create a fair comparison?
A:
These are difficult to do well.
In many cases the operating system will cache files so the second time they are executed they suddenly perform much better.
The other problem is you're comparing interpreted languages against compiled. The interpreted languages require an interpreter loaded into memory somewhere or they can't run. To be scrupulously fair you really should consider if memory usage and load time for the interpreter should be part of the test. If you're looking for performance in an environment where you can assume the interpreter is always preloaded then you can ignore that. Many setups for web servers will be able to keep an interpreter preloaded. If you're doing ad hoc client applications on a desktop then the start up can be very slow while the interpreter is loaded.
A:
To prevent bias I would recommend first stopping all unnecessary processes from running in the background.
I'm not sure about windows, but under linux you can clear the HDD cache via drop_caches
Information on how to use it here
Additionally you may want to take an average for several runs of the application, that way any HDD or OS interference won't skew the results.
A:
I would recommend that you simply run each program many times (like 20 or so) and take the lowest measurement of each set. This will make it so it is highly likely that the program will use the HD cache and other things like that. If they all do that, then it isn't biased.
A:
To get totally unbiased is impossible, you can do various stuff like running minimum processes etc but IMO best way is to run scripts in random order over a long period of time over different days and get average which will be as near to unbias as possible.
Because ultimately code will run in such environment in random order and you are interested in average behavior not some numbers.
| Performing unbiased program/script performance comparison | I want to perform a comparison of multiple implementations of basically the same algorithm, written in Java, C++ and Python, the latter executed using Pypy, Jython and CPython on a Mac OS X 10.6.4 Macbook Pro with normal (non-SSD) HDD.
It's a "decode a stream of data from a file" type of algorithm, where the relevant measurement is total execution time, and I want to prevent bias through e.g. OS an HDD caches, other programs running simultaneously, too large/small sample file etc. What do I need to pay attention to to create a fair comparison?
| [
"These are difficult to do well.\nIn many cases the operating system will cache files so the second time they are executed they suddenly perform much better.\nThe other problem is you're comparing interpreted languages against compiled. The interpreted languages require an interpreter loaded into memory somewhere o... | [
1,
0,
0,
0
] | [] | [] | [
"c++",
"java",
"jython",
"performance",
"python"
] | stackoverflow_0004052691_c++_java_jython_performance_python.txt |
Q:
How come a document in MongoDB sometimes gets inserted , but most often don't?
con = pymongo.Connection('localhost',27017)
db = con.MouseDB
post = { ...some stuff }
datasets = db.datasets
datasets.insert(post)
So far, there are only 3 records, and it's supposed to have about 100...
A:
Did you check to make sure that you don't have collisions on your primary keys. Take a look at the console and it should tell you why a document is not inserting. I'd also recommend trying to insert one at a time from the command line tool to get better information as to why it may not be inserting correctly. If you want to update, make sure to use save instead of insert (which performs an upsert)
| How come a document in MongoDB sometimes gets inserted , but most often don't? | con = pymongo.Connection('localhost',27017)
db = con.MouseDB
post = { ...some stuff }
datasets = db.datasets
datasets.insert(post)
So far, there are only 3 records, and it's supposed to have about 100...
| [
"Did you check to make sure that you don't have collisions on your primary keys. Take a look at the console and it should tell you why a document is not inserting. I'd also recommend trying to insert one at a time from the command line tool to get better information as to why it may not be inserting correctly. I... | [
0
] | [] | [] | [
"database",
"mongodb",
"nosql",
"python"
] | stackoverflow_0004050989_database_mongodb_nosql_python.txt |
Q:
How can I do this complex SQL query using Django ORM? (sub-query with a join)
I'm used to writing my own SQL queries and I'm trying to get used to the whole ORM thing that seems to be so popular nowadays.
Here's the query:
SELECT * FROM routes WHERE route_id IN (
SELECT DISTINCT t.route_id FROM stop_times AS st
LEFT JOIN trips AS t ON st.trip_id=t.trip_id
WHERE stop_id = %s
)
where %s is an integer.
I'm using Django's default ORM. What's the most pythonic way to do this?
Some background info: The DB I'm using is from a GTFS (Google Transit feed specification). This query is supposed to get a list of every route that goes through a particular stop, however the info linking these is in the trips table.
This query works just fine for me, so the only reason I'm asking is to learn.
Thanks!
A:
Correct me if I'm wrong, but I don't think you can do that with Django ORM in a normal way.
There is no subquery support and with a normal join it would depend on your database if a distinct could help you. If you are using Postgres than you could do it with this patch: http://code.djangoproject.com/ticket/6422
The query would be something like this:
Route.objects.filter(stop_time__trips__stop_id=...).distinct('stop_time__route_id')
A:
It'd probably be a bit easier to figure out the appropriate way to do this if you had what you were using for the relevant Models.
I'm assuming something like the following, based on the specification you mentioned working from:
class Route(models.Model):
#bunch of stuff
pass
class Stop(models.Model):
#bunch of stuff
stop_times = models.ManyToManyField(through=StopTime)
class StopTime(models.Model):
trip = models.ForeignKey(Trip)
stop = models.ForeignKey(Stop)
# bunch of additional meta about this M2M table
pass
class Trip(models.Model):
route = models.ForeignKey(Route)
# bunch of stuff
If that's the case... you should be able to do something like
Route.objects.filter(trip__stop__id=my_stop_id)
to get all Route objects that go through a given Stop with a primary key id equal to my_stop_id, which I'm assuming is an integer as per your post.
I apologize if the syntax is a bit off, as I haven't needed to do many-to-many relationships using an explicit extra table. Some adjustment may also be needed if you have to (or choose to) use the related_name parameter for any the foreign keys or the many-to-many-field.
| How can I do this complex SQL query using Django ORM? (sub-query with a join) | I'm used to writing my own SQL queries and I'm trying to get used to the whole ORM thing that seems to be so popular nowadays.
Here's the query:
SELECT * FROM routes WHERE route_id IN (
SELECT DISTINCT t.route_id FROM stop_times AS st
LEFT JOIN trips AS t ON st.trip_id=t.trip_id
WHERE stop_id = %s
)
where %s is an integer.
I'm using Django's default ORM. What's the most pythonic way to do this?
Some background info: The DB I'm using is from a GTFS (Google Transit feed specification). This query is supposed to get a list of every route that goes through a particular stop, however the info linking these is in the trips table.
This query works just fine for me, so the only reason I'm asking is to learn.
Thanks!
| [
"Correct me if I'm wrong, but I don't think you can do that with Django ORM in a normal way.\nThere is no subquery support and with a normal join it would depend on your database if a distinct could help you. If you are using Postgres than you could do it with this patch: http://code.djangoproject.com/ticket/6422\n... | [
1,
1
] | [] | [] | [
"django",
"gtfs",
"orm",
"python",
"sql"
] | stackoverflow_0004039711_django_gtfs_orm_python_sql.txt |
Q:
Return a range of elements of each list inside a list of lists
From a list mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] how can I get a new list of lists composed of the first two elements of each "inside" list e.i. newlist = [[1, 2], [4, 5], [7, 8]]? Is there a one-liner that can do this efficiently (for large lists of lists)?
A:
The easiest way is probably to use a list comprehension:
newlist = [sublist[:2] for sublist in mylist]
A:
Quick answer:
first_two = [sublist[:2] for sublist in mylist]
If having a list of tuples is ok, then a faster answer (2x by my measurements):
import operator
map(operator.itemgetter(0, 1), mylist)
Measurements:
t = timeit.Timer("[i[:2] for i in ll]", "ll = [[i, i + 1, i + 2] for i in xrange(1000)]")
t.timeit(10000)
>>> 2.2732808589935303
t2 = timeit.Timer("map(operator.itemgetter(0, 1), ll)", "import operator; ll = [[i, i + 1, i + 2] for i in xrange(1000)]")
t2.timeit(10000)
>>> 1.3041009902954102
A:
Use list comprehension.
newlist = [x[:2] for x in mylist]
| Return a range of elements of each list inside a list of lists | From a list mylist = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] how can I get a new list of lists composed of the first two elements of each "inside" list e.i. newlist = [[1, 2], [4, 5], [7, 8]]? Is there a one-liner that can do this efficiently (for large lists of lists)?
| [
"The easiest way is probably to use a list comprehension:\nnewlist = [sublist[:2] for sublist in mylist]\n\n",
"Quick answer:\nfirst_two = [sublist[:2] for sublist in mylist]\n\nIf having a list of tuples is ok, then a faster answer (2x by my measurements):\nimport operator\nmap(operator.itemgetter(0, 1), mylist)... | [
7,
3,
1
] | [] | [] | [
"list_comprehension",
"python"
] | stackoverflow_0004053594_list_comprehension_python.txt |
Q:
How to call Wine dll from python on Linux?
I'm writing a python script in Linux, and need to call some Windows functions available in Wine. Specifically, AllocateAndInitializeSid and LookupAccountSidW, to determine who is logged in to a remote Windows computer. These functions are part of advapi32.dll in Wine (edit: using the answers, I was able to call the function, but LookupAccountSidW only works on the local computer).
How can I access these functions, or a Wine dll in general? I've tried
>>> cdll.LoadLibrary("~/.wine/drive_c/windows/system32/advapi32.dll")
but it results in an error:
OSError: ~/.wine/drive_c/windows/system32/advapi32.dll: invalid ELF header
Is there another ctypes function that would work, or some wine interface I could use?
A:
Doesn't Wine provide *.so versions of the dlls? I seem to have /usr/lib32/wine/advapi32.dll.so, for example.
If you're on a 64-bit machine, keep in mind that you'll need a 32-bit version of Python to load 32-bit libraries.
A:
Understand that .DLL is the format used by Windows.
On linux, such libraries end with .SO
You can't use a library compiled for one platform on the other one. It's not compatible.
| How to call Wine dll from python on Linux? | I'm writing a python script in Linux, and need to call some Windows functions available in Wine. Specifically, AllocateAndInitializeSid and LookupAccountSidW, to determine who is logged in to a remote Windows computer. These functions are part of advapi32.dll in Wine (edit: using the answers, I was able to call the function, but LookupAccountSidW only works on the local computer).
How can I access these functions, or a Wine dll in general? I've tried
>>> cdll.LoadLibrary("~/.wine/drive_c/windows/system32/advapi32.dll")
but it results in an error:
OSError: ~/.wine/drive_c/windows/system32/advapi32.dll: invalid ELF header
Is there another ctypes function that would work, or some wine interface I could use?
| [
"Doesn't Wine provide *.so versions of the dlls? I seem to have /usr/lib32/wine/advapi32.dll.so, for example. \nIf you're on a 64-bit machine, keep in mind that you'll need a 32-bit version of Python to load 32-bit libraries.\n",
"Understand that .DLL is the format used by Windows. \nOn linux, such libraries end ... | [
7,
0
] | [] | [] | [
"dll",
"linux",
"python",
"wine"
] | stackoverflow_0004052690_dll_linux_python_wine.txt |
Q:
Open file in universal-newline mode when using pkg_resources?
I am processing a CSV file and have the following working code:
reader = csv.reader(open(filename, 'rU'), dialect='excel')
header = reader.next()
However, to be compatible with elsewhere in the codebase, I need to use a file object using pkg_resources.resource_stream, as follows:
fileobj = pkg_resources.resource_stream('foo', 'tests/bar.csv')
reader = csv.reader(fileobj, dialect='excel')
header = reader.next()
(I'm simplifying here - basically the csv.reader code is in a function over which I don't have control, and it expects a fileobj.)
This throws the following error.
Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
Any idea how I can use universal-newline mode with my fileobj? I can't see anything about this in the pkg_resources documentation.
Thanks.
A:
If the stream always has an fd (e.g. because it's a normal opened file on the filesystem), you can use os.fdopen(fileobj.fileno(), 'rU') to open it with the right mode.
| Open file in universal-newline mode when using pkg_resources? | I am processing a CSV file and have the following working code:
reader = csv.reader(open(filename, 'rU'), dialect='excel')
header = reader.next()
However, to be compatible with elsewhere in the codebase, I need to use a file object using pkg_resources.resource_stream, as follows:
fileobj = pkg_resources.resource_stream('foo', 'tests/bar.csv')
reader = csv.reader(fileobj, dialect='excel')
header = reader.next()
(I'm simplifying here - basically the csv.reader code is in a function over which I don't have control, and it expects a fileobj.)
This throws the following error.
Error: new-line character seen in unquoted field - do you need to open the file in universal-newline mode?
Any idea how I can use universal-newline mode with my fileobj? I can't see anything about this in the pkg_resources documentation.
Thanks.
| [
"If the stream always has an fd (e.g. because it's a normal opened file on the filesystem), you can use os.fdopen(fileobj.fileno(), 'rU') to open it with the right mode.\n"
] | [
6
] | [] | [] | [
"csv",
"pkg_resources",
"python"
] | stackoverflow_0004052489_csv_pkg_resources_python.txt |
Q:
using float('nan') to represent missing values - safe?
Python 3.1
I am doing some calculations on a data that has missing values. Any calculation that involves a missing value should result in a missing value.
I am thinking of using float('nan') to represent missing values. Is it safe? At the end I'll just check
def is_missing(x):
return x!=x # I hope it's safe to use to check for NaN
It seems perfect, but I couldn't find a clear confirmation in the documentation.
I could use None of course, but it would then require that I do every single calculation with try / except TypeError to detect it. I could also use Inf, but I am even less sure about how it works.
EDIT:
@MSN I understand using NaN is slow. But if my choice is either:
# missing value represented by NaN
def f(a, b, c):
return a + b * c
or
# missing value represented by None
def f(a, b, c):
if a is None or b is None or c is None:
return None
else:
return a + b * c
I would imagine the NaN option is still faster, isn't it?
A:
It's safe-ish, but if the FPU ever has to touch x it can be insanely slow (as some hardware treats NaN as a special case): Is it a good idea to use IEEE754 floating point NaN for values which are not set?
| using float('nan') to represent missing values - safe? | Python 3.1
I am doing some calculations on a data that has missing values. Any calculation that involves a missing value should result in a missing value.
I am thinking of using float('nan') to represent missing values. Is it safe? At the end I'll just check
def is_missing(x):
return x!=x # I hope it's safe to use to check for NaN
It seems perfect, but I couldn't find a clear confirmation in the documentation.
I could use None of course, but it would then require that I do every single calculation with try / except TypeError to detect it. I could also use Inf, but I am even less sure about how it works.
EDIT:
@MSN I understand using NaN is slow. But if my choice is either:
# missing value represented by NaN
def f(a, b, c):
return a + b * c
or
# missing value represented by None
def f(a, b, c):
if a is None or b is None or c is None:
return None
else:
return a + b * c
I would imagine the NaN option is still faster, isn't it?
| [
"It's safe-ish, but if the FPU ever has to touch x it can be insanely slow (as some hardware treats NaN as a special case): Is it a good idea to use IEEE754 floating point NaN for values which are not set?\n"
] | [
1
] | [] | [] | [
"floating_point",
"python",
"python_3.x"
] | stackoverflow_0004054005_floating_point_python_python_3.x.txt |
Q:
Pull data from one couchdb doc via ids in another (Python)
I have two databases in CouchDB - DB1's documents are user data - name, email address, username, password but within one field that I store a list of the ID's saved in DB2 where user projects are saved (containing a username field and some Textfields.
Example DB1 Document (Users)
{
"_id": "bobsmith1000",
"_rev": "83-1e00173cac0e736c9988d3addac403de",
"first_name": "Bob",
"password": "$2a$12$sdZUkkyDnDePQFNarTTgyuUZS6DL13JvBk/k9iUa5jh08gWAS5hpm",
"second_name": "Smith",
"urls": null,
"email": "bob@smith.com",
"projects": [
"ee5ccf56da22121fd71d892dbe051746",
"ee5ccf56da22121fd71d892dbe0526bb",
"ee5ccf56da22121fd71d892dbe053433",
"ee5ccf56da22121fd71d892dbe056c71",
"ee5ccf56da22121fd71d892dbe0579c3",
"ee5ccf56da22121fd71d892dbe05930d"
]
}
Example DB2 Document (Projects)
{
"_id": "ee5ccf56da22121fd71d892dbe05930d",
"_rev": "1-c923fbe9de82318980c7778c4c089321",
"url": "http://harkmastering.s3.amazonaws.com/testprojects/testfolder.zip",
"username": "bobsmith1000",
"time": "2010-10-29 07:13:47.377085",
"file_size": "5.2 MB"
}
I am trying to write a view in Python (using the Flask web framework and Python Couchdb library) that will check db1, grab all the project ids, and then go to db2 and in a batch way pull out the url, time, filesize for each document with matching ids so I can can place that data in a table.
I only began programming earlier this year and this involves techniques that I can only imagine. Can anyone help me find a solution?
Kind thanks
A:
Unless you have great reasons to split your docs in different dbs, that seems like is not the case according to your question, them you should keep them all on the same database and have some property on the docs to identify their type (like a "type: user" and "type: project").
That way you can get the desired result on a single couchdb view without too much trouble. In your view map function you will just need to emit keys like ["username",0] and ["username","projectname"]. In Javascript that would be:
function(doc) {
if (doc.type == "user") {
emit([doc._id,0],null);
} else if(doc.type == "project") {
emit([doc.username,doc._id],null);
}
}
Them you can query that view and have an organized set of documents.
| Pull data from one couchdb doc via ids in another (Python) | I have two databases in CouchDB - DB1's documents are user data - name, email address, username, password but within one field that I store a list of the ID's saved in DB2 where user projects are saved (containing a username field and some Textfields.
Example DB1 Document (Users)
{
"_id": "bobsmith1000",
"_rev": "83-1e00173cac0e736c9988d3addac403de",
"first_name": "Bob",
"password": "$2a$12$sdZUkkyDnDePQFNarTTgyuUZS6DL13JvBk/k9iUa5jh08gWAS5hpm",
"second_name": "Smith",
"urls": null,
"email": "bob@smith.com",
"projects": [
"ee5ccf56da22121fd71d892dbe051746",
"ee5ccf56da22121fd71d892dbe0526bb",
"ee5ccf56da22121fd71d892dbe053433",
"ee5ccf56da22121fd71d892dbe056c71",
"ee5ccf56da22121fd71d892dbe0579c3",
"ee5ccf56da22121fd71d892dbe05930d"
]
}
Example DB2 Document (Projects)
{
"_id": "ee5ccf56da22121fd71d892dbe05930d",
"_rev": "1-c923fbe9de82318980c7778c4c089321",
"url": "http://harkmastering.s3.amazonaws.com/testprojects/testfolder.zip",
"username": "bobsmith1000",
"time": "2010-10-29 07:13:47.377085",
"file_size": "5.2 MB"
}
I am trying to write a view in Python (using the Flask web framework and Python Couchdb library) that will check db1, grab all the project ids, and then go to db2 and in a batch way pull out the url, time, filesize for each document with matching ids so I can can place that data in a table.
I only began programming earlier this year and this involves techniques that I can only imagine. Can anyone help me find a solution?
Kind thanks
| [
"Unless you have great reasons to split your docs in different dbs, that seems like is not the case according to your question, them you should keep them all on the same database and have some property on the docs to identify their type (like a \"type: user\" and \"type: project\").\nThat way you can get the desire... | [
1
] | [] | [] | [
"couchdb",
"flask",
"python"
] | stackoverflow_0004052220_couchdb_flask_python.txt |
Q:
How can I create a TABLE if and only if it does not exist?
I'm trying
conn = MySQLdb.connect (host = "localhost",
user = "username",
passwd = "password",
db = "my_db")
cursor = conn.cursor ()
q = """IF NOT EXISTS CREATE TABLE %s (
course VARCHAR(15),
student VARCHAR(15),
teacher VARCHAR(15),
timeslot VARCHAR(15))""" % (d,)
cursor.execute(q)
But I get the error : _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF NOT EXISTS CREATE TABLE ACCOUNTG (\\n\\t course VARCHAR(15),\\n\\t s' at line 1")
I'm not sure what's wrong with what I'm trying, I just want to make a table if it doesn't exist. Any input would be appreciated, thanks!
A:
Wrong syntax: IF NOT EXISTS CREATE TABLE is not valid SQL in MySQL.
You want
CREATE TABLE IF NOT EXISTS [tablename]
per the MySQL documentation.
| How can I create a TABLE if and only if it does not exist? | I'm trying
conn = MySQLdb.connect (host = "localhost",
user = "username",
passwd = "password",
db = "my_db")
cursor = conn.cursor ()
q = """IF NOT EXISTS CREATE TABLE %s (
course VARCHAR(15),
student VARCHAR(15),
teacher VARCHAR(15),
timeslot VARCHAR(15))""" % (d,)
cursor.execute(q)
But I get the error : _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF NOT EXISTS CREATE TABLE ACCOUNTG (\\n\\t course VARCHAR(15),\\n\\t s' at line 1")
I'm not sure what's wrong with what I'm trying, I just want to make a table if it doesn't exist. Any input would be appreciated, thanks!
| [
"Wrong syntax: IF NOT EXISTS CREATE TABLE is not valid SQL in MySQL. \nYou want \nCREATE TABLE IF NOT EXISTS [tablename]\n\nper the MySQL documentation.\n"
] | [
14
] | [] | [] | [
"mysql",
"mysql_error_1064",
"python"
] | stackoverflow_0004054649_mysql_mysql_error_1064_python.txt |
Q:
Does anyone see why the first part of my regex isn't working in Python?
I tested this regex out in RegexBuddy
,[A-Z\s]+?,(LA|RO|MU|FE|AV|CA),(ML|FE|MN|FS|UN)?,(\d+/\d+/\d{4})?
and it seems to be able to do what I need it to do - capture a piece of data that looks like one of the following:
,POWDER,RO,ML,8/19/2002
,POWDER,RO,,,
,POWDER,RO,,8/19/2002
,POWDER,RO,ML,,
When I use it in a python string:
r",[A-Z\s]+?,(LA|RO|MU|FE|AV|CA),(ML|FE|MN|FS|UN)?,(\d+/\d+/\d{4})?"
It misses the first part of the match, and my resulting matches look like: RO,ML,8/19/2002, or RO,ML, or jusr RO,
The first token is a word that is stored as all caps and may have spaces (and/or possibly punctuation that i need to address as well shortly) in it. if I remove the space it still doesn't capture the one word names that it should. Did I miss something obvious?
A:
Yes. You did not capture the first group.
r",([A-Z\s]+),(LA|RO|MU|FE|AV|CA),(ML|FE|MN|FS|UN)?,(\d+/\d+/\d{4})?"
# ^ ^
BTW, it seems that you are parsing a CSV file with regex. In Python, there is already a csv module.
A:
The first part of your regex doesn't have capturing parentheses around it. Try the regex:
,([A-Z\s]+?),(LA|RO|MU|FE|AV|CA),(ML|FE|MN|FS|UN)?,(\d+/\d+/\d{4})?
#^^ This was [A-Z\s]+?; needs to be ([A-Z\s]+?)
which would be this in python:
r",([A-Z\s]+?),(LA|RO|MU|FE|AV|CA),(ML|FE|MN|FS|UN)?,(\d+/\d+/\d{4})?"
Example from the interpreter:
>>> import re
>>> r = re.compile(r",[A-Z\s]+?,(LA|RO|MU|FE|AV|CA),(ML|FE|MN|FS|UN)?,(\d+/\d+/\d{4})?")
>>> r.match(",POWDER,RO,ML,8/19/2002").groups()
('RO', 'ML', '8/19/2002')
>>> r = re.compile(r",([A-Z\s]+?),(LA|RO|MU|FE|AV|CA),(ML|FE|MN|FS|UN)?,(\d+/\d+/\d{4})?")
>>> r.match(",POWDER,RO,ML,8/19/2002").groups()
('POWDER', 'RO', 'ML', '8/19/2002')
A:
I'm not into python, but you just forgot to use brackets to indicate that you want to capture that part:
,([A-Z\s]+)?,(LA|RO|MU|FE|AV|CA),(ML|FE|MN|FS|UN)?,(\d+/\d+/\d{4})? should do what you want
A:
Yes, you missed the grouping parentheses:
>>> s = ",POWDER,RO,ML,8/19/2002"
>>> pat = r",([A-Z\s]+?),(LA|RO|MU|FE|AV|CA),(ML|FE|MN|FS|UN)?,(\d+/\d+/\d{4})?"
>>> re.match(pat, s).groups()
('POWDER', 'RO', 'ML', '8/19/2002')
| Does anyone see why the first part of my regex isn't working in Python? | I tested this regex out in RegexBuddy
,[A-Z\s]+?,(LA|RO|MU|FE|AV|CA),(ML|FE|MN|FS|UN)?,(\d+/\d+/\d{4})?
and it seems to be able to do what I need it to do - capture a piece of data that looks like one of the following:
,POWDER,RO,ML,8/19/2002
,POWDER,RO,,,
,POWDER,RO,,8/19/2002
,POWDER,RO,ML,,
When I use it in a python string:
r",[A-Z\s]+?,(LA|RO|MU|FE|AV|CA),(ML|FE|MN|FS|UN)?,(\d+/\d+/\d{4})?"
It misses the first part of the match, and my resulting matches look like: RO,ML,8/19/2002, or RO,ML, or jusr RO,
The first token is a word that is stored as all caps and may have spaces (and/or possibly punctuation that i need to address as well shortly) in it. if I remove the space it still doesn't capture the one word names that it should. Did I miss something obvious?
| [
"Yes. You did not capture the first group.\nr\",([A-Z\\s]+),(LA|RO|MU|FE|AV|CA),(ML|FE|MN|FS|UN)?,(\\d+/\\d+/\\d{4})?\"\n# ^ ^ \n\nBTW, it seems that you are parsing a CSV file with regex. In Python, there is already a csv module.\n",
"The first part of your regex doesn't have capturing parentheses around... | [
5,
3,
0,
0
] | [] | [] | [
"python",
"regex"
] | stackoverflow_0004054690_python_regex.txt |
Q:
Python XML Parse (using schema to generate dataset)
I'm looking to parse a xml file using Python and I was wondering if there was any way of automating the task over manually walking through all xml nodes/attributes using xml.dom.minidom library.
Essentially what would be sweet is if I could load a xml schema for the xml file I am reading then have that automatically generate some kind of data struct/set with all of the data within the xml.
In C# land this is possible via creating a strongly typed dataset class from a xml schema and then using this dataset to read the xml file in.
Is there any equivalent in Python?
A:
lxml is a super-robust xml parsing package. It includes a subpackage, lxml.objectify, that will make an object tree from your xml.
It doesn't generate a class from the schema -- that's probably more a C#/Java thing -- but it does do schema validation so you know what kind of object you're getting back (see "asserting a schema").
A:
You might take a look at lxml.objectify, particularly the E-factory. It's not really an equivalent to the ADO tools, but you may find it useful nonetheless.
| Python XML Parse (using schema to generate dataset) | I'm looking to parse a xml file using Python and I was wondering if there was any way of automating the task over manually walking through all xml nodes/attributes using xml.dom.minidom library.
Essentially what would be sweet is if I could load a xml schema for the xml file I am reading then have that automatically generate some kind of data struct/set with all of the data within the xml.
In C# land this is possible via creating a strongly typed dataset class from a xml schema and then using this dataset to read the xml file in.
Is there any equivalent in Python?
| [
"lxml is a super-robust xml parsing package. It includes a subpackage, lxml.objectify, that will make an object tree from your xml.\nIt doesn't generate a class from the schema -- that's probably more a C#/Java thing -- but it does do schema validation so you know what kind of object you're getting back (see \"asse... | [
3,
0
] | [
"hey dude - take beautifulSoup - it is a super library. HEAD over to the site scraperwiki.com\nthe can help you! \n"
] | [
-1
] | [
"c#",
"dataset",
"python",
"schema",
"xml"
] | stackoverflow_0004054205_c#_dataset_python_schema_xml.txt |
Q:
django error ,about django-sphinx
from django.db import models
from djangosphinx.models import SphinxSearch
class MyModel(models.Model):
search = SphinxSearch() # optional: defaults to db_table
# If your index name does not match MyModel._meta.db_table
# Note: You can only generate automatic configurations from the ./manage.py script
# if your index name matches.
search = SphinxSearch('index_name')
# Or maybe we want to be more.. specific
searchdelta = SphinxSearch(
index='index_name delta_name',
weights={
'name': 100,
'description': 10,
'tags': 80,
},
mode='SPH_MATCH_ALL',
rankmode='SPH_RANK_NONE',
)
queryset = MyModel.search.query('query')
results1 = queryset.order_by('@weight', '@id', 'my_attribute')
results2 = queryset.filter(my_attribute=5)
results3 = queryset.filter(my_other_attribute=[5, 3,4])
results4 = queryset.exclude(my_attribute=5)[0:10]
results5 = queryset.count()
# as of 2.0 you can now access an attribute to get the weight and similar arguments
for result in results1:
print result, result._sphinx
# you can also access a similar set of meta data on the queryset itself (once it's been sliced or executed in any way)
print results1._sphinx
and
Traceback (most recent call last):
File "D:\zjm_code\sphinx_test\models.py", line 1, in <module>
from django.db import models
File "D:\Python25\Lib\site-packages\django\db\__init__.py", line 10, in <module>
if not settings.DATABASE_ENGINE:
File "D:\Python25\Lib\site-packages\django\utils\functional.py", line 269, in __getattr__
self._setup()
File "D:\Python25\Lib\site-packages\django\conf\__init__.py", line 38, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
A:
I know what the problem is :)
You are trying to run this script as stand-alone. But since you use django models. all of them have to be imported in your namespace. This is what is the error. It clearly days ImportError.
To solve - go to your django-project directory & then type python manage.py shell. This imports all Django-env files. Now import your models & try out the search.
A:
The error is about the environment. Django cannot find your settings file; Are you doing
python manage.py runserver
itself, or something else?
| django error ,about django-sphinx | from django.db import models
from djangosphinx.models import SphinxSearch
class MyModel(models.Model):
search = SphinxSearch() # optional: defaults to db_table
# If your index name does not match MyModel._meta.db_table
# Note: You can only generate automatic configurations from the ./manage.py script
# if your index name matches.
search = SphinxSearch('index_name')
# Or maybe we want to be more.. specific
searchdelta = SphinxSearch(
index='index_name delta_name',
weights={
'name': 100,
'description': 10,
'tags': 80,
},
mode='SPH_MATCH_ALL',
rankmode='SPH_RANK_NONE',
)
queryset = MyModel.search.query('query')
results1 = queryset.order_by('@weight', '@id', 'my_attribute')
results2 = queryset.filter(my_attribute=5)
results3 = queryset.filter(my_other_attribute=[5, 3,4])
results4 = queryset.exclude(my_attribute=5)[0:10]
results5 = queryset.count()
# as of 2.0 you can now access an attribute to get the weight and similar arguments
for result in results1:
print result, result._sphinx
# you can also access a similar set of meta data on the queryset itself (once it's been sliced or executed in any way)
print results1._sphinx
and
Traceback (most recent call last):
File "D:\zjm_code\sphinx_test\models.py", line 1, in <module>
from django.db import models
File "D:\Python25\Lib\site-packages\django\db\__init__.py", line 10, in <module>
if not settings.DATABASE_ENGINE:
File "D:\Python25\Lib\site-packages\django\utils\functional.py", line 269, in __getattr__
self._setup()
File "D:\Python25\Lib\site-packages\django\conf\__init__.py", line 38, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
| [
"I know what the problem is :)\nYou are trying to run this script as stand-alone. But since you use django models. all of them have to be imported in your namespace. This is what is the error. It clearly days ImportError.\nTo solve - go to your django-project directory & then type python manage.py shell. This impor... | [
1,
0
] | [] | [] | [
"django",
"django_sphinx",
"python"
] | stackoverflow_0002174400_django_django_sphinx_python.txt |
Q:
How to use Python re module to replace \n with nothing in a single file
Regards to all.
I'm developing a Image compression system using Python Image Library. The basic workflow is:
Read all images of a certain directory with : find /opt/images -name *.jpg > /opt/rs/images.txt
Read this file and storage the result in a Python list
Iterate the list, create a Image object and passing like a argument to
the compress function
and, copy the resulting image on a certain directory which is buit
depending of the name of the image.
A example:
/opt/buzon/17_499999_1_00000000_00000999_1.jpg
This is the real name of the image:
The final result is:
17_499999.jpg
The ouput directory is: /opt/ftp
and should be storaged on this way:
1- first partition
00000000 - second partition
00000999 - third partition
1- this flag if to decide if we have to compress this image or not (1 is False, 0 is True)
For that reason the final path of the image is:
/opt/ftp/1/00000000/00000999/17_499999.jpg for the original copy
/opt/ftp/1/00000000/00000999/17_499999_tumb.jpg
Now, Where is the problem. When I read the file where I storage the result of the find command, each line of the file has the \n character.
How I can replace with regular expressions this?
The completed source code is this. Any suggests is welcome.
import Image, os ,sys, re, subprocess, shlex
import ConfigParser
from symbol import except_clause
CONFIG_FILE = "/opt/scripts/config.txt"
config = ConfigParser.ConfigParser()
config.read(CONFIG_FILE)
entry_dir = config.get('directories', 'entry_dir')
out_dir = config.get('directories', 'out_dir')
def resize(img, box, fit, out):
'''Downsample the image.
@param img: Un objeto de la clase Imagen
@param box: tuple(x, y) - El recuadro de la imagen resultante
@param fix: boolean - el corte de la imagen para llenar el rectangulo
@param out: objeto de tipo fichero - guarda la imagen hacia la salida estandar
'''
# prepara la imagen con un factor de 2, 4, 8 y el algoritmo mas rapido
factor = 1
while img.size[0]/factor > 2*box[0] and img.size[1]*2/factor > 2*box[1]:
factor *=2
if factor > 1:
img.thumbnail((img.size[0]/factor, img.size[1]/factor), Image.NEAREST)
# Aqui se calcula el rectangulo optimo para la imagen
if fit:
x1 = y1 = 0
x2, y2 = img.size
wRatio = 1.0 * x2/box[0]
hRatio = 1.0 * y2/box[1]
if hRatio > wRatio:
y1 = y2/2-box[1]*wRatio/2
y2 = y2/2+box[1]*wRatio/2
else:
x1 = x2/2-box[0]*hRatio/2
x2 = x2/2+box[0]*hRatio/2
# Este metodo es para manipular rectangulos de una determinada imagen
# definido por 4 valores que representan las coordenadas: izquierda,
# arriba, derecha y abajo
img = img.crop((x1,y1,x2,y2))
# Le damos el nuevo tamanno a la imagen con el algoritmo de mejor calidad(ANTI-ALIAS)
img.thumbnail(box, Image.ANTIALIAS)
return img
def removeFiles(directory):
"""
Funcion para borrar las imagenes luego de ser procesadas
"""
for f in os.listdir(directory):
path = os.path.abspath(f)
if re.match("*.jpg", path):
try:
print "Erasing %s ..." % (path)
os.remove(path)
except os.error:
pass
def case_partition(img):
"""
@desc: Esta funcion es la que realmente guarda la imagen en la
particion 0
@param: imagen a guardar
@output_dir: Directorio a guardar las imagenes
"""
nombre_imagen = img
nombre_import = os.path.splitext(nombre_imagen)
temp = nombre_import[0]
nombre_real = temp.split('_')
if nombre_real[4] == 0:
ouput_file = nombre_real[0] + nombre_real[1] + ".jpg"
output_dir = out_dir + "/%d/%d/%d/" % (nombre_real[2], nombre_real[3], nombre_real[4])
if os.path.isdir(output_dir):
os.chdir(output_dir)
img.save(output_file, "JPEG", quality=75)
else:
create_out_dir(output_dir)
os.chdir(output_dir)
img.save(output_file)
else:
print "Esta imagen sera comprimida"
img = resize(img, 200, 200, 200) ## FIXME Definir el tamano de la imagen
# Salvamos la imagen hacia un objeto de tipo file
# con la calidad en 75% en JPEG y el nombre definido por los especialistas
# Este nombre no esta definido......
# FIXME
output_file = nombre_real[0] + nombre_path[1] + "_.jpg"
output_dir = out_dir + "/%d/%d" % (nombre_real[2], nombre_real[3], nombre_real[4])
if os.path.isdir(output_dir):
os.chdir(out)
img.save(output_file, "JPEG", quality=75)
else:
create_out_dir(output_dir)
os.chdir(output_dir)
img.save(output_file, "JPEG", quality=75)
if __name__ == "__main__":
find = "find %s -name *.jpg > /opt/scripts/images.txt" % entry_dir
args = shlex.split(find)
p = subprocess.Popen(args)
f = open('/opt/scripts/images.txt', "r")
images = []
for line in f:
images.append(line)
f.close()
for i in images:
img = Image.open(filename) # Here is the error when I try to open a file
case_partition(img) # with the format '/opt/buzon/15_498_3_00000000_00000000_1.jpg\n'
# and the \n character is which I want to replace with nothing
removeFiles(entry_dir) #
#
Regards
A:
Assuming s is the string with the carriage return, you may use s.strip("\n") to remove carriage returns at the corners of the string. No need for regular expressions there.
A:
I guess the relevant code lines are these:
for line in f:
images.append(line)
to remove the \n, you can simply call strip() on the string:
for line in f:
images.append(line.strip())
A:
there are many ways to do that without using regexp
simpliest and correct one is use images.append(line.rstrip("\n")), also you can use images.append(line[:-1])
Also you can use glob() module instead call 'find' command through shell. It will return result as python list without having to use the files. ex: images=glob.glob("*.jpg"). http://docs.python.org/library/glob.html?highlight=glob
| How to use Python re module to replace \n with nothing in a single file | Regards to all.
I'm developing a Image compression system using Python Image Library. The basic workflow is:
Read all images of a certain directory with : find /opt/images -name *.jpg > /opt/rs/images.txt
Read this file and storage the result in a Python list
Iterate the list, create a Image object and passing like a argument to
the compress function
and, copy the resulting image on a certain directory which is buit
depending of the name of the image.
A example:
/opt/buzon/17_499999_1_00000000_00000999_1.jpg
This is the real name of the image:
The final result is:
17_499999.jpg
The ouput directory is: /opt/ftp
and should be storaged on this way:
1- first partition
00000000 - second partition
00000999 - third partition
1- this flag if to decide if we have to compress this image or not (1 is False, 0 is True)
For that reason the final path of the image is:
/opt/ftp/1/00000000/00000999/17_499999.jpg for the original copy
/opt/ftp/1/00000000/00000999/17_499999_tumb.jpg
Now, Where is the problem. When I read the file where I storage the result of the find command, each line of the file has the \n character.
How I can replace with regular expressions this?
The completed source code is this. Any suggests is welcome.
import Image, os ,sys, re, subprocess, shlex
import ConfigParser
from symbol import except_clause
CONFIG_FILE = "/opt/scripts/config.txt"
config = ConfigParser.ConfigParser()
config.read(CONFIG_FILE)
entry_dir = config.get('directories', 'entry_dir')
out_dir = config.get('directories', 'out_dir')
def resize(img, box, fit, out):
'''Downsample the image.
@param img: Un objeto de la clase Imagen
@param box: tuple(x, y) - El recuadro de la imagen resultante
@param fix: boolean - el corte de la imagen para llenar el rectangulo
@param out: objeto de tipo fichero - guarda la imagen hacia la salida estandar
'''
# prepara la imagen con un factor de 2, 4, 8 y el algoritmo mas rapido
factor = 1
while img.size[0]/factor > 2*box[0] and img.size[1]*2/factor > 2*box[1]:
factor *=2
if factor > 1:
img.thumbnail((img.size[0]/factor, img.size[1]/factor), Image.NEAREST)
# Aqui se calcula el rectangulo optimo para la imagen
if fit:
x1 = y1 = 0
x2, y2 = img.size
wRatio = 1.0 * x2/box[0]
hRatio = 1.0 * y2/box[1]
if hRatio > wRatio:
y1 = y2/2-box[1]*wRatio/2
y2 = y2/2+box[1]*wRatio/2
else:
x1 = x2/2-box[0]*hRatio/2
x2 = x2/2+box[0]*hRatio/2
# Este metodo es para manipular rectangulos de una determinada imagen
# definido por 4 valores que representan las coordenadas: izquierda,
# arriba, derecha y abajo
img = img.crop((x1,y1,x2,y2))
# Le damos el nuevo tamanno a la imagen con el algoritmo de mejor calidad(ANTI-ALIAS)
img.thumbnail(box, Image.ANTIALIAS)
return img
def removeFiles(directory):
"""
Funcion para borrar las imagenes luego de ser procesadas
"""
for f in os.listdir(directory):
path = os.path.abspath(f)
if re.match("*.jpg", path):
try:
print "Erasing %s ..." % (path)
os.remove(path)
except os.error:
pass
def case_partition(img):
"""
@desc: Esta funcion es la que realmente guarda la imagen en la
particion 0
@param: imagen a guardar
@output_dir: Directorio a guardar las imagenes
"""
nombre_imagen = img
nombre_import = os.path.splitext(nombre_imagen)
temp = nombre_import[0]
nombre_real = temp.split('_')
if nombre_real[4] == 0:
ouput_file = nombre_real[0] + nombre_real[1] + ".jpg"
output_dir = out_dir + "/%d/%d/%d/" % (nombre_real[2], nombre_real[3], nombre_real[4])
if os.path.isdir(output_dir):
os.chdir(output_dir)
img.save(output_file, "JPEG", quality=75)
else:
create_out_dir(output_dir)
os.chdir(output_dir)
img.save(output_file)
else:
print "Esta imagen sera comprimida"
img = resize(img, 200, 200, 200) ## FIXME Definir el tamano de la imagen
# Salvamos la imagen hacia un objeto de tipo file
# con la calidad en 75% en JPEG y el nombre definido por los especialistas
# Este nombre no esta definido......
# FIXME
output_file = nombre_real[0] + nombre_path[1] + "_.jpg"
output_dir = out_dir + "/%d/%d" % (nombre_real[2], nombre_real[3], nombre_real[4])
if os.path.isdir(output_dir):
os.chdir(out)
img.save(output_file, "JPEG", quality=75)
else:
create_out_dir(output_dir)
os.chdir(output_dir)
img.save(output_file, "JPEG", quality=75)
if __name__ == "__main__":
find = "find %s -name *.jpg > /opt/scripts/images.txt" % entry_dir
args = shlex.split(find)
p = subprocess.Popen(args)
f = open('/opt/scripts/images.txt', "r")
images = []
for line in f:
images.append(line)
f.close()
for i in images:
img = Image.open(filename) # Here is the error when I try to open a file
case_partition(img) # with the format '/opt/buzon/15_498_3_00000000_00000000_1.jpg\n'
# and the \n character is which I want to replace with nothing
removeFiles(entry_dir) #
#
Regards
| [
"Assuming s is the string with the carriage return, you may use s.strip(\"\\n\") to remove carriage returns at the corners of the string. No need for regular expressions there.\n",
"I guess the relevant code lines are these:\nfor line in f:\n images.append(line)\n\nto remove the \\n, you can simply call strip(... | [
2,
1,
0
] | [] | [] | [
"python",
"python_imaging_library",
"regex",
"resize"
] | stackoverflow_0004054043_python_python_imaging_library_regex_resize.txt |
Q:
Python std methods hierarchy calls documented?
just encountered a problem at dict "type" subclassing. I did override __iter__ method and expected it will affect other methods like iterkeys, keys etc. because I believed they call __iter__ method to get values but it seems they are implemented independently and I have to override all of them.
Is this a bug or intention they don't make use of other methods and retrieves values separately ?
I didn't find in the standard Python documentation description of calls dependency between methods of standard classes. It would be handy for sublassing work and for orientation what methods is required to override for proper behaviour. Is there some supplemental documentation about python base types/classes internals ?
A:
Subclass Mapping or MuteableMapping from the collections module instead of dict and you get all those methods for free.
Here is a example of a minimal mapping and some of the methods you get for free:
import collections
class MinimalMapping(collections.Mapping):
def __init__(self, *items ):
self.elements = dict(items)
def __getitem__(self, key):
return self.elements[key]
def __len__(self):
return len(self.elements)
def __iter__(self):
return iter(self.elements)
t = MinimalMapping()
print (t.iteritems, t.keys, t.itervalues, t.get)
To subclass any of the builtin containers you should always use the appropriate baseclass from the collections module.
A:
If not specified in the documentation, it is implementation specific. Implementations other that CPython might re-use the iter method to implement iterkeys and others. I would not consider this to be a bug, but simply a bit of freedom for the implementors.
I suspect there is a performance factor in implementing the methods independently, especially as dictionaries are so widely used in Python.
So basically, you should implement them.
A:
You know the saying: "You know what happens when you assume." :-)
They don't officially document that stuff because they may decide to change it in the future. Any unofficial documentation you may find would simply document the current behavior of one Python implementation, and relying on it would result in your code being very, very fragile.
When there is official documentation of special methods, it tends to describe behavior of the interpreter with respect to your own classes, such as using __len__() when __nonzero__() isn't implemented, or only needing __lt()__ for sorting.
Since Python uses duck typing, you usually don't actually need to inherit from a built-in class to make your own class act like one. So you might reconsider whether subclassing dict is really what you want to do. You might choose a different class, such as something from the collections module, or to encapsulate rather than inheriting. (The UserString class uses encapsulation.) Or just start from scratch.
A:
Instead of subclassing dict, you could instead just create make your own class that has exactly the properties you want without too much trouble. Here's a blog post with an example of how to do this. The __str__() method in it isn't the greatest, but that's easily corrected the rest provide the functionality you seek.
| Python std methods hierarchy calls documented? | just encountered a problem at dict "type" subclassing. I did override __iter__ method and expected it will affect other methods like iterkeys, keys etc. because I believed they call __iter__ method to get values but it seems they are implemented independently and I have to override all of them.
Is this a bug or intention they don't make use of other methods and retrieves values separately ?
I didn't find in the standard Python documentation description of calls dependency between methods of standard classes. It would be handy for sublassing work and for orientation what methods is required to override for proper behaviour. Is there some supplemental documentation about python base types/classes internals ?
| [
"Subclass Mapping or MuteableMapping from the collections module instead of dict and you get all those methods for free.\nHere is a example of a minimal mapping and some of the methods you get for free:\nimport collections\nclass MinimalMapping(collections.Mapping):\n def __init__(self, *items ):\n self.e... | [
5,
2,
1,
0
] | [] | [] | [
"python",
"python_datamodel"
] | stackoverflow_0004053662_python_python_datamodel.txt |
Q:
How to deal with utf-8 encoded String and BeautifulSoup?
How can I replace HTML-entities in unicode-Strings with proper unicode?
u'"HAUS Kleider" - Über das Bekleiden und Entkleiden, das VerhŸllen und Veredeln'
to
u'"HAUS-Kleider" - Über das Bekleiden und Entkleiden, das Verhüllen und Veredeln'
edit
Actually the entities are wrong. At it seems like BeautifulSoup f...ed it up.
So the question is: How to deal with utf-8 encoded String and BeautifulSoup?
from BeautifulSoup import BeautifulSoup
f = open('path_to_file','r')
lines = [i for i in f.readlines()]
soup = BeautifulSoup(''.join(lines))
allArticles = []
for row in rows:
l =[]
for r in row.findAll('td'):
l += [r.string] # here things seem to go wrong
allArticles+=[l]
Ü -> Ÿ instead of Ü but actually I don't want the encoding to be changed anyway.
>>> soup.originalEncoding
'utf-8'
but I cant generate a proper unicode string of it
A:
I think what you need are ICU transliterators. I think there is a way to transliterate HTML entities into Unicode.
Try the transliterator id Hex/XML-Any that should to what you want. On the Demo page you can choose "Insert Sample: Compound" and then enter Hex/XML-Any into the "Compound 1" box, add some input data in the box and press "transform". Does this help?
There is a Python ICU binding, but its not taken care of well, I think.
A:
htmlentitydefs.entitydefs["quot"] returns
'"'
That's a dictionary that translates entities to their actual character. You should be able to continue easily from that point.
A:
Ok, the problem was silly, I have to confess. I was working on an old version of rows in the interactive interpreter. I don't know what was wrong with it contents, but this is the correct code:
from BeautifulSoup import BeautifulSoup
f = open('path_to_file','r')
lines = [i for i in f.readlines()]
soup = BeautifulSoup(''.join(lines))
rows = soup.findAll('tr')
allArticles = []
for row in rows:
l =[]
for r in row.findAll('td'):
l += [r.string]
allArticles+=[l]
shame on me!
| How to deal with utf-8 encoded String and BeautifulSoup? | How can I replace HTML-entities in unicode-Strings with proper unicode?
u'"HAUS Kleider" - Über das Bekleiden und Entkleiden, das VerhŸllen und Veredeln'
to
u'"HAUS-Kleider" - Über das Bekleiden und Entkleiden, das Verhüllen und Veredeln'
edit
Actually the entities are wrong. At it seems like BeautifulSoup f...ed it up.
So the question is: How to deal with utf-8 encoded String and BeautifulSoup?
from BeautifulSoup import BeautifulSoup
f = open('path_to_file','r')
lines = [i for i in f.readlines()]
soup = BeautifulSoup(''.join(lines))
allArticles = []
for row in rows:
l =[]
for r in row.findAll('td'):
l += [r.string] # here things seem to go wrong
allArticles+=[l]
Ü -> Ÿ instead of Ü but actually I don't want the encoding to be changed anyway.
>>> soup.originalEncoding
'utf-8'
but I cant generate a proper unicode string of it
| [
"I think what you need are ICU transliterators. I think there is a way to transliterate HTML entities into Unicode. \nTry the transliterator id Hex/XML-Any that should to what you want. On the Demo page you can choose \"Insert Sample: Compound\" and then enter Hex/XML-Any into the \"Compound 1\" box, add some input... | [
1,
1,
0
] | [] | [] | [
"beautifulsoup",
"python"
] | stackoverflow_0004054551_beautifulsoup_python.txt |
Q:
Text in Text Widget as a variable
so I've got this little Text widget with a scroll bar and I've got a question. How do I make text in this Text widget a variable ? If I made this text a variable I would be able to open a text file and edit it's text or save the text I've written, etc or maybe it's a wrong way that I'm approaching this, is there a better way to do this ?
A:
There is no option to associate a variable with a text widget. You can achieve the same thing by using variable traces and widget bindings but it's rarely worth the effort.
The typical way to interact with the text widget is to read a file into a variable then use the insert method of the widget to put the text into the widget. Then, to save you just do the reverse -- get the text from the widget with the get method, and write the data to a file.
One tip: when you do a get, don't get the text from 1.0 to "end", use "end-1c" instead. If you specify "end" as the last character you'll get the implicit newline that tk always adds, meaning your text file will grow by one character each time you do a load/save cycle.
| Text in Text Widget as a variable | so I've got this little Text widget with a scroll bar and I've got a question. How do I make text in this Text widget a variable ? If I made this text a variable I would be able to open a text file and edit it's text or save the text I've written, etc or maybe it's a wrong way that I'm approaching this, is there a better way to do this ?
| [
"There is no option to associate a variable with a text widget. You can achieve the same thing by using variable traces and widget bindings but it's rarely worth the effort.\nThe typical way to interact with the text widget is to read a file into a variable then use the insert method of the widget to put the text i... | [
5
] | [] | [] | [
"python",
"tkinter",
"user_interface"
] | stackoverflow_0004055017_python_tkinter_user_interface.txt |
Q:
wx.ProgressDialog not updating bar or newmsg
The update method of wx.ProgressDialog has a newmsg argument that is supposed to give a textual update on what is happening in each step of the process, but my code is not doing this properly.
Here is the link to the documentation for wx.ProgressDialog http://www.wxpython.org/docs/api/wx.ProgressDialog-class.html
Also, when I run my code, the progress bar itself stops updating when it looks to be about 50 percent complete.
Can anyone show me how to fix these two problems?
Here is my code:
import wx
import time
class Frame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, title="ProgressDialog sample")
self.progressMax = 4
self.count = 0
self.newstep='step '+str(self.count)
self.dialog = None
self.OnTimer(self.count)
def OnTimer(self, evt):
if not self.dialog:
self.dialog = wx.ProgressDialog("Progress in processing your data.",
self.newstep,
self.progressMax,
style=wx.PD_CAN_ABORT
| wx.PD_APP_MODAL
| wx.PD_SMOOTH
| wx.PD_AUTO_HIDE)
# Do Step One
print '----------------------------'
print 'Starting Step One now.'
self.count += 1
self.newstep='step '+str(self.count)
print 'self.count is: ',self.count
print 'self.newstep is: ',self.newstep
keepGoing = self.dialog.Update(self.count,self.newstep)
print '----------------------------'
time.sleep(5)
# Do Step Two
print '----------------------------'
print 'Starting Step Two now.'
self.count += 1
self.newstep='step '+str(self.count)
print 'self.count is: ',self.count
print 'self.newstep is: ',self.newstep
keepGoing = self.dialog.Update(self.count,self.newstep)
print '----------------------------'
time.sleep(5)
# Do Step Three
print '----------------------------'
print 'Starting Step Three now.'
self.count += 1
self.newstep='step '+str(self.count)
print 'self.count is: ',self.count
print 'self.newstep is: ',self.newstep
keepGoing = self.dialog.Update(self.count,self.newstep)
print '----------------------------'
time.sleep(5)
# Do Step Four
print '----------------------------'
print 'Starting Step Four now.'
self.count += 1
self.newstep='step '+str(self.count)
print 'self.count is: ',self.count
print 'self.newstep is: ',self.newstep
keepGoing = self.dialog.Update(self.count,self.newstep)
print '----------------------------'
time.sleep(5)
# Delete the progress bar when it is full
self.dialog.Update(self.progressMax)
time.sleep(3)
self.dialog.Destroy()
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = Frame(None)
frame.Show()
app.MainLoop()
Notice that I am printing everything out in order to check progress. The result of the print commands is different than what is shown in the progress dialog. The print commands seem to be doing what the code is telling them to do, but the progress dialog does not seem to be doing what the code is telling it to do, and the progress dialog is not in agreement with the result of the print commands.
This is in version 2.6 of Python.
EDIT One:
-------------------------------------------------------------------------------
I edited the code above to match adw's suggestions. The problem of not updating newmsg seems to have been eliminated, but the progress bar itself still seems to only get 50% full, and that happens when the newmsg output in the dialog box says "step 3". The progress bar then disappears. A non-computer-person using this software might realistically think that the process only completed about 50% of its work, having quit early in step 3. How can I edit the code so that it shows "step 4" in the dialog box, and so that the progress bar actually fills up to 100% for a second or two before the ProgressDialog is killed?
Edit Two:
------------------------------------------------------------------------------
I added the changes that ChrisC suggested to the code above, as you can see. But running this newly altered code still gives the same problem. So the suggestion does not seem to work in the form that I understood when I edited the code above. Can you suggest something specific I can do to the above code? Is there anything that makes it work on your computer?
A:
Python identifiers are case sensitive, so newstep is different from newStep.
As for the bar itself, that works properly when I run your code. Although I had to change (keepGoing, skip) to keepGoing everywhere, probably a version difference (I have wx.VERSION_STRING == '2.6.3.2').
A:
Your problem is wx.PD_AUTO_HIDE. As it says in the documentation, using that style
Causes the progress dialog to disappear from screen as soon as the maximum value of the progress meter has been reached.
Change your code to
self.dialog = wx.ProgressDialog("Progress in processing your data.",
self.newstep,
self.progressMax,
style=wx.PD_CAN_ABORT
| wx.PD_APP_MODAL
| wx.PD_SMOOTH)
Then the code ChrisC suggested will work.
A:
Can you call self.dialog.Update(self.progressMax) before self.dialog.Destroy(), maybe with a time.sleep(1) thrown in for a visible pause?
| wx.ProgressDialog not updating bar or newmsg | The update method of wx.ProgressDialog has a newmsg argument that is supposed to give a textual update on what is happening in each step of the process, but my code is not doing this properly.
Here is the link to the documentation for wx.ProgressDialog http://www.wxpython.org/docs/api/wx.ProgressDialog-class.html
Also, when I run my code, the progress bar itself stops updating when it looks to be about 50 percent complete.
Can anyone show me how to fix these two problems?
Here is my code:
import wx
import time
class Frame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent, title="ProgressDialog sample")
self.progressMax = 4
self.count = 0
self.newstep='step '+str(self.count)
self.dialog = None
self.OnTimer(self.count)
def OnTimer(self, evt):
if not self.dialog:
self.dialog = wx.ProgressDialog("Progress in processing your data.",
self.newstep,
self.progressMax,
style=wx.PD_CAN_ABORT
| wx.PD_APP_MODAL
| wx.PD_SMOOTH
| wx.PD_AUTO_HIDE)
# Do Step One
print '----------------------------'
print 'Starting Step One now.'
self.count += 1
self.newstep='step '+str(self.count)
print 'self.count is: ',self.count
print 'self.newstep is: ',self.newstep
keepGoing = self.dialog.Update(self.count,self.newstep)
print '----------------------------'
time.sleep(5)
# Do Step Two
print '----------------------------'
print 'Starting Step Two now.'
self.count += 1
self.newstep='step '+str(self.count)
print 'self.count is: ',self.count
print 'self.newstep is: ',self.newstep
keepGoing = self.dialog.Update(self.count,self.newstep)
print '----------------------------'
time.sleep(5)
# Do Step Three
print '----------------------------'
print 'Starting Step Three now.'
self.count += 1
self.newstep='step '+str(self.count)
print 'self.count is: ',self.count
print 'self.newstep is: ',self.newstep
keepGoing = self.dialog.Update(self.count,self.newstep)
print '----------------------------'
time.sleep(5)
# Do Step Four
print '----------------------------'
print 'Starting Step Four now.'
self.count += 1
self.newstep='step '+str(self.count)
print 'self.count is: ',self.count
print 'self.newstep is: ',self.newstep
keepGoing = self.dialog.Update(self.count,self.newstep)
print '----------------------------'
time.sleep(5)
# Delete the progress bar when it is full
self.dialog.Update(self.progressMax)
time.sleep(3)
self.dialog.Destroy()
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = Frame(None)
frame.Show()
app.MainLoop()
Notice that I am printing everything out in order to check progress. The result of the print commands is different than what is shown in the progress dialog. The print commands seem to be doing what the code is telling them to do, but the progress dialog does not seem to be doing what the code is telling it to do, and the progress dialog is not in agreement with the result of the print commands.
This is in version 2.6 of Python.
EDIT One:
-------------------------------------------------------------------------------
I edited the code above to match adw's suggestions. The problem of not updating newmsg seems to have been eliminated, but the progress bar itself still seems to only get 50% full, and that happens when the newmsg output in the dialog box says "step 3". The progress bar then disappears. A non-computer-person using this software might realistically think that the process only completed about 50% of its work, having quit early in step 3. How can I edit the code so that it shows "step 4" in the dialog box, and so that the progress bar actually fills up to 100% for a second or two before the ProgressDialog is killed?
Edit Two:
------------------------------------------------------------------------------
I added the changes that ChrisC suggested to the code above, as you can see. But running this newly altered code still gives the same problem. So the suggestion does not seem to work in the form that I understood when I edited the code above. Can you suggest something specific I can do to the above code? Is there anything that makes it work on your computer?
| [
"Python identifiers are case sensitive, so newstep is different from newStep.\nAs for the bar itself, that works properly when I run your code. Although I had to change (keepGoing, skip) to keepGoing everywhere, probably a version difference (I have wx.VERSION_STRING == '2.6.3.2').\n",
"Your problem is wx.PD_AUTO... | [
1,
1,
0
] | [] | [] | [
"progress_bar",
"progressdialog",
"python",
"wxpython"
] | stackoverflow_0004046040_progress_bar_progressdialog_python_wxpython.txt |
Q:
How do I write this to a file? I already implemented the Twitter streaming API (Python)...but it just prints to console
from getpass import getpass
from textwrap import TextWrapper
import tweepy
import time
class StreamWatcherListener(tweepy.StreamListener):
status_wrapper = TextWrapper(width=60, initial_indent=' ', subsequent_indent=' ')
def on_status(self, status):
try:
print self.status_wrapper.fill(status.text)
print '\n %s %s via %s\n' % (status.author.screen_name, status.created_at, status.source)
except:
# Catch any unicode errors while printing to console
# and just ignore them to avoid breaking application.
pass
def on_error(self, status_code):
print 'An error has occured! Status code = %s' % status_code
return True # keep stream alive
def on_timeout(self):
print 'Snoozing Zzzzzz'
username="abc"
password="abc"
auth = tweepy.BasicAuthHandler(username, password)
listener = StreamWatcherListener()
stream=tweepy.Stream(auth,listener)
stream.filter(locations=[-122.75,36.8,-121.75,37.8,-74,40,-73,41])
This just prints to console. But what if I want to do more with it?
The library I'm using is here.
A:
You are using print statements.
Open a file and write the string that you are printing to console.
In your code
class StreamWatcherListener(tweepy.StreamListener):
status_wrapper = TextWrapper(width=60, initial_indent=' ', subsequent_indent=' ')
def __init__(self, api=None):
self.file = open("myNewFile")
super(StreamWatcherListener, self).__init__(api)
....
A:
Don't use print. instead write to a file.
file = open("myNewFile")
file.write("hello")
A:
#....
class StreamWatcherListener(tweepy.StreamListener):
status_wrapper = TextWrapper(width=60, initial_indent=' ', subsequent_indent=' ')
def __init__(self, api=None):
self.file = open("myNewFile")#!!!
super(StreamWatcherListener, self).__init__(api)
def on_status(self, status):
try:#!!!
self.file.write(str(self.status_wrapper.fill(status.text)))
self.file.write('\n %s %s via %s\n' % (status.author.screen_name, status.created_at, status.source))
#....
A:
Note that you can print to a file with almost no changes:
import sys
sys.stdout = open('myFile', 'w')
print 'hello'
This will write hello to myFile.
| How do I write this to a file? I already implemented the Twitter streaming API (Python)...but it just prints to console | from getpass import getpass
from textwrap import TextWrapper
import tweepy
import time
class StreamWatcherListener(tweepy.StreamListener):
status_wrapper = TextWrapper(width=60, initial_indent=' ', subsequent_indent=' ')
def on_status(self, status):
try:
print self.status_wrapper.fill(status.text)
print '\n %s %s via %s\n' % (status.author.screen_name, status.created_at, status.source)
except:
# Catch any unicode errors while printing to console
# and just ignore them to avoid breaking application.
pass
def on_error(self, status_code):
print 'An error has occured! Status code = %s' % status_code
return True # keep stream alive
def on_timeout(self):
print 'Snoozing Zzzzzz'
username="abc"
password="abc"
auth = tweepy.BasicAuthHandler(username, password)
listener = StreamWatcherListener()
stream=tweepy.Stream(auth,listener)
stream.filter(locations=[-122.75,36.8,-121.75,37.8,-74,40,-73,41])
This just prints to console. But what if I want to do more with it?
The library I'm using is here.
| [
"You are using print statements.\nOpen a file and write the string that you are printing to console.\nIn your code\nclass StreamWatcherListener(tweepy.StreamListener):\n status_wrapper = TextWrapper(width=60, initial_indent=' ', subsequent_indent=' ')\n\n def __init__(self, api=None):\n self.file... | [
2,
0,
0,
0
] | [] | [] | [
"api",
"logging",
"python",
"twitter"
] | stackoverflow_0004050184_api_logging_python_twitter.txt |
Q:
Lists in pgu/pygame
I'm searching for help about lists in pgu gui for pygame. I need to know which methods and properties they have, so I can include them in my programs
A:
My first suggestion
Use python's builtins to introspect on
import pgu.gui.List
import inspect
help(pgu.gui.List) # to read out the doc strings
print dir(pgu.gui.List) # to get the namespace of List class
# to get all methods of that class
all_functions = inspect.getmembers(pgu.gui.List, inspect.isfunction)
Always look at the source code, when it is available
http://code.google.com/p/pgu/source/browse/trunk/pgu/gui/area.py
From the code: You can create and clear a list.
class List(ScrollArea):
"""A list of items in an area.
<p>This widget can be a form element, it has a value set to whatever item is selected.</p>
<pre>List(width,height)</pre>
"""
....
def clear(self):
"""Clear the list.
<pre>List.clear()</pre>
"""
...
Usage :
# Create the actual widget
usagelist = gui.List(width, height)
| Lists in pgu/pygame | I'm searching for help about lists in pgu gui for pygame. I need to know which methods and properties they have, so I can include them in my programs
| [
"My first suggestion\nUse python's builtins to introspect on \nimport pgu.gui.List\nimport inspect\nhelp(pgu.gui.List) # to read out the doc strings\nprint dir(pgu.gui.List) # to get the namespace of List class\n# to get all methods of that class\nall_functions = inspect.getmembers(pgu.gui.List, inspect.isfunction)... | [
0
] | [] | [] | [
"pgu",
"pygame",
"python"
] | stackoverflow_0004055347_pgu_pygame_python.txt |
Q:
How to set defualt python library path
I'm using FreeBSD 7.2. I upgraded to Python 2.6. However when I run any python app, it is still using /usr/local/lib/pytho25 as the library path. How do I change it? I cannot modify the python app. Basically I need to change the default lib path to python26.
A:
Are you sure you're using the new binary? I'm not familiar with FreeBSD, but with OpenBSD you have to do a ln -s /usr/local/bin/python2.6 /usr/local/bin/python if you want to start it as python. Perhaps it still points the old way? Also there is PYTHONPATH
A:
You can creat a softlink to your desiered python executable:
$ cd /usr/bin
$ ln -s python2.6 python
This way python command points to python2.6
A:
You have probably not migrated correctly to python 2.6 as you should no longer have python 2.5
You can follow the UPDATING notes here to completely get rid of python2.5 (this is for python2.7 but you can safely follow those instructions):
http://www.freshports.org/lang/python27/
| How to set defualt python library path | I'm using FreeBSD 7.2. I upgraded to Python 2.6. However when I run any python app, it is still using /usr/local/lib/pytho25 as the library path. How do I change it? I cannot modify the python app. Basically I need to change the default lib path to python26.
| [
"Are you sure you're using the new binary? I'm not familiar with FreeBSD, but with OpenBSD you have to do a ln -s /usr/local/bin/python2.6 /usr/local/bin/python if you want to start it as python. Perhaps it still points the old way? Also there is PYTHONPATH\n",
"You can creat a softlink to your desiered python ex... | [
3,
0,
0
] | [] | [] | [
"freebsd",
"linux",
"python"
] | stackoverflow_0003749658_freebsd_linux_python.txt |
Q:
Adding Album Art using python in mp3 metadata
The code below doesnt seem to update the artwork of the mp3 file.
Code:-
#Editing the MetaData
tag = eyeD3.Tag()
print tag.link('location') //Returns 1
tag.setVersion([2,3,0])
print tag.addImage(0x08,'artwork.jpg') //Return None (Its sure that file is present)
print tag.update() //Returns 1
The values returned by the function are correct but then also the metadata is not getting updated.
What can be the possible reasons?
A:
It looks like you're specifically referring to adding images to an MP3 using the eyeD3 module. I've only used the CLI version of eyeD3 so I may be wrong, but you don't seem to be passing a type parameter to the addImage method. I don't remember being able to get it to work without passing a type.
--add-image=IMG_PATH:TYPE[:DESCRIPTION]
Add an image to the tag. The description and type
optional, but when used, both ':' delimiters must be
present. The type MUST be an string that corresponds
to one given with --list-image-types. If the IMG_PATH
value is empty the APIC frame with TYPE is removed.
http://eyed3.nicfit.net/
| Adding Album Art using python in mp3 metadata | The code below doesnt seem to update the artwork of the mp3 file.
Code:-
#Editing the MetaData
tag = eyeD3.Tag()
print tag.link('location') //Returns 1
tag.setVersion([2,3,0])
print tag.addImage(0x08,'artwork.jpg') //Return None (Its sure that file is present)
print tag.update() //Returns 1
The values returned by the function are correct but then also the metadata is not getting updated.
What can be the possible reasons?
| [
"It looks like you're specifically referring to adding images to an MP3 using the eyeD3 module. I've only used the CLI version of eyeD3 so I may be wrong, but you don't seem to be passing a type parameter to the addImage method. I don't remember being able to get it to work without passing a type.\n--add-image=IMG_... | [
0
] | [] | [] | [
"artwork",
"id3",
"metadata",
"mp3",
"python"
] | stackoverflow_0002336911_artwork_id3_metadata_mp3_python.txt |
Q:
Python: How do I promote an object from a base class to a derived class?
Hope this isn't too basic, but...
Suppose I have a base class pa(), and I have derived classes pai(), paj(), etc, that inherit from the base class.
I would like to instantiate an object from base class pa():
>>> from pamod import *
>>> mypa = pa()
>>> mypa
<pamod.pa object at 0x28d4fd0>
>>>
... and then promote it (cast it) to a derived class, based on some action:
>>> mypa.do(this)
>>> mypa
<pamod.pai object at 0x28d4fd0>
>>>
Where based on the value of "this", mypa becomes an object from class pai, etc.
I know I can assign to the object's __class__.
mypa.__class__ = pai
However I'm wondering if that's really the best approach.
Under my scheme, each instance of pai (say) would have started life as an instance of the base class pa, so pai's __init__ method could be overloaded somehow, I'm guessing.
See
this
discussion.
Peter
A:
It's a terrible approach, since you have to handle initialization of the new attributes yourself. Write a class method in the child that returns a new instance with the appropriate attributes copied over.
A:
I don't get it. Seems like reassigning __class__ keeps me from having to copy everything over, which is good since we're talking a huge (100's of MiB) amount of data.
(I'm answering my own question here so I can include code)
What's wrong with this? In reality, "x" and "y" might represent some vast amount of data. Calling mypa.do(1) promotes mypa to a member of class pai:
class pa(object):
def __init__(self):
self.x = 1.0
def do(self,i):
if i==1:
self.__class__ = pai
self.promote()
class pai(pa):
def __init__(self):
pa.__init__(self)
self.promote()
def promote(self):
self.y = 2.0
| Python: How do I promote an object from a base class to a derived class? | Hope this isn't too basic, but...
Suppose I have a base class pa(), and I have derived classes pai(), paj(), etc, that inherit from the base class.
I would like to instantiate an object from base class pa():
>>> from pamod import *
>>> mypa = pa()
>>> mypa
<pamod.pa object at 0x28d4fd0>
>>>
... and then promote it (cast it) to a derived class, based on some action:
>>> mypa.do(this)
>>> mypa
<pamod.pai object at 0x28d4fd0>
>>>
Where based on the value of "this", mypa becomes an object from class pai, etc.
I know I can assign to the object's __class__.
mypa.__class__ = pai
However I'm wondering if that's really the best approach.
Under my scheme, each instance of pai (say) would have started life as an instance of the base class pa, so pai's __init__ method could be overloaded somehow, I'm guessing.
See
this
discussion.
Peter
| [
"It's a terrible approach, since you have to handle initialization of the new attributes yourself. Write a class method in the child that returns a new instance with the appropriate attributes copied over.\n",
"I don't get it. Seems like reassigning __class__ keeps me from having to copy everything over, which is... | [
5,
0
] | [] | [] | [
"python"
] | stackoverflow_0004047935_python.txt |
Q:
What is the canonical way of handling different types in Python?
I have a function where I need to generate different output strings for another program I invoke, depending on which type it wants.
Basically, the called program needs a command line argument telling it which type it was called with.
Happily I found this answer on SO on how to check a variable for type. But I noticed how people also raised objections, that checking for types betrays a "not object oriented" design. So, is there some other way, presumable more "more object oriented" way of handling this without explicitly checking for type?
The code I have now goes something like this:
def myfunc(val):
cmd_type = 'i'
if instance(val, str):
cmd_type = 's'
cmdline = 'magicprogram ' + cmd_type + ' ' + val
Popen(cmdline, ... blah blah)
...
which works just fine, but I just wanted to know if there is some technique I am unaware of.
A:
You could use Double Dispatch or Multimethods.
A:
But I noticed how people also raised objections,
that checking for types betrays a "not object oriented" design
Actually it's called Duck typing style ("If it looks like a duck and quacks like a duck, it must be a duck."), and it's the python language that recommend using this style of programming .
and with duck typing come something call EAFP (Easier to Ask Forgiveness than Permission)
presumable more "more object oriented" way of handling this without
explicitly checking for type?
you mean more pythonic, basically what will be more pythonic in your case is something like this:
def myfunc(val):
cmd_type = 'i'
# forget about passing type to your magicprogram
cmdline = 'magicprogram %s ' % val
Popen(cmdline, ... blah blah)
and in your magicprogram (i don't know if it's your script or ...), and because
in all cases your program will get a string so just try to convert it to whatever your
script accept;
from optparse import OptionParser
# ....
if __name__ == '__main__':
parser = OptionParser(usage="blah blah")
# ...
(options, args) = parser.parse_args()
# Here you apply the EAFP with all type accepted.
try:
# call the function that will deal with if arg is string
# remember duck typing.
except ... :
# You can continue here
I don't know what's all your code, but you can follow the example above it's more pythonic, and remember every rule has their exception so maybe your case is an exception
and you will better be with type checking.
Hope this will clear things for you.
A:
I don't think Double Dispatching or Multimethods are particularly relevant nor have much to do with the objections people had to that other SO answer.
Not surprisingly, to make what you're doing more object-oriented, you'd need introduce some objects (and corresponding classes) into it. Making each value an instance of a class would allow -- in fact, virtually force -- you to stop checking its type. The modifications to your sample code below show a very simple way this could have been done:
class Value(object):
""" Generic container of values. """
def __init__(self, type_, val):
self.type = type_ # using 'type_' to avoid hiding built-in
self.val = val
def myfunc(val):
# Look ma, no type-checking!
cmdline = 'magicprogram {obj.type} {obj.val}'.format(obj=val)
print 'Popen({!r}, ... blah blah)'.format(cmdline)
# ...
val1 = Value('i', 42)
val2 = Value('s', 'foobar')
myfunc(val1) # Popen('magicprogram i 42', ... blah blah)
myfunc(val2) # Popen('magicprogram s foobar', ... blah blah)
It would be even more object-oriented if there were methods in the Value class to access its attributes indirectly, but just doing the above gets rid of the infamous type-checking. A more object-oriented design would probably have a different subclass for each kind of Value which all share a common set of methods for clients, like myfunc(), to use to create, manipulate, and extract information from them.
Another benefit of using objects is that you shouldn't have to modify myfunc() if/when you add support for a new type of 'Value` to your application -- if your abstraction of the essence of a "Value" is a good one, that is.
A:
This is more of an engineering in the large question than how to design one small function. There are many different ways to go about it, but they more or less break down to the same general thought process. Back where the type of val is known it should specify how it should be translated into a command line arg. If it were me I would probably make val be a class that had a To Command Line function that did the right thing. You could also assign a type specific myfunc function to a variable then call that when you need to.
edit: To explain the last version something along the lines of
Val = "a string"
myfunc = myfuncStringVersion
more or less doing the same thing you would with wrapping val in a class only broken out into a value and function since you might not want to wrap val in a class.
| What is the canonical way of handling different types in Python? | I have a function where I need to generate different output strings for another program I invoke, depending on which type it wants.
Basically, the called program needs a command line argument telling it which type it was called with.
Happily I found this answer on SO on how to check a variable for type. But I noticed how people also raised objections, that checking for types betrays a "not object oriented" design. So, is there some other way, presumable more "more object oriented" way of handling this without explicitly checking for type?
The code I have now goes something like this:
def myfunc(val):
cmd_type = 'i'
if instance(val, str):
cmd_type = 's'
cmdline = 'magicprogram ' + cmd_type + ' ' + val
Popen(cmdline, ... blah blah)
...
which works just fine, but I just wanted to know if there is some technique I am unaware of.
| [
"You could use Double Dispatch or Multimethods.\n",
" But I noticed how people also raised objections, \nthat checking for types betrays a \"not object oriented\" design\n\nActually it's called Duck typing style (\"If it looks like a duck and quacks like a duck, it must be a duck.\"), and it's the python langu... | [
5,
3,
3,
1
] | [] | [] | [
"oop",
"paradigms",
"python"
] | stackoverflow_0004051847_oop_paradigms_python.txt |
Q:
Assigning a value to an element of a slice in Python
This is a simple question about how Python handles data and variables. I've done a lot of experimenting and have Python mostly figured out, except this keeps tripping me up:
[edit: I separated and rearranged the examples for clarity]
Example 1:
>>> a = [[1], 2]
>>> a[0:1]
[[1]]
>>> a[0:1] = [[5]]
>>> a
[[5], 2] # The assignment worked.
Example 2:
>>> a = [[1], 2]
>>> a[0:1][0]
[1]
>>> a[0:1][0] = [5]
>>> a
[[1], 2] # No change?
Example 3:
>>> a = [[1], 2]
>>> a[0:1][0][0]
1
>>> a[0:1][0][0] = 5
>>> a
[[5], 2] # Why now?
Can anybody explain to me what's going on here?
So far the answers seem to claim that a[0:1] returns a new list containing a reference to the first element of a. But I don't see how that explains Example 1.
A:
a[0:1] is returning a new array which contains a reference to the array [1], thus you end up modifying the inner array via a reference call.
The reason the first case doesn't modify the [1] array is that you're assigning the copied outer array a new inner array value.
Bottom line - a[0:1] returns a copy of the data, but the inner data is not copied.
A:
My understanding is slicing returns a new object. That is it's return value is a new list.
Hence you can not use an assignment operator to changes the values of the original list
>>> a = [[1], 2, 3]
>>> k = a[0:2]
>>> id(a)
4299352904
>>> id(k)
4299353552
>>>
>>> id(a)
4299352904
>>> id(a[0:2])
4299352832
some more plays along the lines
>>> k = 5
>>>
>>> id(k)
4298182344
>>> a[0] = [1,2]
>>> a
[[1, 2], 2, 3]
>>> id(a)
4299352904
>>>
[Edit: on second part of question]
>>> a[0:1] = [[5]]
The following notation is also called commonly as slice assignment
The behavior for builtin lists is atomic (delete + insert) happens in one go. My understanding is that this is not allowed for custom sequence.
A:
There are three distinct operations with indices, all are translated to method calls:
a[i] = b => a.__setitem__(i, b)
del a[i] => a.__delitem__(i)
a[i] used as an expression => a.__getitem__(i)
Here a, b and i are expressions, and i can contain slice objects created using the colon shorthand syntax. E.g.:
>>> class C(object):
... def __setitem__(self, *a):
... print a
...
>>> C()[1] = 0
(1, 0)
>>> C()['foo'] = 0
('foo', 0)
>>> C()['foo':'bar'] = 0
(slice('foo', 'bar', None), 0)
>>> C()['foo':'bar',5] = 0
((slice('foo', 'bar', None), 5), 0)
So what's happening in your third example is this:
a[0:1][0][0] = 5
becomes
a.__getitem__(slice(0,1)).__getitem__(0).__setitem__(0, 5)
The first __getitem__ returns a copy of part of the list, but the second __getitem__ returns the actual list inside that, which is then modified using __setitem__.
Your second example on the other hand becomes
a.__getitem__(slice(0,1)).__setitem__(0, 5)
So __setitem__ is being called on the sliced copy, leaving the original list intact.
| Assigning a value to an element of a slice in Python | This is a simple question about how Python handles data and variables. I've done a lot of experimenting and have Python mostly figured out, except this keeps tripping me up:
[edit: I separated and rearranged the examples for clarity]
Example 1:
>>> a = [[1], 2]
>>> a[0:1]
[[1]]
>>> a[0:1] = [[5]]
>>> a
[[5], 2] # The assignment worked.
Example 2:
>>> a = [[1], 2]
>>> a[0:1][0]
[1]
>>> a[0:1][0] = [5]
>>> a
[[1], 2] # No change?
Example 3:
>>> a = [[1], 2]
>>> a[0:1][0][0]
1
>>> a[0:1][0][0] = 5
>>> a
[[5], 2] # Why now?
Can anybody explain to me what's going on here?
So far the answers seem to claim that a[0:1] returns a new list containing a reference to the first element of a. But I don't see how that explains Example 1.
| [
"a[0:1] is returning a new array which contains a reference to the array [1], thus you end up modifying the inner array via a reference call.\nThe reason the first case doesn't modify the [1] array is that you're assigning the copied outer array a new inner array value.\nBottom line - a[0:1] returns a copy of the d... | [
7,
3,
1
] | [] | [] | [
"list",
"python",
"slice",
"variable_assignment"
] | stackoverflow_0004055515_list_python_slice_variable_assignment.txt |
Q:
SQLAlchemy equivalent to Django's annotate() method
I'm doing a join like this in SQLAlchemy:
items = Item.query\
.outerjoin((ItemInfo, ItemInfo.item_id==Item.id))
items.add_columns(ItemInfo.count)
This causes SQLAlchemy to return tuples:
>>> items.first()
(<Item ...>, 2)
I'd much prefer it if the "count" value would instead be returned as an attribute of the item, i.e. I want to do:
>>> items.first().count
2
Is this supported?
A:
Actually, "items.first().count" would work, since the tuple you get back is a named tuple...but guessing you don't want to see items.first().item.foo.
The second way you could do this would be just to run the result of your query() through a function that constructs the kind of result you want:
def process(q):
for item, count in q:
item.count = count
yield count
edit: here is a generalized version:
from sqlalchemy.orm.query import Query
class AnnotateQuery(Query):
_annotations = ()
def annotate(self, key, expr):
q = self.add_column(expr)
q._annotations = self._annotations + (key, )
return q
def __iter__(self):
if not self._annotations:
return super(AnnotateQuery, self).__iter__()
else:
for row in super(AnnotateQuery, self):
item, remaining = row[0], row[1:]
for i, key in enumerate(self._annotations):
setattr(item, key, remaining[i])
yield item
# session usage:
Session = sessionmaker(query_cls=AnnotateQuery)
# query usage:
q = Session.query(Item).outerjoin(...).annotate('count', Item.count)
The third, is that you alter the Item class to support this function. You'd use column_property() to apply a select subquery to your class: http://www.sqlalchemy.org/docs/orm/mapper_config.html#sql-expressions-as-mapped-attributes . If you wanted the loading of the attribute to be conditional, you'd use deferred: http://www.sqlalchemy.org/docs/orm/mapper_config.html#deferred-column-loading .
| SQLAlchemy equivalent to Django's annotate() method | I'm doing a join like this in SQLAlchemy:
items = Item.query\
.outerjoin((ItemInfo, ItemInfo.item_id==Item.id))
items.add_columns(ItemInfo.count)
This causes SQLAlchemy to return tuples:
>>> items.first()
(<Item ...>, 2)
I'd much prefer it if the "count" value would instead be returned as an attribute of the item, i.e. I want to do:
>>> items.first().count
2
Is this supported?
| [
"Actually, \"items.first().count\" would work, since the tuple you get back is a named tuple...but guessing you don't want to see items.first().item.foo.\nThe second way you could do this would be just to run the result of your query() through a function that constructs the kind of result you want:\ndef process(q):... | [
6
] | [] | [] | [
"django",
"orm",
"python",
"sqlalchemy"
] | stackoverflow_0004052724_django_orm_python_sqlalchemy.txt |
Q:
Strange newline when attempting unbuffered reading in python
I have this code:
def getch(self):
if os.name == 'posix':
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
elif os.name == 'nt':
ch = msvcrt.getch()
return ch
This runs just fine on python 2.6 and 2.7 but whenever I try and test it on python 3.0 and up there is a new line printed out by the stdin.read call, I think this may because the python 3 changes to sys.stdin, stdout, and stderr but I'm not sure how to fix it
EDIT: running on OS X 10.6.4 python 3.1 and Ubuntu 9.04 python 2.6 this happened for me.
A:
This might be a platform-specific problem. Have you tried the code on different POSIX-based operating systems (e.g. Linux, BSD, Darwin, etc.). Are your results the same? They all handle terminal operations a little differently, so you might need to account for more than just posix vs. nt and go a little deeper.
| Strange newline when attempting unbuffered reading in python | I have this code:
def getch(self):
if os.name == 'posix':
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
elif os.name == 'nt':
ch = msvcrt.getch()
return ch
This runs just fine on python 2.6 and 2.7 but whenever I try and test it on python 3.0 and up there is a new line printed out by the stdin.read call, I think this may because the python 3 changes to sys.stdin, stdout, and stderr but I'm not sure how to fix it
EDIT: running on OS X 10.6.4 python 3.1 and Ubuntu 9.04 python 2.6 this happened for me.
| [
"This might be a platform-specific problem. Have you tried the code on different POSIX-based operating systems (e.g. Linux, BSD, Darwin, etc.). Are your results the same? They all handle terminal operations a little differently, so you might need to account for more than just posix vs. nt and go a little deeper. \n... | [
1
] | [] | [] | [
"python",
"python_3.x",
"terminal"
] | stackoverflow_0004055903_python_python_3.x_terminal.txt |
Q:
Httplib2 - AttributeError: 'NoneType' object has no attribute 'makefile'
How do I fix this?
PS: On googling, I found that this is some httplib2 bug but I didn't understand how to use the patches people have provided.
Traceback (most recent call last):
File "alt_func.py", line 18, in <module>
func(code)
File "alt_func.py", line 9, in func
resp, content = h.request(url_string, "GET", headers={'Referer': referer})
File "/usr/lib/pymodules/python2.6/httplib2/__init__.py", line 1099, in request
(response, new_content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/usr/lib/pymodules/python2.6/httplib2/__init__.py", line 901, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/usr/lib/pymodules/python2.6/httplib2/__init__.py", line 871, in _conn_request
response = conn.getresponse()
File "/usr/lib/python2.6/httplib.py", line 984, in getresponse
method=self._method)
File "/usr/lib/python2.6/httplib.py", line 330, in __init__
self.fp = sock.makefile('rb', 0)
AttributeError: 'NoneType' object has no attribute 'makefile'
A:
This is a known issue: http://code.google.com/p/httplib2/issues/detail?id=96
There appear to be some dupes logged, or perhaps the same symptom arising from different circumstances:
http://code.google.com/p/httplib2/issues/detail?id=101
http://code.google.com/p/httplib2/issues/detail?id=102
A:
You will also get this error if the server you are tying to connect to is not running or is on a different port. Quite a misleading error message, if you ask me.
A:
You have created an HTTPConnection instance, but is it not connected to anything, so the sock still has the initial value of None
Can you post some code that exhibits this failure? Which patches are you using/trying to use
| Httplib2 - AttributeError: 'NoneType' object has no attribute 'makefile' | How do I fix this?
PS: On googling, I found that this is some httplib2 bug but I didn't understand how to use the patches people have provided.
Traceback (most recent call last):
File "alt_func.py", line 18, in <module>
func(code)
File "alt_func.py", line 9, in func
resp, content = h.request(url_string, "GET", headers={'Referer': referer})
File "/usr/lib/pymodules/python2.6/httplib2/__init__.py", line 1099, in request
(response, new_content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/usr/lib/pymodules/python2.6/httplib2/__init__.py", line 901, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/usr/lib/pymodules/python2.6/httplib2/__init__.py", line 871, in _conn_request
response = conn.getresponse()
File "/usr/lib/python2.6/httplib.py", line 984, in getresponse
method=self._method)
File "/usr/lib/python2.6/httplib.py", line 330, in __init__
self.fp = sock.makefile('rb', 0)
AttributeError: 'NoneType' object has no attribute 'makefile'
| [
"This is a known issue: http://code.google.com/p/httplib2/issues/detail?id=96\nThere appear to be some dupes logged, or perhaps the same symptom arising from different circumstances:\n\nhttp://code.google.com/p/httplib2/issues/detail?id=101\nhttp://code.google.com/p/httplib2/issues/detail?id=102\n\n",
"You will a... | [
5,
5,
0
] | [] | [] | [
"httplib2",
"python"
] | stackoverflow_0003226218_httplib2_python.txt |
Q:
Extracting data from a URL result with special formatting
I have a URL:
http://somewhere.com/relatedqueries?limit=2&query=seedterm
where modifying the inputs, limit and query, will generate wanted data. Limit is the max number of term possible and query is the seed term.
The URL provides text result formatted in this way:
oo.visualization.Query.setResponse({version:'0.5',reqId:'0',status:'ok',sig:'1303596067112929220',table:{cols:[{id:'score',label:'Score',type:'number',pattern:'#,##0.###'},{id:'query',label:'Query',type:'string',pattern:''}],rows:[{c:[{v:0.9894380670262618,f:'0.99'},{v:'newterm1'}]},{c:[{v:0.9894380670262618,f:'0.99'},{v:'newterm2'}]}],p:{'totalResultsCount':'7727'}}});
I'd like to write a python script that takes two arguments (limit number and the query seed), go fetch the data online, parse the result and return a list with the new terms ['newterm1','newterm2'] in this case.
I'd love some help, especially with the URL fetching since I have never done this before.
A:
It sounds like you can break this problem up into several subproblems.
Subproblems
There are a handful of problems that need to be solved before composing the completed script:
Forming the request URL: Creating a configured request URL from a template
Retrieving data: Actually making the request
Unwrapping JSONP: The returned data appears to be JSON wrapped in a JavaScript function call
Traversing the object graph: Navigating through the result to find the desired bits of information
Forming the request URL
This is just simple string formatting.
url_template = 'http://somewhere.com/relatedqueries?limit={limit}&query={seedterm}'
url = url_template.format(limit=2, seedterm='seedterm')
Python 2 Note
You will need to use the string formatting operator (%) here.
url_template = 'http://somewhere.com/relatedqueries?limit=%(limit)d&query=%(seedterm)s'
url = url_template % dict(limit=2, seedterm='seedterm')
Retrieving data
You can use the built-in urllib.request module for this.
import urllib.request
data = urllib.request.urlopen(url) # url from previous section
This returns a file-like object called data. You can also use a with-statement here:
with urllib.request.urlopen(url) as data:
# do processing here
Python 2 Note
Import urllib2 instead of urllib.request.
Unwrapping JSONP
The result you pasted looks like JSONP. Given that the wrapping function that is called (oo.visualization.Query.setResponse) doesn't change, we can simply strip this method call out.
result = data.read()
prefix = 'oo.visualization.Query.setResponse('
suffix = ');'
if result.startswith(prefix) and result.endswith(suffix):
result = result[len(prefix):-len(suffix)]
Parsing JSON
The resulting result string is just JSON data. Parse it with the built-in json module.
import json
result_object = json.loads(result)
Traversing the object graph
Now, you have a result_object that represents the JSON response. The object itself be a dict with keys like version, reqId, and so on. Based on your question, here is what you would need to do to create your list.
# Get the rows in the table, then get the second column's value for
# each row
terms = [row['c'][2]['v'] for row in result_object['table']['rows']]
Putting it all together
#!/usr/bin/env python3
"""A script for retrieving and parsing results from requests to
somewhere.com.
This script works as either a standalone script or as a library. To use
it as a standalone script, run it as `python3 scriptname.py`. To use it
as a library, use the `retrieve_terms` function."""
import urllib.request
import json
import sys
E_OPERATION_ERROR = 1
E_INVALID_PARAMS = 2
def parse_result(result):
"""Parse a JSONP result string and return a list of terms"""
prefix = 'oo.visualization.Query.setResponse('
suffix = ');'
# Strip JSONP function wrapper
if result.startswith(prefix) and result.endswith(suffix):
result = result[len(prefix):-len(suffix)]
# Deserialize JSON to Python objects
result_object = json.loads(result)
# Get the rows in the table, then get the second column's value
# for each row
return [row['c'][2]['v'] for row in result_object['table']['rows']]
def retrieve_terms(limit, seedterm):
"""Retrieves and parses data and returns a list of terms"""
url_template = 'http://somewhere.com/relatedqueries?limit={limit}&query={seedterm}'
url = url_template.format(limit=limit, seedterm=seedterm)
try:
with urllib.request.urlopen(url) as data:
data = perform_request(limit, seedterm)
result = data.read()
except:
print('Could not request data from server', file=sys.stderr)
exit(E_OPERATION_ERROR)
terms = parse_result(result)
print(terms)
def main(limit, seedterm):
"""Retrieves and parses data and prints each term to standard output"""
terms = retrieve_terms(limit, seedterm)
for term in terms:
print(term)
if __name__ == '__main__'
try:
limit = int(sys.argv[1])
seedterm = sys.argv[2]
except:
error_message = '''{} limit seedterm
limit must be an integer'''.format(sys.argv[0])
print(error_message, file=sys.stderr)
exit(2)
exit(main(limit, seedterm))
Python 2.7 version
#!/usr/bin/env python2.7
"""A script for retrieving and parsing results from requests to
somewhere.com.
This script works as either a standalone script or as a library. To use
it as a standalone script, run it as `python2.7 scriptname.py`. To use it
as a library, use the `retrieve_terms` function."""
import urllib2
import json
import sys
E_OPERATION_ERROR = 1
E_INVALID_PARAMS = 2
def parse_result(result):
"""Parse a JSONP result string and return a list of terms"""
prefix = 'oo.visualization.Query.setResponse('
suffix = ');'
# Strip JSONP function wrapper
if result.startswith(prefix) and result.endswith(suffix):
result = result[len(prefix):-len(suffix)]
# Deserialize JSON to Python objects
result_object = json.loads(result)
# Get the rows in the table, then get the second column's value
# for each row
return [row['c'][2]['v'] for row in result_object['table']['rows']]
def retrieve_terms(limit, seedterm):
"""Retrieves and parses data and returns a list of terms"""
url_template = 'http://somewhere.com/relatedqueries?limit=%(limit)d&query=%(seedterm)s'
url = url_template % dict(limit=2, seedterm='seedterm')
try:
with urllib2.urlopen(url) as data:
data = perform_request(limit, seedterm)
result = data.read()
except:
sys.stderr.write('%s\n' % 'Could not request data from server')
exit(E_OPERATION_ERROR)
terms = parse_result(result)
print terms
def main(limit, seedterm):
"""Retrieves and parses data and prints each term to standard output"""
terms = retrieve_terms(limit, seedterm)
for term in terms:
print term
if __name__ == '__main__'
try:
limit = int(sys.argv[1])
seedterm = sys.argv[2]
except:
error_message = '''{} limit seedterm
limit must be an integer'''.format(sys.argv[0])
sys.stderr.write('%s\n' % error_message)
exit(2)
exit(main(limit, seedterm))
A:
i didn't understand well your problem because from your code there it seem to me that you use Visualization API (it's the first time that i hear about it by the way).
But well if you are just searching for a way to fetch data from a web page you could use urllib2 this is just for getting data, and if you want to parse the retrieved data you will have to use a more appropriate library like BeautifulSoop
if you are dealing with another web service (RSS, Atom, RPC) rather than web pages you can find a bunch of python library that you can use and that deal with each service perfectly.
import urllib2
from BeautifulSoup import BeautifulSoup
result = urllib2.urlopen('http://somewhere.com/relatedqueries?limit=%s&query=%s' % (2, 'seedterm'))
htmletxt = resul.read()
result.close()
soup = BeautifulSoup(htmltext, convertEntities="html" )
# you can parse your data now check BeautifulSoup API.
| Extracting data from a URL result with special formatting | I have a URL:
http://somewhere.com/relatedqueries?limit=2&query=seedterm
where modifying the inputs, limit and query, will generate wanted data. Limit is the max number of term possible and query is the seed term.
The URL provides text result formatted in this way:
oo.visualization.Query.setResponse({version:'0.5',reqId:'0',status:'ok',sig:'1303596067112929220',table:{cols:[{id:'score',label:'Score',type:'number',pattern:'#,##0.###'},{id:'query',label:'Query',type:'string',pattern:''}],rows:[{c:[{v:0.9894380670262618,f:'0.99'},{v:'newterm1'}]},{c:[{v:0.9894380670262618,f:'0.99'},{v:'newterm2'}]}],p:{'totalResultsCount':'7727'}}});
I'd like to write a python script that takes two arguments (limit number and the query seed), go fetch the data online, parse the result and return a list with the new terms ['newterm1','newterm2'] in this case.
I'd love some help, especially with the URL fetching since I have never done this before.
| [
"It sounds like you can break this problem up into several subproblems.\nSubproblems\nThere are a handful of problems that need to be solved before composing the completed script:\n\nForming the request URL: Creating a configured request URL from a template\nRetrieving data: Actually making the request\nUnwrapping ... | [
12,
1
] | [] | [] | [
"parsing",
"python",
"url"
] | stackoverflow_0004056375_parsing_python_url.txt |
Q:
python getting weekday from an input date
I'm trying to work on a homework problem where I have an input date in the format YYYY-MM-DD
I need to import a couple modules and create a function weekday where it splits up the date and returns the weekday.
So far I imported:
from time import *
from datetime import *
I need help in my weekday function where I must use a .split method
Create an object of the class datetime.date.
and use strftime to return the day of the week in full text.
Can anyone help me get started on how to implement these functions and modules properly?
A:
Suppose s is your input string:
s = '2010-10-29'
At the prompt, try s.split('-'). What happens?
Create a date object:
d = datetime.date(2010, 10, 29)
Then run d.strftime('%B'). What happens? How would you get the weekday, instead?
You can fill in the rest. Look at the Python docs for more information. Python doc: time, datetime
A:
it's two lines
import time
print time.strftime("%A", time.strptime('2010-10-29', "%Y-%m-%d"))
prints 'Friday'
| python getting weekday from an input date | I'm trying to work on a homework problem where I have an input date in the format YYYY-MM-DD
I need to import a couple modules and create a function weekday where it splits up the date and returns the weekday.
So far I imported:
from time import *
from datetime import *
I need help in my weekday function where I must use a .split method
Create an object of the class datetime.date.
and use strftime to return the day of the week in full text.
Can anyone help me get started on how to implement these functions and modules properly?
| [
"Suppose s is your input string:\ns = '2010-10-29'\n\nAt the prompt, try s.split('-'). What happens?\nCreate a date object:\nd = datetime.date(2010, 10, 29)\n\nThen run d.strftime('%B'). What happens? How would you get the weekday, instead?\nYou can fill in the rest. Look at the Python docs for more information. Py... | [
15,
2
] | [] | [] | [
"date",
"python"
] | stackoverflow_0004056683_date_python.txt |
Q:
python parsing a block of text betwen 2 known lines
I am trying to get a block of lines between 2 known lines using pyparsing. For example:
ABC
....
DEF
My python code:
end = Literal("\n").suppress()
firstLine = Literal("ABC") + SkipTo(end)
secondLine = Literal("DEF") + SkipTo(end)
line = SkipTo(end)
test = firstLine + OneOrMore(line) + secondLine
test.searchString(myText)
--> but it doesn't work. Python just hangs.
Can anybody show me how to do it?
Thanks,
A:
Add this debugging code to your program:
firstLine.setName("firstLine").setDebug()
line.setName("line").setDebug()
secondLine.setName("secondLine").setDebug()
and change searchString to parseString. setDebug() will print out every time an expression is about to be attempted to match, and if matched, what got matched, and if not matched, the exception. With your program, after making these changes I get:
Match firstLine at loc 0(1,1)
Matched firstLine -> ['ABC', '.... ']
Match line at loc 11(3,1)
Matched line -> ['DEF ']
Match line at loc 15(3,1)
Exception raised:Expected line (at char 17), (line:4, col:2)
Match secondLine at loc 15(3,1)
Exception raised:Expected "DEF" (at char 16), (line:4, col:1)
Traceback (most recent call last):
File "rrrr.py", line 19, in <module>
test.parseString(myText)
File "C:\Python25\lib\site-packages\pyparsing-1.5.5-py...
raise exc
pyparsing.ParseException: Expected "DEF" (at char 16), (line:4, col:1)
Probably not what you expected.
A:
I finally found answer to my question.
end = Literal("\n").suppress()
firstLine = Literal("ABC") + SkipTo(end)
secondLine = Literal("DEF") + SkipTo(end)
line = ~secondLine + SkipTo(end)
test = firstLine + OneOrMore(line) + secondLine
test.searchString(myText)
That works for me.
| python parsing a block of text betwen 2 known lines | I am trying to get a block of lines between 2 known lines using pyparsing. For example:
ABC
....
DEF
My python code:
end = Literal("\n").suppress()
firstLine = Literal("ABC") + SkipTo(end)
secondLine = Literal("DEF") + SkipTo(end)
line = SkipTo(end)
test = firstLine + OneOrMore(line) + secondLine
test.searchString(myText)
--> but it doesn't work. Python just hangs.
Can anybody show me how to do it?
Thanks,
| [
"Add this debugging code to your program:\nfirstLine.setName(\"firstLine\").setDebug()\nline.setName(\"line\").setDebug()\nsecondLine.setName(\"secondLine\").setDebug()\n\nand change searchString to parseString. setDebug() will print out every time an expression is about to be attempted to match, and if matched, w... | [
1,
0
] | [] | [] | [
"pyparsing",
"python"
] | stackoverflow_0004040762_pyparsing_python.txt |
Q:
Python ctypes.create_string_buffer Problem
The ReadProcessMemory function of kernel32.dll appears to be returning Unicode.
kernel32 = ctypes.windll.kernel32
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
pid = int(raw_input("Enter PID: "))
hproc = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION |PROCESS_VM_READ, False, pid)
lpbaseaddr = 16799644
read_buff = ctypes.create_string_buffer(4)
bytread = ctypes.c_ulong(0)
kernel32.ReadProcessMemory(hproc, lpbaseaddr, read_buff,
4, ctypes.byref(bytread))
print read_buff.raw #i also tried read_buff.value
I know the value at that address is 80 because I used cheat engine to make it 80. The print read_buff line returns
P. If I make the value of that address 81 with cheat engine and run my program it returns the value Q. I have been messing around and unichr(80) returns P and unichr(81) returns Q. There is obviously a problem with create_string_buff. Should I be using a byte buffer or integer buffer and how would I do that? Using unichr() works for a few values but say the address value is 800, unichr(800) obviously won't work. I'm looking for read_buff to return 50 or 60 or 800, etc.
A:
It is not returning Unicode, but four bytes as a string (probably '\x80\x00\x00\x00') Pass a pointer to an integer not a string buffer:
read_buff = ctypes.c_uint()
kernel32.ReadProcessMemory(hproc, lpbaseaddr, ctypes.byref(read_buff),
ctypes.sizeof(read_buff), ctypes.byref(bytread))
print read_buff.value
| Python ctypes.create_string_buffer Problem | The ReadProcessMemory function of kernel32.dll appears to be returning Unicode.
kernel32 = ctypes.windll.kernel32
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
pid = int(raw_input("Enter PID: "))
hproc = kernel32.OpenProcess(PROCESS_QUERY_INFORMATION |PROCESS_VM_READ, False, pid)
lpbaseaddr = 16799644
read_buff = ctypes.create_string_buffer(4)
bytread = ctypes.c_ulong(0)
kernel32.ReadProcessMemory(hproc, lpbaseaddr, read_buff,
4, ctypes.byref(bytread))
print read_buff.raw #i also tried read_buff.value
I know the value at that address is 80 because I used cheat engine to make it 80. The print read_buff line returns
P. If I make the value of that address 81 with cheat engine and run my program it returns the value Q. I have been messing around and unichr(80) returns P and unichr(81) returns Q. There is obviously a problem with create_string_buff. Should I be using a byte buffer or integer buffer and how would I do that? Using unichr() works for a few values but say the address value is 800, unichr(800) obviously won't work. I'm looking for read_buff to return 50 or 60 or 800, etc.
| [
"It is not returning Unicode, but four bytes as a string (probably '\\x80\\x00\\x00\\x00') Pass a pointer to an integer not a string buffer:\nread_buff = ctypes.c_uint()\nkernel32.ReadProcessMemory(hproc, lpbaseaddr, ctypes.byref(read_buff),\n ctypes.sizeof(read_buff), ctypes.byref(bytrea... | [
5
] | [] | [] | [
"ctypes",
"python"
] | stackoverflow_0004056609_ctypes_python.txt |
Q:
App Engine Namespaces
App Engine provides a way to set the current "namespace". Is this a way to be able to easily reference variables, and thus not always have to insert database lookups in one's code?
A:
Not quite.
Namespacing is useful when you have an appengine app that you want to deploy to serve discrete groups data. You can read more about it here.
With namespacing, you partition your appengine app's stuff (datastore, memcache, and taskqueue) into a bunch of separate groups where data, row keys, tasks, etc, don't cross-contaminate or have name/key collisions.
A:
No. Namespaces are intended to make it easier to segment your datastore (etc.).
It is particular useful if your app servers multiple organizations, but each organizations' data should be completely separate. This simplifies your code, and may also help app engine scale your app too. Read more this in the documentation on an Overview of Multitenancy.
| App Engine Namespaces | App Engine provides a way to set the current "namespace". Is this a way to be able to easily reference variables, and thus not always have to insert database lookups in one's code?
| [
"Not quite.\nNamespacing is useful when you have an appengine app that you want to deploy to serve discrete groups data. You can read more about it here.\nWith namespacing, you partition your appengine app's stuff (datastore, memcache, and taskqueue) into a bunch of separate groups where data, row keys, tasks, etc... | [
5,
1
] | [] | [] | [
"google_app_engine",
"python"
] | stackoverflow_0004057140_google_app_engine_python.txt |
Q:
Border around string python
Write a function spaced(s) that outputs spaces and a dashdot border around a string s.
The sample code, which calls spaced("Hello") would output:
--.-.-.-.-
. .
- Hello -
. .
-.-.-.-.-.
Please help me out with this :D. Im new to programming and im trying to learn this stuff. I dont have any programming experience so its quite a challenge to me. Thanks everyone!
A:
the key to programming is looking for patterns, and then implementing them.
define your requirements:
• must have fixed-space fonts
• border at the top/bottom needs to be the length of text + margin (white space) + border
• text must have two spaces in all directions (vertical and horizontal)
• you want alternating periods and hyphens
def spaced(s):
text = "hello"
textLength = len(text)
lineLength = textLength + 2 * (2 + 1)
height = 5
# at this point we know the first and fifth lines are the same and
# we know the first and fourth are the same. (reflected against the x-axis)
hBorder = ""
for c in range(lineLength):
if c % 2:
hBorder = hBorder + '.'
else:
hBorder = hBorder + '-'
spacer = "." + " " * (lineLength - 2) + "."
fancyText = "- " + text + " -"
return (hBorder, spacer, fancyText, spacer, hBorder)
textTuple = spaced("hello world")
for line in textTuple:
print line
Remember, you can only predict spacing for fixed width fonts. If you have any questions about the function above, ask in the comments. Cheers.
| Border around string python | Write a function spaced(s) that outputs spaces and a dashdot border around a string s.
The sample code, which calls spaced("Hello") would output:
--.-.-.-.-
. .
- Hello -
. .
-.-.-.-.-.
Please help me out with this :D. Im new to programming and im trying to learn this stuff. I dont have any programming experience so its quite a challenge to me. Thanks everyone!
| [
"the key to programming is looking for patterns, and then implementing them.\ndefine your requirements:\n• must have fixed-space fonts\n• border at the top/bottom needs to be the length of text + margin (white space) + border\n• text must have two spaces in all directions (vertical and horizontal)\n• you want alter... | [
3
] | [] | [] | [
"python"
] | stackoverflow_0004057129_python.txt |
Q:
Oauth + Aeoid +Python + Google App Engine + Google documents
I am trying to complete a story assignment system for my school newspaper in Google App Engine. It'll track deadlines for writers, allow writers to pick up stories, and give an "at a glance" view of the weeks stories. My partner and I are trying to fully integrate it with our newspapers Google Apps installation. Oh, and we have to use 3 legged Oauth because we don't have Google Apps Premier.
In that endeavor, I stumbled upon Aeoid and was able to follow the instructions to make federated login work. It's very cool!
Where I'm running into trouble is using Oauth to get a list of the users google documents. I have a test page set up here: mustrun.cornellsun.com/test. It is giving me errors - I've copied them at the bottom of this mail. I don't know if this has to do with my consumer secret (should I be using the key I get from google marketplace? or should I be using the key I get from the manage domains page?). Right now I'm using the key I got from the manage domains page
Also complicating this is that the actual appspot domain is mustrun2sun [].appspot[too new can't post more than one link].com, but I set it up in google apps so that only users from my domain can log in and also so that the app is deployed on my domain. (app is deployed as must[]run[].corn[]ellsun[].[]com & everything refers to it as such, even in the manage domains thing.)
I'm using GDClient 2.0 classes so I'm fairly sure that everything should work as planned... i.e. I'm not using the old service stuff or anything. I've used htt[]p:/[]/k[]ing[]yo-bachi.blog[]spot.c[]om/2010/05/gaego[]ogleoauth.ht[]ml as a bit of a template for my Oauth "dance" because the Google examples are out of date & use the old Google data 1.0 library - I think.
The error that I'm getting when I go to my test page is
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 511, in __call__
handler.get(*groups)
File "/base/data/home/apps/mustrun2sun/1.341947133742569880/main.py", line 170, in get
feed = client.GetDocList(auth_token=gdata.gauth.AeLoad(users.get_current_user().user_id())) #auth_token=TOKEN
File "/base/data/home/apps/mustrun2sun/1.341947133742569880/gdata/docs/client.py", line 141, in get_doclist
auth_token=auth_token, **kwargs)
File "/base/data/home/apps/mustrun2sun/1.341947133742569880/gdata/client.py", line 635, in get_feed
**kwargs)
File "/base/data/home/apps/mustrun2sun/1.341947133742569880/gdata/client.py", line 308, in request
response, Unauthorized)
Unauthorized: Unauthorized - Server responded with: 401, <HTML>
<HEAD>
<TITLE>Token invalid - Invalid AuthSub token.</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Token invalid - Invalid AuthSub token.</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
Also, since this is hard w/o any source code, below is the relevant code:
import gdata.auth
import gdata.gauth
import gdata.docs.client
import gdata.docs.data
import gdata.docs.service
import gdata.alt.appengine
from aeoid import middleware, users
class GetOauthToken(webapp.RequestHandler):
def get(self):
user_id = users.get_current_user().user_id()
saved_request_token = gdata.gauth.AeLoad("tmp_"+user_id)
gdata.gauth.AeDelete ("tmp_" + user_id)
request_token = gdata.gauth.AuthorizeRequestToken(saved_request_token, self.request.uri)
#upgrade the token
access_token = client.GetAccessToken(request_token)
#save the upgraded token
gdata.gauth.AeSave(access_token, user_id)
self.redirect('/test')
class Test(webapp.RequestHandler):
def get(self):
TOKEN = gdata.gauth.AeLoad(users.get_current_user().user_id())
if TOKEN:
client = gdata.docs.client.DocsClient(source=SETTINGS['APP_NAME'])
client.auth_token = gdata.gauth.AeLoad(users.get_current_user().user_id()) #could try to put back as TOKEN?
self.response.out.write('moo baby')
client.ssl = True
feed = client.GetDocList(auth_token=gdata.gauth.AeLoad(users.get_current_user().user_id())) #auth_token=TOKEN
self.response.out.write(feed)
self.response.out.write('moo boobob')
self.response.headers['Content-Type'] = 'text/plain'
for entry in feed.entry:
self.response.out.writeln(entry.title.text)
else:
# Get unauthorized request token
gdata.gauth.AeDelete(users.get_current_user().user_id())
client = gdata.docs.client.DocsClient(source=SETTINGS['APP_NAME'])
client.ssl = True # Force communication through HTTPS
oauth_callback_url = ('http://%s/get_oauth_token' %
self.request.host)
request_token = client.GetOAuthToken(
SETTINGS['SCOPES'], oauth_callback_url, SETTINGS['CONSUMER_KEY'],
consumer_secret=SETTINGS['CONSUMER_SECRET'])
gdata.gauth.AeSave(request_token, "tmp_"+users.get_current_user().user_id())
# Authorize request token
domain = None#'cornellsun.com'
self.redirect(str(request_token.generate_authorization_url(google_apps_domain=domain)))
I've been looking high and low on the web for an answer & I have not been able to find one.
A:
I have a working python App Engine app that uses OpenID, and OAuth to get your google contacts:
http://github.com/sje397/Chess
It is running at:
http://your-move.appspot.com
Note that Aeoid is not needed anymore, since App Engine has built-in OpenID support.
A:
I just found out wasting a couple of hours, that you get a 401 also if the URL is not correct.
In my example, I was doing
.../buzz/v1/activities/@me/@self**?&**alt=json
Instead of
.../buzz/v1/activities/@me/@self**?**alt=json
A:
I have personally not worked with OAuth, but a few things I noticed that may (or may not) help:
The 401 error is likely an HTTP 401 error, which means that the url was valid but required authentication. This obviously is explained by the failed OAuth attempt, but it also might be important to redirect users who are not logged in to another page.
The error is occurring when you assign your feed variable. Is the auth_token parameter simply supposed to be a username?
3.You are using the line.
gdata.gauth.AeLoad(users.get_current_user().user_id())
frequently. Even though it might not be related to your auth problems, you would probably be better off making this query once and storing it in a variable. Then when you need it again, access it that way. It will improve the speed of your application.
Again, I apologize that I have had no specific OAuth experience. I just tried to scan and find some things that may spark you onto the right path.
| Oauth + Aeoid +Python + Google App Engine + Google documents | I am trying to complete a story assignment system for my school newspaper in Google App Engine. It'll track deadlines for writers, allow writers to pick up stories, and give an "at a glance" view of the weeks stories. My partner and I are trying to fully integrate it with our newspapers Google Apps installation. Oh, and we have to use 3 legged Oauth because we don't have Google Apps Premier.
In that endeavor, I stumbled upon Aeoid and was able to follow the instructions to make federated login work. It's very cool!
Where I'm running into trouble is using Oauth to get a list of the users google documents. I have a test page set up here: mustrun.cornellsun.com/test. It is giving me errors - I've copied them at the bottom of this mail. I don't know if this has to do with my consumer secret (should I be using the key I get from google marketplace? or should I be using the key I get from the manage domains page?). Right now I'm using the key I got from the manage domains page
Also complicating this is that the actual appspot domain is mustrun2sun [].appspot[too new can't post more than one link].com, but I set it up in google apps so that only users from my domain can log in and also so that the app is deployed on my domain. (app is deployed as must[]run[].corn[]ellsun[].[]com & everything refers to it as such, even in the manage domains thing.)
I'm using GDClient 2.0 classes so I'm fairly sure that everything should work as planned... i.e. I'm not using the old service stuff or anything. I've used htt[]p:/[]/k[]ing[]yo-bachi.blog[]spot.c[]om/2010/05/gaego[]ogleoauth.ht[]ml as a bit of a template for my Oauth "dance" because the Google examples are out of date & use the old Google data 1.0 library - I think.
The error that I'm getting when I go to my test page is
Traceback (most recent call last):
File "/base/python_runtime/python_lib/versions/1/google/appengine/ext/webapp/__init__.py", line 511, in __call__
handler.get(*groups)
File "/base/data/home/apps/mustrun2sun/1.341947133742569880/main.py", line 170, in get
feed = client.GetDocList(auth_token=gdata.gauth.AeLoad(users.get_current_user().user_id())) #auth_token=TOKEN
File "/base/data/home/apps/mustrun2sun/1.341947133742569880/gdata/docs/client.py", line 141, in get_doclist
auth_token=auth_token, **kwargs)
File "/base/data/home/apps/mustrun2sun/1.341947133742569880/gdata/client.py", line 635, in get_feed
**kwargs)
File "/base/data/home/apps/mustrun2sun/1.341947133742569880/gdata/client.py", line 308, in request
response, Unauthorized)
Unauthorized: Unauthorized - Server responded with: 401, <HTML>
<HEAD>
<TITLE>Token invalid - Invalid AuthSub token.</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1>Token invalid - Invalid AuthSub token.</H1>
<H2>Error 401</H2>
</BODY>
</HTML>
Also, since this is hard w/o any source code, below is the relevant code:
import gdata.auth
import gdata.gauth
import gdata.docs.client
import gdata.docs.data
import gdata.docs.service
import gdata.alt.appengine
from aeoid import middleware, users
class GetOauthToken(webapp.RequestHandler):
def get(self):
user_id = users.get_current_user().user_id()
saved_request_token = gdata.gauth.AeLoad("tmp_"+user_id)
gdata.gauth.AeDelete ("tmp_" + user_id)
request_token = gdata.gauth.AuthorizeRequestToken(saved_request_token, self.request.uri)
#upgrade the token
access_token = client.GetAccessToken(request_token)
#save the upgraded token
gdata.gauth.AeSave(access_token, user_id)
self.redirect('/test')
class Test(webapp.RequestHandler):
def get(self):
TOKEN = gdata.gauth.AeLoad(users.get_current_user().user_id())
if TOKEN:
client = gdata.docs.client.DocsClient(source=SETTINGS['APP_NAME'])
client.auth_token = gdata.gauth.AeLoad(users.get_current_user().user_id()) #could try to put back as TOKEN?
self.response.out.write('moo baby')
client.ssl = True
feed = client.GetDocList(auth_token=gdata.gauth.AeLoad(users.get_current_user().user_id())) #auth_token=TOKEN
self.response.out.write(feed)
self.response.out.write('moo boobob')
self.response.headers['Content-Type'] = 'text/plain'
for entry in feed.entry:
self.response.out.writeln(entry.title.text)
else:
# Get unauthorized request token
gdata.gauth.AeDelete(users.get_current_user().user_id())
client = gdata.docs.client.DocsClient(source=SETTINGS['APP_NAME'])
client.ssl = True # Force communication through HTTPS
oauth_callback_url = ('http://%s/get_oauth_token' %
self.request.host)
request_token = client.GetOAuthToken(
SETTINGS['SCOPES'], oauth_callback_url, SETTINGS['CONSUMER_KEY'],
consumer_secret=SETTINGS['CONSUMER_SECRET'])
gdata.gauth.AeSave(request_token, "tmp_"+users.get_current_user().user_id())
# Authorize request token
domain = None#'cornellsun.com'
self.redirect(str(request_token.generate_authorization_url(google_apps_domain=domain)))
I've been looking high and low on the web for an answer & I have not been able to find one.
| [
"I have a working python App Engine app that uses OpenID, and OAuth to get your google contacts:\nhttp://github.com/sje397/Chess\nIt is running at:\nhttp://your-move.appspot.com\nNote that Aeoid is not needed anymore, since App Engine has built-in OpenID support.\n",
"I just found out wasting a couple of hours, t... | [
3,
1,
0
] | [] | [] | [
"google_app_engine",
"google_docs",
"oauth",
"python"
] | stackoverflow_0002835908_google_app_engine_google_docs_oauth_python.txt |
Q:
Why is Loan undefined when type(self) works just fine?
The following code is being used by the admin to save a Loan object
import uuid
from django.db import models
from django.contrib.auth.models import User
from apps.partners.models import Agent
# Create your models here.
class Loan(models.Model):
""" This is our local info about the loan from the LOS """
guid = models.CharField(max_length=64, blank=True)
number = models.CharField(max_length=64, blank=True)
name = models.CharField(max_length=64)
address = models.CharField(max_length=128)
address2 = models.CharField(max_length=128, null=True, blank=True)
city = models.CharField(max_length=32)
state = models.CharField(max_length=2)
zipcode = models.CharField(max_length=9)
borrowers = models.ManyToManyField(User, related_name='loan_borrowers')
officers = models.ManyToManyField(Agent, related_name='loan_officers')
def __unicode__(self):
return "%s %s, %s %s" % (self.address, self.city, self.state, self.zipcode)
def save(self, force_insert=False, force_update=False, using=None):
""" Adds a GUID if one is not present """
if self.guid == None:
self.guid = uuid.uuid4().hex
super(Loan, self).save(force_insert, force_update, using)
When I get to the super line, I get:
TypeError: super() argument 1 must be type, not None
The save call is made from options.py line 597 and at that point obj is known to be a Loan object.
if I replace the super() line with
super(type(self), self).save(force_insert, force_update, using)
all is well. What is going on here?
The rest of the file is:
class Need(models.Model):
from apps.public_portal.models import DocumentType
loan = models.ForeignKey(Loan, null=False, blank=False)
borrower = models.ForeignKey(User, null=False, blank=False)
doctype = models.ForeignKey(DocumentType, null=False, blank=False)
satisfied = models.DateTimeField(null=True, blank=True)
first_request = models.DateTimeField(auto_now_add=True)
last_request = models.DateTimeField(null=True, blank=True)
def __unicode__(self):
return "%s from %s for %s" % (self.doctype.name, self.borrower.get_full_name(), self.loan)
So I don't see how anything is binding Loan to None
A:
The Django developers offer a pattern for overriding the model save() method. Using that pattern, the implementation for your save() method should be:
def save(self, *args, **kwargs):
if self.guid == None:
self.guid = uuid.uuid4().hex
super(Blog, self).save(*args, **kwargs) # Call the "real" save() method.
Let me offer a different approach: use signals!
Instead of trying to override the save() method, use a pre-save signal to initialize the guid field prior to the record being inserted/updated. Add the following code to your model.py file:
def add_loan_guid( sender, instance, **kwargs ):
"""Ensure that a Loan always has a guid"""
if instance.guid == None:
instance.guid = uuid.uuid4().hex
pre_save.connect( add_loan_guid, sender=Loan )
Now, any time that a Loan object is saved, but before it is persisted to the database, add_loan_guid() will be called, and if the Loan instance has no guid set, a new one will be created.
A:
Something else is rebinding Loan to None. Look further down, or maybe in another module. Also, you don't want type(self) since that will fail for any grandchildren or further.
| Why is Loan undefined when type(self) works just fine? | The following code is being used by the admin to save a Loan object
import uuid
from django.db import models
from django.contrib.auth.models import User
from apps.partners.models import Agent
# Create your models here.
class Loan(models.Model):
""" This is our local info about the loan from the LOS """
guid = models.CharField(max_length=64, blank=True)
number = models.CharField(max_length=64, blank=True)
name = models.CharField(max_length=64)
address = models.CharField(max_length=128)
address2 = models.CharField(max_length=128, null=True, blank=True)
city = models.CharField(max_length=32)
state = models.CharField(max_length=2)
zipcode = models.CharField(max_length=9)
borrowers = models.ManyToManyField(User, related_name='loan_borrowers')
officers = models.ManyToManyField(Agent, related_name='loan_officers')
def __unicode__(self):
return "%s %s, %s %s" % (self.address, self.city, self.state, self.zipcode)
def save(self, force_insert=False, force_update=False, using=None):
""" Adds a GUID if one is not present """
if self.guid == None:
self.guid = uuid.uuid4().hex
super(Loan, self).save(force_insert, force_update, using)
When I get to the super line, I get:
TypeError: super() argument 1 must be type, not None
The save call is made from options.py line 597 and at that point obj is known to be a Loan object.
if I replace the super() line with
super(type(self), self).save(force_insert, force_update, using)
all is well. What is going on here?
The rest of the file is:
class Need(models.Model):
from apps.public_portal.models import DocumentType
loan = models.ForeignKey(Loan, null=False, blank=False)
borrower = models.ForeignKey(User, null=False, blank=False)
doctype = models.ForeignKey(DocumentType, null=False, blank=False)
satisfied = models.DateTimeField(null=True, blank=True)
first_request = models.DateTimeField(auto_now_add=True)
last_request = models.DateTimeField(null=True, blank=True)
def __unicode__(self):
return "%s from %s for %s" % (self.doctype.name, self.borrower.get_full_name(), self.loan)
So I don't see how anything is binding Loan to None
| [
"The Django developers offer a pattern for overriding the model save() method. Using that pattern, the implementation for your save() method should be:\ndef save(self, *args, **kwargs):\n if self.guid == None:\n self.guid = uuid.uuid4().hex\n super(Blog, self).save(*args, **kwargs) # Call the \"real\"... | [
1,
0
] | [] | [] | [
"django",
"django_admin",
"django_models",
"python"
] | stackoverflow_0004047535_django_django_admin_django_models_python.txt |
Q:
Relational database design - Two Relations 1:1 or one 1:2?
This question is about how to design a SQL relationship. I am pretty newbie in this matter and I'd like to know the answers of (way) more experts guys...
I am currently migrating a ZopeDB (Object oriented) database to MySQL (relational) using MeGrok and SqlAlchemy (although I don't think that's really too relevant, since my question is more about designing a relationship in a relational database).
I have two classes related like this:
class Child(object):
def __init__(self):
self.field1 = "hello world"
class Parent(object):
def __init__(self):
self.child1 = Child()
self.child2 = Child()
The "Parent" class has two different instances of a Child() class. I am not even sure about how to treat this (two different 1:1 relationships or a 1:2 relationship).
Currently, I have this:
class Child(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("children_table")
id = Column("id", Integer, primary_key=True)
field1 = Column("field1", String(64)) #Irrelevant
def __init__(self):
self.field1 = "hello world"
class Parent(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("parent_table")
id = Column("id", Integer, primary_key=True)
child1_id = Column("child_1_id", Integer, ForeignKey("children_table.id"))
child2_id = Column("child_2_id", Integer, ForeignKey("children_table.id"))
child1 = relationship(Child,
primaryjoin = ("parent_table.child1_id == children_table.id")
)
child2 = relationship(Child,
primaryjoin = ("parent_table.child2_id == children_table.id")
)
Meaning... Ok, I store the two "children" ids as foreign keys in the Parent and retrieve the children itself using that information.
This is working fine, but I don't know if it's the most proper solution.
Or I could do something like:
class Child(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("children_table")
id = Column("id", Integer, primary_key=True)
parent_id = Column("id", Integer, ForeignKey("parent_table.id")) # New!
type = Column("type", ShortInteger) # New!
field1 = Column("field1", String(64)) #Irrelevant
def __init__(self):
self.field1 = "hello world"
class Parent(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("parent_table")
id = Column("id", Integer, primary_key=True)
child1 = relationship(
# Well... this I still don't know how to write it down,
# but it would be something like:
# Give me all the children whose "parent_id" is my own "id"
# AND their type == 1
# I'll deal with the joins and the actual implementation depending
# on your answer, guys
)
child2 = relationship(
# Would be same as above
# but selecting children whose type == 2
)
This may be good for adding new children to the parent class... If I add a "Parent.child3", I just need to create a new relationship very similar to the already existing ones.
The way I have it now would imply creating a new relationship AND adding a new foreign key to the parent.
Also, having a "parent" table with a bunch of foreign keys may not make it the best "parent" table in the world, right?
I'd like to know what people that know much more about databases think :)
Thank you.
PS: Related post? Question 3998545
A:
Expanded in Response to Comments
The issue is, you are thinking in the terms that you know (understandable), and you have the limitations of an OO database ... which would not be good to carry over into the Relational db. So for many reasons, it is best to simply identify the Entities and Relations, and to Normalise them. The method you use to call is easy to change and you will not be limited to only what you have now.
There are some good answers here, but even those are limited and incomplete. If you Normalise Parent and Child (being people, they will have many common columns), you get Person, with no duplicated columns.
People have "upward" relations to other people, their Parents, but that is context, not the fact that the Parent exists as a Person first (and you can have more than two if you like). People also have "downward" relations to their Children, also contextual. The limitation of two children per Parent is absurd (you may have to inspect your methods/classes: I suspect one is an "upward" navigation and the other is "downward"). And you do not want to have to store the relations as duplicates (once that Fred is a father of Sally; twice that Sally is a child of Fred), that single fact exists in a single row, which can be interpreted Parent⇢Child or Parent⇠Child.
This requirement has come up in many questions, therefore I am using a single generic, but detailed, illustration. The model defines any tree structure that needs to be walked up or down, handled by simple recursion. It is called a Bill of Materials structure, originally created for inventory control systems, and can be applied to any tree structure requirement. It is Fifth Normal Form; no duplicate columns; no Update Anomalies.
Bill of Materials
For Assemblies and Components, which would have many common columns, they are Normalised into Part; whether they are Assemblies or Components is contextual, and these contextual columns are located in the Associative (many-to-many) table.
Two Relations 1:1 or one 1:2 ?
Actually, it is two times 1::n.
Ordinals, or Ranking, is explicit in the Primary Key (chronological order). If some other ordinal is required, simply add a column to the Associative table. better yet, it is truly a derived column, so compute it at runtime from current values.
A:
This is probably a little out of context, since I use none of the things you've mentioned - but as far as the general design goes, here are a couple ideas:
Keep relationships based on common types: has_one, has_many, belongs_to, has_and_belongs_to_many.
With children, it's better to not specify N number of children explicitly; either there are none, one, or there could potentially be many. Thus your model declarations of child1 and child2 would be replaced by a single property - an array containing children.
To be totally honest, I don't know how well that fits in with what you're using. However, that's generally how relationships work in an ORM sense. So, based on this:
If a model belongs to another (it has a foreign key for another table), it would have a parent [sic] property with a reference to the parent object
If a model has one model that belongs to it (the other model has a foreign key to the first model's table), it would have a child [sic] property with a reference to the child object
If a model has many models that belong to it (many other models have foreign keys to the first model's table), it would have a children [sic] property that is an array of references to child objects
If a model has and belongs to many other models... you might want to consider using both parents and children properties, or something similar; nomenclature is less important than you having access to a group of models that it belongs to, and another group of models that belong to it.
Sorry if that's totally unhelpful, but it might shed some light. HTH.
A:
I'll admit that I'm not too familiar with object databases, but in relational terms this is a straightforward one-to-many (optional) relationship.
create table parent (
id int PK,
otherField whatever
)
create table child (
id int PK,
parent_id int Fk,
otherField whatever
)
Obviously, that's not usable code as it stands....
I think this is similar to your second example. If you need to track the ordinal postion of the children in their relationships to the parent, you'd add a column to the child table such as:
create table child (
id int PK,
parent_id int Fk,
birth_order int,
otherField whatever
)
You'd have to be responsible for managing that field at teh application level, it's not something you can expect the DBMS to do for you.
I called it an optional relationship on the assumption that childless parents can exist--if that's not true, it becomes a required relationship logically, though you'd still have to let the DBMS create a new parent record childlessly, then grab its id to create the child--and once again manage the requirement at the application level.
| Relational database design - Two Relations 1:1 or one 1:2? | This question is about how to design a SQL relationship. I am pretty newbie in this matter and I'd like to know the answers of (way) more experts guys...
I am currently migrating a ZopeDB (Object oriented) database to MySQL (relational) using MeGrok and SqlAlchemy (although I don't think that's really too relevant, since my question is more about designing a relationship in a relational database).
I have two classes related like this:
class Child(object):
def __init__(self):
self.field1 = "hello world"
class Parent(object):
def __init__(self):
self.child1 = Child()
self.child2 = Child()
The "Parent" class has two different instances of a Child() class. I am not even sure about how to treat this (two different 1:1 relationships or a 1:2 relationship).
Currently, I have this:
class Child(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("children_table")
id = Column("id", Integer, primary_key=True)
field1 = Column("field1", String(64)) #Irrelevant
def __init__(self):
self.field1 = "hello world"
class Parent(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("parent_table")
id = Column("id", Integer, primary_key=True)
child1_id = Column("child_1_id", Integer, ForeignKey("children_table.id"))
child2_id = Column("child_2_id", Integer, ForeignKey("children_table.id"))
child1 = relationship(Child,
primaryjoin = ("parent_table.child1_id == children_table.id")
)
child2 = relationship(Child,
primaryjoin = ("parent_table.child2_id == children_table.id")
)
Meaning... Ok, I store the two "children" ids as foreign keys in the Parent and retrieve the children itself using that information.
This is working fine, but I don't know if it's the most proper solution.
Or I could do something like:
class Child(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("children_table")
id = Column("id", Integer, primary_key=True)
parent_id = Column("id", Integer, ForeignKey("parent_table.id")) # New!
type = Column("type", ShortInteger) # New!
field1 = Column("field1", String(64)) #Irrelevant
def __init__(self):
self.field1 = "hello world"
class Parent(rdb.Model):
rdb.metadata(metadata)
rdb.tablename("parent_table")
id = Column("id", Integer, primary_key=True)
child1 = relationship(
# Well... this I still don't know how to write it down,
# but it would be something like:
# Give me all the children whose "parent_id" is my own "id"
# AND their type == 1
# I'll deal with the joins and the actual implementation depending
# on your answer, guys
)
child2 = relationship(
# Would be same as above
# but selecting children whose type == 2
)
This may be good for adding new children to the parent class... If I add a "Parent.child3", I just need to create a new relationship very similar to the already existing ones.
The way I have it now would imply creating a new relationship AND adding a new foreign key to the parent.
Also, having a "parent" table with a bunch of foreign keys may not make it the best "parent" table in the world, right?
I'd like to know what people that know much more about databases think :)
Thank you.
PS: Related post? Question 3998545
| [
"Expanded in Response to Comments\nThe issue is, you are thinking in the terms that you know (understandable), and you have the limitations of an OO database ... which would not be good to carry over into the Relational db. So for many reasons, it is best to simply identify the Entities and Relations, and to Norma... | [
4,
1,
1
] | [] | [] | [
"database_design",
"modeling",
"python",
"relational_database",
"sqlalchemy"
] | stackoverflow_0004055332_database_design_modeling_python_relational_database_sqlalchemy.txt |
Q:
Any framework for PHP, as effective as Django for Python?
I am using python with django. There I can simply make form from models and also it had builtin Admin.
I am eager to know corresponding framework for PHP with all this facilities.
I have encountered lot some similar questions like this, but they had not compared the frameworks with django. Experts Please Suggest.
A:
I'd try Symfony.
What you're referring to sounds like "scaffolding"
A:
I've had good success with Zend in the past. It has a lot of functionality in its libraries and it is all completely decoupled, so you can use whichever parts best fit your task, leaving out other things all together.
A:
It doesn't have built in admin, but I like CodeIgniter. It really gives you freedom with your code without getting in the way.
A:
I like Yii. It's based on the Model-View-Controller pattern, like most of the other PHP frameworks mentioned here. It uses templates, can do scaffolding, etc...
A:
Another one that once saved my ass in a project with close deadline was CakePHP
| Any framework for PHP, as effective as Django for Python? | I am using python with django. There I can simply make form from models and also it had builtin Admin.
I am eager to know corresponding framework for PHP with all this facilities.
I have encountered lot some similar questions like this, but they had not compared the frameworks with django. Experts Please Suggest.
| [
"I'd try Symfony.\nWhat you're referring to sounds like \"scaffolding\"\n",
"I've had good success with Zend in the past. It has a lot of functionality in its libraries and it is all completely decoupled, so you can use whichever parts best fit your task, leaving out other things all together.\n",
"It doesn't ... | [
3,
2,
2,
2,
0
] | [] | [] | [
"django",
"frameworks",
"php",
"python"
] | stackoverflow_0004030026_django_frameworks_php_python.txt |
Q:
Why is this C method segfaulting?
I'm writing an immutable linked list class in C, but one method is mysteriously segfaulting. The code is intended to be roughly equivalent to this:
class PList(object):
def __init__(self, first, rest=None):
self.first = first
self.rest = rest
def cons(self, item):
return PList(item, self)
Here is my code:
#include <Python.h>
#include <structmember.h>
static PyTypeObject PListType;
typedef struct PListStruct{
PyObject_HEAD
PyObject *first;
struct PListStruct *rest;
} PList;
static PyMemberDef plist_members[] = {
{"first", T_OBJECT_EX, offsetof(PList, first), READONLY, "First element"},
{"rest", T_OBJECT_EX, offsetof(PList, rest), READONLY, "Rest of the list"},
{NULL}
};
static PyObject *
PList_cons(PList *self, PyObject *arg)
{
PList *new_list = PyObject_CallFunctionObjArgs(&PListType, arg, self);
Py_INCREF(new_list);
return new_list;
}
static PyMethodDef plist_methods[] = {
{"cons", (PyCFunction)PList_cons, METH_O, "Add an item to the list"},
{NULL}
};
static void PList_dealloc(PList *self)
{
Py_XDECREF(self->first);
Py_XDECREF(self->rest);
self->ob_type->tp_free((PyObject*)self);
}
static int
PList_init(PList *self, PyObject *args, PyObject *kwds)
{
PyObject *first=NULL, *rest=NULL, *tmp;
static char *kwlist[] = {"first", "rest", NULL};
if (! PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist,
&first, &rest))
return -1;
if (first){
tmp = self->first;
Py_INCREF(first);
self->first = first;
Py_XDECREF(tmp);
}
if (rest) {
tmp = self->rest;
Py_INCREF(rest);
self->rest = rest;
Py_XDECREF(tmp);
}
else {
tmp = self->rest;
Py_INCREF(Py_None);
self->rest = Py_None;
Py_XDECREF(tmp);
}
return 0;
}
static PyTypeObject PListType= {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"pysistence.persistent_list.PList", /*tp_name*/
sizeof(PList), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)PList_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"Persistent list", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
plist_methods, /* tp_methods */
plist_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)PList_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};
#ifndef PyMODINIT_FUNC
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
initpersistent_list(void)
{
PyObject *m;
PListType.tp_new = PyType_GenericNew;
if (PyType_Ready(&PListType) < 0)
return;
m = Py_InitModule3("pysistence.persistent_list", 0,
"Docstring");
Py_INCREF(&PListType);
PyModule_AddObject(m, "PList", (PyObject*)&PListType);
}
If I run this code, it segfaults on the last line:
from pysistence.persistent_list import PList
p = PList(1)
p = PList(2, p)
p = p.cons(3)
I'm sure I'm just doing something stupid, but I don't see what it is. Is there something I'm missing?
A:
I am reading from the documentation:
PyObject* PyObject_CallFunctionObjArgs(PyObject *callable, ..., NULL)
Return value: New reference.
Call a callable Python object callable, with a variable number of PyObject* arguments. The arguments are provided as a variable number of parameters followed by NULL. Returns the result of the call on success, or NULL on failure.
You are missing the NULL value at the end.
Edit: Ho and you also want to check if the function returns NULL in case of memory failure
| Why is this C method segfaulting? | I'm writing an immutable linked list class in C, but one method is mysteriously segfaulting. The code is intended to be roughly equivalent to this:
class PList(object):
def __init__(self, first, rest=None):
self.first = first
self.rest = rest
def cons(self, item):
return PList(item, self)
Here is my code:
#include <Python.h>
#include <structmember.h>
static PyTypeObject PListType;
typedef struct PListStruct{
PyObject_HEAD
PyObject *first;
struct PListStruct *rest;
} PList;
static PyMemberDef plist_members[] = {
{"first", T_OBJECT_EX, offsetof(PList, first), READONLY, "First element"},
{"rest", T_OBJECT_EX, offsetof(PList, rest), READONLY, "Rest of the list"},
{NULL}
};
static PyObject *
PList_cons(PList *self, PyObject *arg)
{
PList *new_list = PyObject_CallFunctionObjArgs(&PListType, arg, self);
Py_INCREF(new_list);
return new_list;
}
static PyMethodDef plist_methods[] = {
{"cons", (PyCFunction)PList_cons, METH_O, "Add an item to the list"},
{NULL}
};
static void PList_dealloc(PList *self)
{
Py_XDECREF(self->first);
Py_XDECREF(self->rest);
self->ob_type->tp_free((PyObject*)self);
}
static int
PList_init(PList *self, PyObject *args, PyObject *kwds)
{
PyObject *first=NULL, *rest=NULL, *tmp;
static char *kwlist[] = {"first", "rest", NULL};
if (! PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist,
&first, &rest))
return -1;
if (first){
tmp = self->first;
Py_INCREF(first);
self->first = first;
Py_XDECREF(tmp);
}
if (rest) {
tmp = self->rest;
Py_INCREF(rest);
self->rest = rest;
Py_XDECREF(tmp);
}
else {
tmp = self->rest;
Py_INCREF(Py_None);
self->rest = Py_None;
Py_XDECREF(tmp);
}
return 0;
}
static PyTypeObject PListType= {
PyObject_HEAD_INIT(NULL)
0, /*ob_size*/
"pysistence.persistent_list.PList", /*tp_name*/
sizeof(PList), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor)PList_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash */
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
"Persistent list", /* tp_doc */
0, /* tp_traverse */
0, /* tp_clear */
0, /* tp_richcompare */
0, /* tp_weaklistoffset */
0, /* tp_iter */
0, /* tp_iternext */
plist_methods, /* tp_methods */
plist_members, /* tp_members */
0, /* tp_getset */
0, /* tp_base */
0, /* tp_dict */
0, /* tp_descr_get */
0, /* tp_descr_set */
0, /* tp_dictoffset */
(initproc)PList_init, /* tp_init */
0, /* tp_alloc */
0, /* tp_new */
};
#ifndef PyMODINIT_FUNC
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
initpersistent_list(void)
{
PyObject *m;
PListType.tp_new = PyType_GenericNew;
if (PyType_Ready(&PListType) < 0)
return;
m = Py_InitModule3("pysistence.persistent_list", 0,
"Docstring");
Py_INCREF(&PListType);
PyModule_AddObject(m, "PList", (PyObject*)&PListType);
}
If I run this code, it segfaults on the last line:
from pysistence.persistent_list import PList
p = PList(1)
p = PList(2, p)
p = p.cons(3)
I'm sure I'm just doing something stupid, but I don't see what it is. Is there something I'm missing?
| [
"I am reading from the documentation:\n\nPyObject* PyObject_CallFunctionObjArgs(PyObject *callable, ..., NULL)\n Return value: New reference.\n\nCall a callable Python object callable, with a variable number of PyObject* arguments. The arguments are provided as a variable number of parameters followed by NULL. R... | [
4
] | [] | [] | [
"c",
"python",
"python_c_extension",
"segmentation_fault"
] | stackoverflow_0004057611_c_python_python_c_extension_segmentation_fault.txt |
Q:
confused about python subprocess inside for loop
I am trying to automate some big data file processing using python.
A lop of the processing is chained , i.e script1 writes a file , that is then processed by script2 , then script2's output by script3 etc.
I am using the subprocess module in a threaded context.
I have one class that creates tuples of chained scripts
("scr1.sh","scr2.sh","scr3.sh").
Then another class that uses a call like
for script in scriplist:
subprocess.call(script)
My question is that in this for loop , is each script only called after subprocess.call(script1) returns a successful retcode?.
Or is it that all three get called right after one another since I am using subprocess.call, Without using "sleep" or "wait", I want to make sure that the second script only starts after the first one is over.
edit: The pydoc says
"subprocess.call(*popenargs, **kwargs)
Run command with arguments. Wait for command to complete, then return the returncode attribute."
So in the for loop (above) , does it wait for each retcode before iterating to the next script.
I am new to threading . I am attaching the stripped-down code for the class that runs the analysis here. The subprocess.call loop is part of this class.
class ThreadedDataProcessor(Thread):
def __init__(self, in_queue, out_queue):
# Uses Queue
Thread.__init__(self)
self.in_queue = in_queue
self.out_queue = out_queue
def run(self):
while True:
path = self.in_queue.get()
if path is None:
break
myprocessor = ProcessorScriptCreator(path)
scrfiles = myprocessor.create_and_return_shell_scripts()
for index,file in enumerate(scrfiles):
subprocess.call([file])
print "CALLED%s%s" % (index,file) *5
#report(myfile.describe())
#report("Done %s" % path)
self.out_queue.put(path)
in_queue = Queue()
A:
The loop will serially call each script, wait until it completes, and then call the next one regardless of success or failure of the previous call. You probably want to say:
try:
map(subprocess.check_call, script_list)
except Exception, e:
# failed script
A new thread will start with each call to run, and also end when run is done. You iterate over the script with subprocess within one thread.
You should make sure that each set of calls in each thread are not going to impact other calls from other threads. For example trying to read and write to the same file from a script call in multiple threads at the same time.
| confused about python subprocess inside for loop | I am trying to automate some big data file processing using python.
A lop of the processing is chained , i.e script1 writes a file , that is then processed by script2 , then script2's output by script3 etc.
I am using the subprocess module in a threaded context.
I have one class that creates tuples of chained scripts
("scr1.sh","scr2.sh","scr3.sh").
Then another class that uses a call like
for script in scriplist:
subprocess.call(script)
My question is that in this for loop , is each script only called after subprocess.call(script1) returns a successful retcode?.
Or is it that all three get called right after one another since I am using subprocess.call, Without using "sleep" or "wait", I want to make sure that the second script only starts after the first one is over.
edit: The pydoc says
"subprocess.call(*popenargs, **kwargs)
Run command with arguments. Wait for command to complete, then return the returncode attribute."
So in the for loop (above) , does it wait for each retcode before iterating to the next script.
I am new to threading . I am attaching the stripped-down code for the class that runs the analysis here. The subprocess.call loop is part of this class.
class ThreadedDataProcessor(Thread):
def __init__(self, in_queue, out_queue):
# Uses Queue
Thread.__init__(self)
self.in_queue = in_queue
self.out_queue = out_queue
def run(self):
while True:
path = self.in_queue.get()
if path is None:
break
myprocessor = ProcessorScriptCreator(path)
scrfiles = myprocessor.create_and_return_shell_scripts()
for index,file in enumerate(scrfiles):
subprocess.call([file])
print "CALLED%s%s" % (index,file) *5
#report(myfile.describe())
#report("Done %s" % path)
self.out_queue.put(path)
in_queue = Queue()
| [
"The loop will serially call each script, wait until it completes, and then call the next one regardless of success or failure of the previous call. You probably want to say:\ntry:\n map(subprocess.check_call, script_list)\nexcept Exception, e:\n # failed script\n\nA new thread will start with each call to run, ... | [
2
] | [] | [] | [
"multithreading",
"python",
"queue"
] | stackoverflow_0004029782_multithreading_python_queue.txt |
Q:
Pylons app deployment with privately developed dependencies
In my organization, we have a couple of internally developed Python packages. For sake of example, let's call them Foo and Bar. Both are developed in separate Git repositories. Foo is a Pylons application that uses certain library functions from Bar. Neither is publicly distributed.
When we deploy Foo, we typically export the latest revision from source control and run setup.py develop within our virtualenv. This works okay.
The problem is that we'll need some way of distributing Bar for every environment where we deploy Foo. We obviously can't put 'Bar' in setup.py's install_requires (as easy_install won't find be able to find it on any website). I can't find any way of automatically obtaining/installing privately developed dependencies.
Is there an easier to way to manage this? I feel like I'm missing the point of Python packaging and distribution.
A:
You can create a package repository. The steps are basically:
Create an egg with setup.py bdist_egg
Copy the created egg from dist to a directory served by Apache
Add the url to the directory exposed by Apache to the easy_install command with the -f switch
Note that Apache is not necessarily required, but it automatically generates a directory listing that easy_install can deal with.
If you are using buildout, there are config options to do the same thing as -f and I am pretty sure there is something you can use in pip as well.
A:
When using setuptools, in setup.py you can specify HTTP, FTP and SVN locations where easy_install should look for packages:
http://peak.telecommunity.com/DevCenter/setuptools#dependencies-that-aren-t-in-pypi
You can either publish Bar in some "secret" location, or, I haven't tried it but maybe HTTP basic auth works:
setup(
...
dependency_links = [
"http://user:pass@example.com/private-repository/"
],
)
A:
At my work we use setuptools to create packages specific to the OS. We happen to use RedHat so we call bdist_rpm to create rpm package. We find that works better than eggs because we can do dependency management in the packages for both python and non-python libs.
We create the rpms on our continuous integration machine and the move them to a YUM repo where they can be pushed out via a YUM update or upgrade.
| Pylons app deployment with privately developed dependencies | In my organization, we have a couple of internally developed Python packages. For sake of example, let's call them Foo and Bar. Both are developed in separate Git repositories. Foo is a Pylons application that uses certain library functions from Bar. Neither is publicly distributed.
When we deploy Foo, we typically export the latest revision from source control and run setup.py develop within our virtualenv. This works okay.
The problem is that we'll need some way of distributing Bar for every environment where we deploy Foo. We obviously can't put 'Bar' in setup.py's install_requires (as easy_install won't find be able to find it on any website). I can't find any way of automatically obtaining/installing privately developed dependencies.
Is there an easier to way to manage this? I feel like I'm missing the point of Python packaging and distribution.
| [
"You can create a package repository. The steps are basically:\n\nCreate an egg with setup.py bdist_egg\nCopy the created egg from dist to a directory served by Apache\nAdd the url to the directory exposed by Apache to the easy_install command with the -f switch\n\nNote that Apache is not necessarily required, but ... | [
2,
1,
0
] | [] | [] | [
"deployment",
"distutils",
"python",
"setuptools"
] | stackoverflow_0004005009_deployment_distutils_python_setuptools.txt |
Q:
Why store sessions on the server instead of inside a cookie?
I have been using Flask for some time now and I am really enjoying the framework. One thing that I fail to understand is that in almost all other places they talk about storing the session on the server and the session id on the client, which would then identify the session. However after using flask, I dont feel the need to do so. Saving the session as a cookie on the client cryptographically serves my purpose and seems quite secure too. The only thing being I am unable to encrypt the session keys for eg:
session['life'] = 'the great one'
would appear as
life='gfhjfkjdfa some encryption kj'
in the cookie saved on the client. But how would that matter as it is still encrypted.
I am sure that people here know things much better than I do, so request someone to please clarify :-)
A:
Even if your data is encrypted, the user could still roll back their cookie to a previous state (unless you start encoding one-time IDs etc)
e.g. cookie says the user has 100 credits, user spends 100 credits, they get a new cookie saying they have 0 credits. They could then restore their previous cookie (with 100 credits).
Depending how you encrypt the cookie, the user may also be able to delete keys, insert bogus data etc too.
A:
If the session data is needed at the server, it makes sense to store it at the server. It keeps down the data bulk sent back and forth from the client. Also, cookies have a limit on the amount of data they can store.
A:
In addition to the points already mentioned above
Users can disable cookies using their browser settings.
A lot of antivirus scanners also scan and flag cookies as a risk because of which which can also result in cookies not being allowed on the users computer.
Cookies can be deleted by the user even in the middle of his session. (In fact, i inadvertently did that the other day when one my PC scans listed the tracking cookies...and i just clicked "Clean" and they were all gone). In case the user happens to delete the cookies, the users state will be lost.
If you use cookies to manage the entire state, you are always dependant on the client environment and its settings. In as such, you will probably atleast need a fall back mechanism in case the cookies are deleted / disabled etc in order for your application to work correctly.
A:
The SecureCookie implementation Flask uses does not encrypt the values. The only thing that is being ensured is that the user cannot modify the cookie without knowing the secret used by the application.
| Why store sessions on the server instead of inside a cookie? | I have been using Flask for some time now and I am really enjoying the framework. One thing that I fail to understand is that in almost all other places they talk about storing the session on the server and the session id on the client, which would then identify the session. However after using flask, I dont feel the need to do so. Saving the session as a cookie on the client cryptographically serves my purpose and seems quite secure too. The only thing being I am unable to encrypt the session keys for eg:
session['life'] = 'the great one'
would appear as
life='gfhjfkjdfa some encryption kj'
in the cookie saved on the client. But how would that matter as it is still encrypted.
I am sure that people here know things much better than I do, so request someone to please clarify :-)
| [
"Even if your data is encrypted, the user could still roll back their cookie to a previous state (unless you start encoding one-time IDs etc)\ne.g. cookie says the user has 100 credits, user spends 100 credits, they get a new cookie saying they have 0 credits. They could then restore their previous cookie (with 100... | [
19,
8,
7,
2
] | [] | [] | [
"cookies",
"flask",
"python",
"session"
] | stackoverflow_0003948975_cookies_flask_python_session.txt |
Q:
In Python, how would you write a regex that matches the following?
The string contains one or more "@" symbols. One or more of those symbols must have a character after it (not a space).
A:
import re
my_regex = re.compile(r'@\S+')
The \S class matches any non-whitespace character. If you'd prefer only alphanumeric characters, you might want to use \w instead.
Then, if you wanted to get all of the instances where it matched:
for match in my_regex.finditer(string_to_search):
# Do something with the MatchObject in 'match'
More details on finditer are available here: http://docs.python.org/library/re.html#re.finditer
A:
import re
pattern = re.compile(r'@+\S+')
This pattern follows the question's spec more closely: "one or more "@" symbols"
| In Python, how would you write a regex that matches the following? | The string contains one or more "@" symbols. One or more of those symbols must have a character after it (not a space).
| [
"import re\nmy_regex = re.compile(r'@\\S+')\n\nThe \\S class matches any non-whitespace character. If you'd prefer only alphanumeric characters, you might want to use \\w instead.\nThen, if you wanted to get all of the instances where it matched:\nfor match in my_regex.finditer(string_to_search):\n # Do somethin... | [
5,
0
] | [] | [] | [
"python",
"regex",
"string"
] | stackoverflow_0004057089_python_regex_string.txt |
Q:
Check if string contains one value or another, syntax error?
I'm coming from a javascript backend to Python and I'm running into a basic but confusing problem
I have a string that can contain a value of either 'left', 'center', or 'right'. I'm trying to test if the variable contains either 'left' or 'right'.
In js its easy:
if( str === 'left' || str === 'right' ){}
However, in python I get a syntax error with this:
if str == 'left' || str == 'right':
Why doesn't this work, and what's the right syntax?
A:
Python's logical OR operator is called or. There is no ||.
if string == 'left' or string == 'right':
## ^^
BTW, in Python this kind of test is usually written as:
if string in ('left', 'right'):
## in Python ≥3.1, also possible with set literal
## if string in {'left', 'right'}:
Also note that str is a built-in function in Python. You should avoid naming a variable that clashes with them.
| Check if string contains one value or another, syntax error? | I'm coming from a javascript backend to Python and I'm running into a basic but confusing problem
I have a string that can contain a value of either 'left', 'center', or 'right'. I'm trying to test if the variable contains either 'left' or 'right'.
In js its easy:
if( str === 'left' || str === 'right' ){}
However, in python I get a syntax error with this:
if str == 'left' || str == 'right':
Why doesn't this work, and what's the right syntax?
| [
"Python's logical OR operator is called or. There is no ||.\nif string == 'left' or string == 'right':\n## ^^\n\nBTW, in Python this kind of test is usually written as:\nif string in ('left', 'right'):\n\n## in Python ≥3.1, also possible with set literal\n## if string in {'left', 'right'}:\n\nAlso... | [
13
] | [] | [] | [
"if_statement",
"python"
] | stackoverflow_0004058085_if_statement_python.txt |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.